diff --git a/contiguous-array.py b/contiguous-array.py new file mode 100644 index 00000000..1715fc6b --- /dev/null +++ b/contiguous-array.py @@ -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. +''' + +class Solution: + def findMaxLength(self, nums): + 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 \ No newline at end of file diff --git a/longest-palindrome.py b/longest-palindrome.py new file mode 100644 index 00000000..89be9aaa --- /dev/null +++ b/longest-palindrome.py @@ -0,0 +1,26 @@ +''' +Time Complexity : O(n) +Space Complexity : O(n) +Did this code successfully run on Leetcode : Yes +Any problem you faced while coding this : No +''' +class Solution: + def longestPalindrome(self, s: str) -> int: + freq = {} + for ch in s: + freq[ch] = freq.get(ch, 0) + 1 + + length = 0 + has_odd = False + + for count in freq.values(): + if count % 2 == 0: + length += count + else: + length += count - 1 + has_odd = True + + if has_odd: + length += 1 + + return length diff --git a/subarray-sum-equals-k.py b/subarray-sum-equals-k.py new file mode 100644 index 00000000..cbe1ac6f --- /dev/null +++ b/subarray-sum-equals-k.py @@ -0,0 +1,67 @@ +''' +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. +''' + +class Solution: + # def subarraySum(self, nums: List[int], k: int) -> int: + # cnt = 0 + # n = len(nums) + # for i in range(n): + # sm = 0 + # for j in range(i, n): + # sm += nums[j] + # if sm == k: + # cnt += 1 + + # return cnt + # def subarraySum(self, nums: List[int], k: int) -> int: + # hashmap = {} + # hashmap[0] = 1 + # cnt = 0 + # rsum = 0 + # for i in range(len(nums)): + # rsum += nums[i] + # if rsum - k in hashmap: + # cnt += hashmap.get(rsum - k) + + # hashmap[rsum] = hashmap.get(rsum, 0) + 1 + + # return cnt + def subarraySum(self, nums: List[int], k: int) -> int: + cnt = 0 + hashmap = {} + hashmap[0] = 1 + n = len(nums) + rsum = 0 + for i in range(n): + rsum += nums[i] + if rsum - k in hashmap: + cnt += hashmap.get(rsum - k) + + hashmap[rsum] = hashmap.get(rsum, 0) + 1 + + return cnt + + + + + + + + + + + + + + + + + + +