Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions contiguous_array.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
''' Time Complexity : O(n)
Space Complexity : O(n)
Did this code successfully run on Leetcode : Yes
Any problem you faced while coding this : No

Approach : Calculate the Running Sum at each index.
Key idea is, if 2 indices have same running sum, their subarray is always balanced.
'''

class Solution:
def findMaxLength(self, nums: List[int]) -> int:
rSum = 0
hashmap = {}
hashmap[0] = -1
result = 0
for i in range(len(nums)):
if nums[i] == 0:
rSum -= 1
else:
rSum +=1

if rSum in hashmap:
length = i - hashmap[rSum]
result = max(result, length)
else:
hashmap[rSum] = i
return result
22 changes: 22 additions & 0 deletions longest_palindrome.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
''' Time Complexity : O(n)
Space Complexity : O(n)
Did this code successfully run on Leetcode : Yes
Any problem you faced while coding this : No

Approach : if char already present in set, means we found 1 pair, increament count by 2,
else add char to set,
at end, it set has stil has element, we can add 1 to the count
'''
class Solution:
def longestPalindrome(self, s: str) -> int:
hashset=set()
count = 0
for c in s:
if c in hashset:
count += 2
hashset.remove(c)
else:
hashset.add(c)
if hashset:
count += 1
return count
21 changes: 21 additions & 0 deletions subarray-sum-equals-k.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
''' Time Complexity : O(n)
Space Complexity : O(n)
Did this code successfully run on Leetcode : Yes
Any problem you faced while coding this : No

Approach : Calculate the Running Sum at each index.
IF diff of Running Sum and k is already in hashmap, that means we have got subarray at that running sum
'''
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
result = 0
rSum = 0
hashmap = {}
hashmap[0] = 1
for i in range(len(nums)):
rSum += nums[i]
diff = rSum - k
if diff in hashmap:
result += hashmap[diff]
hashmap[rSum] = hashmap.get(rSum,0) + 1
return result