From e98461afd8ae167815c9e2d1bc361a53e9a534e9 Mon Sep 17 00:00:00 2001 From: sainaga00 Date: Wed, 11 Feb 2026 11:49:16 -0500 Subject: [PATCH] Hashing-2 --- contiguous.py | 27 +++++++++++++++++++++++++++ longestPalindrome.py | 30 ++++++++++++++++++++++++++++++ subarrayEqualsK.py | 24 ++++++++++++++++++++++++ 3 files changed, 81 insertions(+) create mode 100644 contiguous.py create mode 100644 longestPalindrome.py create mode 100644 subarrayEqualsK.py diff --git a/contiguous.py b/contiguous.py new file mode 100644 index 00000000..a0d7a1dc --- /dev/null +++ b/contiguous.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: Convert 0 to -1 and 1 to +1 and compute prefix sum. +# Store first occurrence of each prefix sum in hashmap to maximize length. + +class Solution: + def findMaxLength(self, nums: List[int]) -> int: + max_len = 0 + h_map = {} + c_sum = 0 + + for i in range(len(nums)): + if nums[i] == 0: + c_sum -= 1 + else: + c_sum += 1 + + if c_sum == 0: + max_len = i + 1 + elif c_sum in h_map: + max_len = max(max_len, i - h_map[c_sum]) + else: + h_map[c_sum] = i + + return max_len diff --git a/longestPalindrome.py b/longestPalindrome.py new file mode 100644 index 00000000..a87f47f1 --- /dev/null +++ b/longestPalindrome.py @@ -0,0 +1,30 @@ +# Time Complexity : O(n) +# Space Complexity : O(1) +# Did this code successfully run on Leetcode : Yes +# Any problem you faced while coding this : No +# Approach: Count frequency of each character. +# For even frequencies, use all occurrences. +# For odd frequencies, use (count - 1) to keep it even. +# If at least one odd frequency exists, we can place one character in the center. + +class Solution: + def longestPalindrome(self, s: str) -> int: + freq_cnt = [0] * 256 + + for i in s: + freq_cnt[ord(i)] += 1 + + max_cnt = 0 + has_odd = False + + for i in freq_cnt: + if i % 2 == 0: + max_cnt += i + else: + max_cnt += (i - 1) + has_odd = True + + if has_odd: + max_cnt += 1 + + return max_cnt diff --git a/subarrayEqualsK.py b/subarrayEqualsK.py new file mode 100644 index 00000000..0ab13137 --- /dev/null +++ b/subarrayEqualsK.py @@ -0,0 +1,24 @@ +# 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 prefix sum + hashmap. At each index, compute cumulative sum. +# Store frequency of each prefix sum to handle multiple matches. + +class Solution: + def subarraySum(self, nums: List[int], k: int) -> int: + h_map = {0: 1} + c_sum = 0 + res = 0 + + for i in nums: + c_sum += i + if (c_sum - k) in h_map: + res += h_map[c_sum - k] + + if c_sum not in h_map: + h_map[c_sum] = 1 + else: + h_map[c_sum] += 1 + + return res