Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions ContiguousSubarray.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// Time Complexity: O(n)
// Space Complexity: O(n)


// Treat 0 as -1 and 1 as +1, and maintain a running sum; equal numbers of 0s and 1s result in the same prefix sum repeating.
// Use a dictionary to store the first index where each prefix sum occurs (initialize sum = 0 at index -1).
// When the same sum appears again, the subarray between the previous index and current index has equal 0s and 1s;
// update the maximum length.
public class Solution
{
public int FindMaxLength(int[] nums)
{
if (nums == null || nums.Length == 0)
return 0;
Dictionary<int, int> dict = new();
int max = 0; int sum = 0;
dict.Add(0, -1);
for (int i = 0; i < nums.Length; i++)
{
if (nums[i] == 0)
sum -= 1;
else
sum += 1;

if (dict.ContainsKey(sum))
{
int currentIndex = i - dict[sum];
max = Math.Max(max, currentIndex);
// if you need maintain indexes
// if (max < currentIndex)
// {
// int start = dict[sum] + 1;
// int end = i;
// }
}
else
{
dict.Add(sum, i);
}
}
return max;
}
}
32 changes: 32 additions & 0 deletions longestPalindrome.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
//Time and space - O(n)

// Use a HashSet to track characters that appear an odd number of times.
// When a character appears twice, form a pair, add 2 to the palindrome length, and remove it from the set.
// After processing all characters, if any odd-count character remains, add 1 to place one in the center
public class Solution
{
public int LongestPalindrome(string s)
{
HashSet<char> hash = new();
int count = 0;
for (int i = 0; i < s.Length; i++)
{
char ch = s[i];
if (hash.Contains(ch))
{
count += 2;
hash.Remove(ch);
}
else
{
hash.Add(ch);
}
}
if (hash.Count != 0)
{
count += 1;
}
return count;
}
}

35 changes: 35 additions & 0 deletions subArraySumEqualsK.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// Time Complexity: O(n)
// Space Complexity: O(n)

// Use a prefix sum (rsum) and a dictionary to store how many times each prefix sum has appeared.
// For each index, check if (rsum − k) exists in the dictionary; if it does, those occurrences form subarrays with sum k.
// Update the dictionary with the current prefix sum count as you iterate.
public class Solution
{
public int SubarraySum(int[] nums, int k)
{
Dictionary<int, int> dict = new();
int rsum = 0;
int count = 0;
dict.Add(0, 1);
for (int i = 0; i < nums.Length; i++)
{
rsum += nums[i];
int res = rsum - k;
if (dict.ContainsKey(res))
{
count += dict[res];
}
if (dict.ContainsKey(rsum))
{
dict[rsum]++;
}
else
{
dict.TryAdd(rsum, 1);
}
}
return count;

}
}