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 ContiguousArray.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 : Increment sum for every 1 and decrement for every 0.
# If same runningSum is encountered again, that subarray between those indices is balanced.
# Track the longest subarray using hashmap.

class Solution:
def findMaxLength(self, nums: List[int]) -> int:
runningSum, maxLen = 0, 0
runningSumToIndex = {0: -1}

for i, num in enumerate(nums):
if num == 0:
runningSum -= 1
else:
runningSum += 1

if runningSum in runningSumToIndex:
maxLen = max(maxLen, i - runningSumToIndex[runningSum])
else:
runningSumToIndex[runningSum] = i

return maxLen


24 changes: 24 additions & 0 deletions LongestPalindrome.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Time Complexity : O(n)
# Space Complexity : O(1) as max 52 characters are stored
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Approach : HashSet used to track characters that haven't formed a pair yet,
# Add 2 to the count when pair found and remove that char from the set.
# If set is not empty, we can put one in the center — so we add 1 to the total.

class Solution:
def longestPalindrome(self, s: str) -> int:
char_set = set()
count = 0

for ch in s:
if ch in char_set:
char_set.remove(ch)
count += 2
else:
char_set.add(ch)

if len(char_set) > 0:
count += 1

return count
25 changes: 25 additions & 0 deletions SubArraySumEqualsK.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# 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 : Use runningSum to keep track of the sum so far.
# Check if runningSum - k was seen before — if yes, we’ve found a valid subarray.
# Finally, we count how many times each running sum appeared using a hashmap.

class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
runningSum, count = 0, 0
runningSumToFreq = {0: 1}

for num in nums:
runningSum += num

if runningSum - k in runningSumToFreq:
count += runningSumToFreq[runningSum - k]


runningSumToFreq[runningSum] = runningSumToFreq.get(runningSum, 0) + 1

return count