From 759c09a612634b182ee81e8c6c38a727da1a92dc Mon Sep 17 00:00:00 2001 From: rbhargav0104 Date: Wed, 31 Dec 2025 18:36:41 +0530 Subject: [PATCH] Completed Hashing-2 --- contiguosarray.cpp | 28 ++++++++++++++++++++++++++++ longestpalindrome.cpp | 35 +++++++++++++++++++++++++++++++++++ subarraySum.cpp | 0 3 files changed, 63 insertions(+) create mode 100644 contiguosarray.cpp create mode 100644 longestpalindrome.cpp create mode 100644 subarraySum.cpp diff --git a/contiguosarray.cpp b/contiguosarray.cpp new file mode 100644 index 00000000..7d1e7199 --- /dev/null +++ b/contiguosarray.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + int findMaxLength(vector& nums) { + int n = nums.size(); + unordered_map map; + map[0] = -1;//added in order to handle subarrays that start from index 0 + int rSum = 0;//aka prefix sum + + int max = 0;//stores the maximum length of a balanced subarray found so far + + for (int i = 0; i < n; i++) { + int num = nums[i]; + + if (num == 0) rSum--;//-1 if 0 + else rSum++;//+1 if 1 + + if (map.find(rSum) != map.end()){//search if rSum was seen in the hashmap + max = std::max(max, i - map[rSum]);//computes the length of the max arraay length so far + } + else{ + map[rSum]= i;//rSum was not seen before + + } + } + return max; + } + +}; \ No newline at end of file diff --git a/longestpalindrome.cpp b/longestpalindrome.cpp new file mode 100644 index 00000000..091c178a --- /dev/null +++ b/longestpalindrome.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + int longestPalindrome(string s) { + unordered_map freq; + + // count frequency of each character in the string + for (char c : s) { + freq[c]++; // increment count of character c + } + int length = 0; + bool hasOdd = false; // flag to check if any character has odd frequency + + // iterate over each character frequency + for (auto it : freq) { + // it.second -> frequency of that character + + // if frequency is even, we can use all characters + if (it.second % 2 == 0) { + length += it.second; + } + else { + length += it.second - 1; + + // mark that at least one odd-frequency character exists + hasOdd = true; + } + } + + // we can place exactly one character in the center of the palindrome + if (hasOdd) { + length += 1; + } + return length; + } +}; diff --git a/subarraySum.cpp b/subarraySum.cpp new file mode 100644 index 00000000..e69de29b