Skip to content

Added C# solutions for Chapter 1 (Two Pointers) #71

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 21, 2025
Merged
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
33 changes: 33 additions & 0 deletions csharp/Two Pointers/IsPalindromeValid.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
public class Solution
{
public bool IsPalindromeValid(string s)
{
int left = 0, right = s.Length - 1;
while (left < right)
{
// Skip non-alphanumeric characters from the left.
while (left < right && !char.IsLetterOrDigit(s[left]))
{
left++;
}

// Skip non-alphanumeric characters from the right.
while (left < right && !char.IsLetterOrDigit(s[right]))
{
right--;
}

// If the characters at the left and right pointers don't
// match, the string is not a palindrome.
if (s[left] != s[right])
{
return false;
}

left++;
right--;
}

return true;
}
}
33 changes: 33 additions & 0 deletions csharp/Two Pointers/LargestContainer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
public class Solution
{
public int LargestContainer(int[] heights)
{
int max_water = 0;
int left = 0, right = heights.Length - 1;
while (left < right)
{
// Calculate the water contained between the current pair of
// lines.
int water = Math.Min(heights[left], heights[right]) * (right - left);
max_water = Math.Max(max_water, water);
// Move the pointers inward, always moving the pointer at the
// shorter line. If both lines have the same height, move both
// pointers inward.
if (heights[left] < heights[right])
{
left++;
}
else if (heights[left] > heights[right])
{
right--;
}
else
{
left++;
right--;
}
}

return max_water;
}
}
20 changes: 20 additions & 0 deletions csharp/Two Pointers/LargestContainerBruteForce.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
public class Solution
{
public int LargestContainerBruteForce(int[] heights)
{
int n = heights.Length;
int max_water = 0;
// Find the maximum amount of water stored between all pairs of
// lines.
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
int water = Math.Min(heights[i], heights[j]) * (j - i);
max_water = Math.Max(max_water, water);
}
}

return max_water;
}
}
45 changes: 45 additions & 0 deletions csharp/Two Pointers/NextLexicographicalSequence.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
public class Solution
{
public string NextLexicographicalSequence(string s)
{
char[] letters = s.ToCharArray();
// Locate the pivot, which is the first character from the right that breaks
// non-increasing order. Start searching from the second-to-last position,
// since the last character is neither increasing nor decreasing.
int pivot = letters.Length - 2;
while (pivot >= 0 && letters[pivot] >= letters[pivot + 1])
{
pivot--;
}
// If pivot is not found, the string is already in its largest permutation. In
// this case, reverse the string to obtain the smallest permutation.
if (pivot == -1)
{
ReverseString(letters, 0, letters.Length - 1);
return string.Join("", letters);
}
// Find the rightmost successor to the pivot.
int rightmost_successor = letters.Length - 1;
while (letters[rightmost_successor] <= letters[pivot])
{
rightmost_successor--;
}
// Swap the rightmost successor with the pivot to increase the lexicographical
// order of the suffix.
(letters[pivot], letters[rightmost_successor]) = (letters[rightmost_successor], letters[pivot]);
// Reverse the suffix after the pivot to minimize its permutation.
ReverseString(letters, pivot + 1, letters.Length - 1);
return string.Join("", letters);
}

public void ReverseString(char[] s, int start, int end)
{
while (start < end)
{
(s[start], s[end]) = (s[end], s[start]);

start++;
end--;
}
}
}
30 changes: 30 additions & 0 deletions csharp/Two Pointers/PairSumSorted.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
public class Solution
{
public int[] PairSumSorted(int[] nums, int target)
{
int left = 0, right = nums.Length - 1;
while (left < right)
{
int sum = nums[left] + nums[right];
// If the sum is smaller, increment the left pointer, aiming
// to increase the sum toward the target value.
if (sum < target)
{
left++;
}
// If the sum is larger, decrement the right pointer, aiming
// to decrease the sum toward the target value.
else if (sum > target)
{
right--;
}
// If the target pair is found, return its indexes.
else
{
return [left, right];
}
}

return [];
}
}
19 changes: 19 additions & 0 deletions csharp/Two Pointers/PairSumSortedBruteForce.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
public class Solution
{
public int[] PairSumSortedBruteForce(int[] nums, int target)
{
int n = nums.Length;
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (nums[i] + nums[j] == target)
{
return [i, j];
}
}
}

