From 7aa99004fc6934ac9876de9a91105ef42cdba4bd Mon Sep 17 00:00:00 2001 From: nikhylw <1.nikhil.wani+nikhly@gmail.com> Date: Mon, 4 May 2026 22:30:43 +0530 Subject: [PATCH] add hashing-2 solutions (all 3) --- W2_3_409_longest_palindrome.py | 22 ++++++++++++++++++++++ W2_4_525_contiguous_array.py | 27 +++++++++++++++++++++++++++ W2_5_560_subarray_sum_equals_k.py | 22 ++++++++++++++++++++++ 3 files changed, 71 insertions(+) create mode 100644 W2_3_409_longest_palindrome.py create mode 100644 W2_4_525_contiguous_array.py create mode 100644 W2_5_560_subarray_sum_equals_k.py diff --git a/W2_3_409_longest_palindrome.py b/W2_3_409_longest_palindrome.py new file mode 100644 index 00000000..8ea143c4 --- /dev/null +++ b/W2_3_409_longest_palindrome.py @@ -0,0 +1,22 @@ +# Time complexity: O(N), where n is the length of characters in the string +# Space complexity: O(1) + + +class Solution: + def longestPalindrome(self, s: str) -> int: + hashset = set() + count = 0 + + for i in range(0, len(s)): + ch = s[i] + + if ch in hashset: + count = count + 2 + hashset.remove(ch) + else: + hashset.add(ch) + + if len(hashset) != 0: + count = count + 1 + + return count diff --git a/W2_4_525_contiguous_array.py b/W2_4_525_contiguous_array.py new file mode 100644 index 00000000..a506a2d7 --- /dev/null +++ b/W2_4_525_contiguous_array.py @@ -0,0 +1,27 @@ +#Time complexity: O(N) +#Space complexity: O(N) + +class Solution: + def findMaxLength(self, nums: List[int]) -> int: + + hashmap = {} + maxx = 0 + rsum = 0 + + hashmap[0] = -1 + + for i in range(len(nums)): + if nums[i] == 0: + rsum = rsum - 1 + else: + rsum = rsum + 1 + + if rsum not in hashmap: + hashmap[rsum] = i + else: + curr = i - hashmap[rsum] + maxx = max(maxx, curr) + + return maxx + + diff --git a/W2_5_560_subarray_sum_equals_k.py b/W2_5_560_subarray_sum_equals_k.py new file mode 100644 index 00000000..4dc7c12b --- /dev/null +++ b/W2_5_560_subarray_sum_equals_k.py @@ -0,0 +1,22 @@ +#Time complexity: O(n) +#Space complexity: O(n) + +class Solution: + def subarraySum(self, nums: List[int], k: int) -> int: + hashmap = dict() + hashmap[0] = 1 + rsum = 0 + count = 0 + + for i in range(0, len(nums)): + rsum = rsum + nums[i] + + if rsum - k in hashmap: + count = count + hashmap[rsum - k] + + if rsum not in hashmap: + hashmap[rsum] = 0 + + hashmap[rsum] = hashmap[rsum] + 1 + + return count