diff --git a/contiguous_array.py b/contiguous_array.py new file mode 100644 index 00000000..b12288b9 --- /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. + 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 \ No newline at end of file diff --git a/longest_palindrome.py b/longest_palindrome.py new file mode 100644 index 00000000..56ec1277 --- /dev/null +++ b/longest_palindrome.py @@ -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 \ No newline at end of file diff --git a/subarray-sum-equals-k.py b/subarray-sum-equals-k.py new file mode 100644 index 00000000..7d639772 --- /dev/null +++ b/subarray-sum-equals-k.py @@ -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 \ No newline at end of file