return [];
}
}
20 changes: 20 additions & 0 deletions csharp/Two Pointers/ShiftZerosToTheEnd.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
public class Solution
{
public void ShiftZerosToTheEnd(int[] nums)
{
// The 'left' pointer is used to position non-zero elements.
int left = 0;
// Iterate through the array using a 'right' pointer to locate non-zero
// elements.
for (int right = 0; right < nums.Length; right++)
{
if (nums[right] != 0)
{
(nums[right], nums[left]) = (nums[left], nums[right]);
// Increment 'left' since it now points to a position already occupied
// by a non-zero element.
left++;
}
}
}
}
23 changes: 23 additions & 0 deletions csharp/Two Pointers/ShiftZerosToTheEndNaive.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
public class Solution
{
public void ShiftZerosToTheEndNaive(int[] nums)
{
int[] temp = new int[nums.Length];
int i = 0;
// Add all non-zero elements to the left of 'temp'.
foreach (int num in nums)
{
if (num != 0)
{
temp[i] = num;
i++;
}
}

// Set 'nums' to 'temp'.
for (int j = 0; j < nums.Length; j++)
{
nums[j] = temp[j];
}
}
}
64 changes: 64 additions & 0 deletions csharp/Two Pointers/TripletSum.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
public class Solution
{
public IList<IList<int>> TripletSum(int[] nums)
{
IList<IList<int>> triplets = [];
Array.Sort(nums);
for (int i = 0; i < nums.Length; i++)
{
// Optimization: triplets consisting of only positive numbers
// will never sum to 0.
if (nums[i] > 0)
{
break;
}

// To avoid duplicate triplets, skip 'a' if it's the same as
// the previous number.
if (i > 0 && nums[i] == nums[i - 1])
{
continue;
}

// Find all pairs that sum to a target of '-a' (-nums[i]).
IList<IList<int>> pairs = PairSumSortedAllPairs(nums, i + 1, -nums[i]);
foreach (var pair in pairs)
{
triplets.Add([nums[i], pair[0], pair[1]]);
}
}

return triplets;
}

public IList<IList<int>> PairSumSortedAllPairs(int[] nums, int start, int target)
{
IList<IList<int>> pairs = [];
int left = start, right = nums.Length - 1;
while (left < right)
{
int sum = nums[left] + nums[right];
if (sum == target)
{
pairs.Add([nums[left], nums[right]]);
left++;
// To avoid duplicate '[b, c]' pairs, skip 'b' if it's the
// same as the previous number.
while (left < right && nums[left] == nums[left - 1])
{
left++;
}
}
else if (sum < target)
{
left++;
}
else
{
right--;
}
}

return pairs;
}
}
35 changes: 35 additions & 0 deletions csharp/Two Pointers/TripletSumBruteForce.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
public class Solution
{
public IList<IList<int>> TripletSumBruteForce(int[] nums)
{
int n = nums.Length;
// Use a hash set to ensure we don't add duplicate triplets.
HashSet<Tuple<int, int, int>> triplets = [];
// Iterate through the indexes of all triplets.
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
for (int k = j + 1; k < n; k++)
{
if (nums[i] + nums[j] + nums[k] == 0)
{
// Sort the triplet before including it in the
// hash set.
int[] triplet = [nums[i], nums[j], nums[k]];
Array.Sort(triplet);
triplets.Add(new Tuple<int, int, int>(triplet[0], triplet[1], triplet[2]));
}
}
}
}

IList<IList<int>> result = [];
foreach (var triplet in triplets)
{
result.Add([triplet.Item1, triplet.Item2, triplet.Item3]);
}

return result;
}
}