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
32 changes: 32 additions & 0 deletions Problem1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
'''
We use cumSum to keep track of weather a subarray has sum = k.
Then use hashmap to keep count of the cumSums so we know how many times
the cumSum has occured which eventually can be used to count subarrays.

For every cumSum we check if cumSum-k has occured and how many times in the hashmap.
Then we increment the count of cumSum in hashmap.

Time Complexity: O(n)
Space Complexity: O(n)
'''

class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
# If the first number is k
cumSumMap = {0: 1}
result = 0
cumSum = 0

for num in nums:
cumSum += num
if (cumSum-k) in cumSumMap:
result += cumSumMap[cumSum-k]

if cumSum not in cumSumMap:
cumSumMap[cumSum] = 0

cumSumMap[cumSum] += 1



return result
34 changes: 34 additions & 0 deletions Problem2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
'''
The logic is same as problem 1. If we see 0 as -1 then the cumSum will
be 0 for the subarray that has equal numbers of 0s and 1s.

Also the cumSum can be same for each subarray in the beginning and end if it has
equal numbers of 0s and 1s.

We check if the cumSum has apperead before in the hMap and store the earliest location
of a cumSum in order to get the max length.

When the cumSum is 0 then the length of the subarray will be equal to the index + 1,
hence we add 0: -1 to the hMap prior to the loop in order to cover this edge case.
Time Complexity: O(n)
Space complexity: O(n)
'''

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

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

if cumSum in cumSumMap:
maxLen = max(maxLen, i - cumSumMap[cumSum])
else:
cumSumMap[cumSum] = i

return maxLen
30 changes: 30 additions & 0 deletions Problem3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
'''
If there are 2 occurances of a char, we can make a palindrome using them.
So after every 2 occurances of any character we add 2 to the maxLength of palindrome.

Now a palindrome can have odd length if there is only one element in the middle which occurs only once in
the palindrome string.

So if there are any other characters which only occur once or for odd times we add 1 to the final result
as we can only use one of those remaining characters.

Time Complexity: O(n)
Space Complexity: O(n)
'''
class Solution:
def longestPalindrome(self, s: str) -> int:
charSet = set()
result = 0

for i in s:
if i in charSet:
result += 2
charSet.remove(i)

else:
charSet.add(i)

if len(charSet) != 0:
result += 1

return result