0% found this document useful (0 votes)
32 views26 pages

C Sharp Challange

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views26 pages

C Sharp Challange

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 26

1.

Reverse a String

Problem:

Write a method to reverse a given string without using built-in methods like Reverse().

Code:

// See https://aka.ms/new-console-template for more information


using System;
using System.Xml;

namespace StringUtilities
{
class StringReverser
{
public string Text { get; set; }

public string Reverse(string input)


{
if(string.IsNullOrWhiteSpace(input))
{ return "String is null or WhitespaceHandling space"; }

char[] chars = input.ToCharArray();


int left = 0;
int right = chars.Length - 1;

while (left < right)


{
char temp = chars[left];
chars[left] = chars[right];
chars[right] = temp;

left++;
right--;
}

return new string(chars);


}
}

class Program
{
static void Main(string[] args)
{
var reverser = new StringReverser();
Console.WriteLine("Please Enter the String: ");
reverser.Text = Convert.ToString(Console.ReadLine());
string reversedText = reverser.Reverse(reverser.Text);
Console.WriteLine("The reversed string is: " + reversedText);
Console.ReadKey();
}
}
}

Explanation:
 First, we convert the input string into a character array since strings are immutable in
C#.
 We use two pointers (left and right) to swap characters at both ends of the array.
 We continue swapping until the pointers meet in the middle. This way, we reverse the
string in place without extra memory.
 Finally, we convert the character array back into a string and return the result.

2. Check for Palindrome

Problem:

Check if a given string is a palindrome (i.e., reads the same forward and backward).

Code:

csharp
Copy code
public bool IsPalindrome(string str) {
int start = 0, end = str.Length - 1; // Step 1: Initialize two
pointers.

// Step 2: Compare characters from both ends of the string.


while (start < end) {
if (str[start] != str[end]) // If characters don't match, it's not
a palindrome.
return false;

start++; // Move the start pointer right.


end--; // Move the end pointer left.
}

// Step 3: If all characters match, it's a palindrome.


return true;
}

Explanation:

 We use two pointers (start and end) to compare characters from both ends of the
string.
 If at any point the characters don’t match, we immediately return false, meaning it’s
not a palindrome.
 If all characters match, we return true, meaning the string is a palindrome.

3. Two Sum Problem

Problem:

Given an array of integers, find two numbers such that they add up to a specific target. Return
their indices.
Code:

csharp
Copy code

4. Find the Missing Number in a Sequence

Problem:

You are given an array containing numbers from 1 to n, but one number is missing. Find the
missing number.

Code:

csharp
Copy code
public int FindMissingNumber(int[] arr, int n) {
int expectedSum = n * (n + 1) / 2; // Step 1: Calculate the sum of
numbers from 1 to n (formula for sum of n numbers).
int actualSum = arr.Sum(); // Step 2: Calculate the sum of the numbers
in the array.

return expectedSum - actualSum; // Step 3: The difference between


expected sum and actual sum is the missing number.
}

Explanation:

 The sum of the first n natural numbers can be calculated using the formula:
Sum=n(n+1)2\text{Sum} = \frac{n(n+1)}{2}Sum=2n(n+1).
 We calculate this expected sum and subtract the sum of the numbers in the array. The
result is the missing number.
 This solution runs in O(n) time.

5. Find Duplicates in an Array

Problem:

Given an array of integers, find and print the duplicate elements.

Code:

csharp
Copy code
public void PrintDuplicates(int[] arr) {
var duplicates = arr.GroupBy(x => x) // Step 1: Group array elements
by their values.
.Where(g => g.Count() > 1) // Step 2: Filter out
groups that have more than one occurrence.
.Select(g => g.Key); // Step 3: Select the key
(the duplicate value).
// Step 4: Print the duplicates.
foreach (var num in duplicates) {
Console.WriteLine(num);
}
}

Explanation:

 We use the GroupBy() method to group elements by their values.


 The Where() clause filters out groups that have more than one occurrence (i.e.,
duplicates).
 Finally, we use a loop to print each duplicate value.
 This approach is efficient and leverages LINQ to solve the problem in O(n) time.

These examples demonstrate a range of C# programming techniques, including arrays,


dictionaries, LINQ, and mathematical reasoning. Each problem highlights important concepts
such as algorithm design, time complexity, and clean, maintainable code for a Senior C#
developer role.

If you'd like more solutions or specific questions explained in detail, feel free to ask!

4o

You said:

more
ChatGPT said:

ChatGPT

Here are 5 more coding problems with complete code and explanations to further enhance
your understanding for C# interview preparation at a senior level.

6. Merge Two Sorted Arrays

Problem:

Given two sorted arrays, merge them into a single sorted array.

Code:

csharp
Copy code
public int[] MergeSortedArrays(int[] arr1, int[] arr2) {
int i = 0, j = 0, k = 0;
int[] result = new int[arr1.Length + arr2.Length]; // Step 1: Create a
new array to hold the merged result.

// Step 2: Compare elements from both arrays and add the smaller one to
the result.
while (i < arr1.Length && j < arr2.Length) {
if (arr1[i] < arr2[j]) {
result[k++] = arr1[i++];
} else {
result[k++] = arr2[j++];
}
}

// Step 3: Add the remaining elements of arr1 (if any).


while (i < arr1.Length) {
result[k++] = arr1[i++];
}

// Step 4: Add the remaining elements of arr2 (if any).


while (j < arr2.Length) {
result[k++] = arr2[j++];
}

return result;
}

Explanation:

 The solution uses two pointers (i and j) to compare elements from both arrays.
 The smaller element is added to the result array. After that, the pointer for the
corresponding array is incremented.
 Once one array is fully processed, the remaining elements from the other array are
added to the result.
 The time complexity of this solution is O(n + m), where n and m are the lengths of the
two arrays.

7. Remove Duplicates from Sorted Array

Problem:

Given a sorted array, remove the duplicates in place and return the new length.

Code:

csharp
Copy code
public int RemoveDuplicates(int[] nums) {
if (nums.Length == 0) return 0;

int uniqueIndex = 0; // Step 1: Use `uniqueIndex` to keep track of


unique elements.

// Step 2: Loop through the array.


for (int i = 1; i < nums.Length; i++) {
if (nums[i] != nums[uniqueIndex]) { // If the current element is
different from the previous unique one.
uniqueIndex++; // Move the unique index.
nums[uniqueIndex] = nums[i]; // Update the unique index with
the new unique element.
}
}

return uniqueIndex + 1; // Step 3: Return the new length of the array


with unique elements.
}

Explanation:

 This problem is solved using a two-pointer technique. The uniqueIndex pointer


tracks the position where the next unique element should be placed.
 We compare the current element with the last unique one. If they are different, we
move uniqueIndex forward and place the new unique element there.
 This approach runs in O(n) time and modifies the array in place.

8. Find the Intersection of Two Arrays

Problem:

Given two arrays, find their intersection. Each element in the result must be unique.

Code:

csharp
Copy code
public int[] Intersection(int[] nums1, int[] nums2) {
var set1 = new HashSet<int>(nums1); // Step 1: Store the elements of
the first array in a set.
var result = new HashSet<int>();

// Step 2: Check each element in the second array for presence in the
first set.
foreach (var num in nums2) {
if (set1.Contains(num)) {
result.Add(num); // If the element is found, add it to the
result set (to ensure uniqueness).
}
}

return result.ToArray(); // Step 3: Convert the result set to an


array.
}

Explanation:

 We store the elements of the first array in a HashSet to enable fast lookups (O(1) time
complexity).
 For each element in the second array, we check if it exists in the first set. If it does, we
add it to the result set.
 Finally, we return the result set as an array. This approach ensures that the result
contains only unique elements.

9. Longest Common Prefix

Problem:

Write a function to find the longest common prefix among an array of strings.

Code:

csharp
Copy code
public string LongestCommonPrefix(string[] strs) {
if (strs == null || strs.Length == 0) return ""; // Step 1: Handle
edge case.

string prefix = strs[0]; // Step 2: Assume the first string is the


prefix.

// Step 3: Compare the assumed prefix with every other string.


for (int i = 1; i < strs.Length; i++) {
while (strs[i].IndexOf(prefix) != 0) { // If the current string
doesn't start with the prefix.
prefix = prefix.Substring(0, prefix.Length - 1); // Reduce the
prefix length.

if (prefix == "") return ""; // If no common prefix is found,


return an empty string.
}
}

return prefix; // Step 4: Return the common prefix.


}

Explanation:

 We assume the first string is the common prefix and compare it with each of the
remaining strings.
 If a string doesn’t start with the current prefix, we shorten the prefix one character at a
time until we find a common prefix or reach an empty string.
 The solution has a time complexity of O(n * m), where n is the number of strings and
m is the length of the prefix.

10. Valid Parentheses

Problem:
Given a string containing just the characters (, ), {, }, [, and ], determine if the input string
is valid. A string is valid if the brackets are closed in the correct order.

Code:

csharp
Copy code
public bool IsValid(string s) {
var stack = new Stack<char>(); // Step 1: Use a stack to track open
parentheses.

// Step 2: Loop through each character in the string.


foreach (char c in s) {
// If it's an opening bracket, push it onto the stack.
if (c == '(' || c == '{' || c == '[') {
stack.Push(c);
}
// If it's a closing bracket, check if it matches the top of the
stack.
else {
if (stack.Count == 0) return false; // If the stack is empty,
the string is invalid.

char top = stack.Pop(); // Pop the top element and check if it


matches.
if ((c == ')' && top != '(') || (c == '}' && top != '{') || (c
== ']' && top != '[')) {
return false; // If it doesn't match, return false.
}
}
}

// Step 3: If the stack is empty, all parentheses were matched.


return stack.Count == 0;
}

Explanation:

 A stack is used to keep track of opening parentheses. For every closing parenthesis,
we check if it matches the top of the stack.
 If it does, we pop the stack; otherwise, the string is invalid.
 If the stack is empty after processing the entire string, the parentheses are valid. The
time complexity of this solution is O(n).

These additional problems continue to explore common coding challenges such as array
manipulation, string processing, and data structure usage (stacks, hashsets). Solving these
will further prepare you for a Senior C# developer interview, where understanding efficient
algorithms and data structures is crucial.

Let me know if you'd like more coding challenges or if you want further explanations on any
concepts!

4o
You said:

more
ChatGPT said:

ChatGPT

Here are 5 more coding problems with full code and detailed explanations for more
advanced interview preparation.

11. Find the First Non-Repeating Character in a String

Problem:

Given a string, find the first non-repeating character and return its index. If it doesn't exist,
return -1.

Code:

csharp
Copy code
public int FirstUniqChar(string s) {
var frequency = new Dictionary<char, int>(); // Step 1: Create a
dictionary to store character frequencies.

// Step 2: Populate the dictionary with character frequencies.


foreach (char c in s) {
if (frequency.ContainsKey(c)) {
frequency[c]++;
} else {
frequency[c] = 1;
}
}

// Step 3: Find the first character that appears only once.


for (int i = 0; i < s.Length; i++) {
if (frequency[s[i]] == 1) {
return i; // Return the index of the first non-repeating
character.
}
}

return -1; // Step 4: If no unique character is found, return -1.


}

Explanation:

 We use a dictionary to keep track of the frequency of each character in the string.
 In the second loop, we check each character to see if it appears only once.
 The time complexity is O(n) since we traverse the string twice (once for counting and
once for checking).
12. Rotate an Array

Problem:

Rotate an array to the right by k steps, where k is non-negative.

Code:

csharp
Copy code
public void Rotate(int[] nums, int k) {
k = k % nums.Length; // Step 1: Adjust k to handle cases where k >
nums.Length.

// Step 2: Reverse the entire array.


Reverse(nums, 0, nums.Length - 1);

// Step 3: Reverse the first k elements.


Reverse(nums, 0, k - 1);

// Step 4: Reverse the remaining elements.


Reverse(nums, k, nums.Length - 1);
}

private void Reverse(int[] nums, int start, int end) {


while (start < end) {
int temp = nums[start]; // Swap the start and end elements.
nums[start] = nums[end];
nums[end] = temp;
start++;
end--;
}
}

Explanation:

 We perform three reversals:


1. Reverse the entire array.
2. Reverse the first k elements.
3. Reverse the remaining elements.
 This approach has a time complexity of O(n), and reversing the array in place saves
extra space.

13. Find the Majority Element

Problem:

Given an array of size n, find the majority element. The majority element is the element that
appears more than n / 2 times.
Code:

csharp
Copy code
public int MajorityElement(int[] nums) {
int count = 0, candidate = 0;

// Step 1: Use the Boyer-Moore Voting Algorithm to find the candidate.


foreach (int num in nums) {
if (count == 0) {
candidate = num; // Assign a new candidate.
}
count += (num == candidate) ? 1 : -1; // Increment if same,
decrement if different.
}

return candidate; // Step 2: Return the majority element.


}

Explanation:

 The Boyer-Moore Voting Algorithm works by maintaining a candidate and


adjusting its count based on whether subsequent elements match the candidate.
 Since the problem guarantees that a majority element always exists, the algorithm will
return the correct element.
 This approach runs in O(n) time with O(1) space.

14. Find the Peak Element

Problem:

A peak element in an array is an element that is greater than its neighbors. Given an array,
find the peak element and return its index. The array may contain multiple peaks.

Code:

csharp
Copy code
public int FindPeakElement(int[] nums) {
int left = 0, right = nums.Length - 1;

// Step 1: Binary search to find the peak.


while (left < right) {
int mid = left + (right - left) / 2;

// Step 2: Compare mid with its next neighbor.


if (nums[mid] > nums[mid + 1]) {
right = mid; // If mid is greater, peak is in the left half.
} else {
left = mid + 1; // If mid is smaller, peak is in the right
half.
}
}
return left; // Step 3: Return the index of the peak element.
}

Explanation:

 We use binary search to find the peak element in O(log n) time.


 At each step, we compare the middle element with its neighbor to decide whether the
peak lies in the left or right half of the array.

15. Find the Missing Number

Problem:

You are given an array containing n distinct numbers from the range [0, n]. Find the
missing number.

Code:

csharp
Copy code
public int MissingNumber(int[] nums) {
int n = nums.Length;
int totalSum = n * (n + 1) / 2; // Step 1: Calculate the expected sum
of numbers from 0 to n.

int actualSum = 0;
foreach (int num in nums) {
actualSum += num; // Step 2: Calculate the actual sum of the
array.
}

return totalSum - actualSum; // Step 3: The missing number is the


difference between the expected and actual sums.
}

Explanation:

 The sum of the first n natural numbers is Sum=n(n+1)2\text{Sum} = \frac{n(n+1)}


{2}Sum=2n(n+1).
 We calculate the expected sum and subtract the actual sum of the array to find the
missing number.
 This approach runs in O(n) time with O(1) space complexity.

These problems cover a wide range of algorithmic challenges, including searching, array
manipulation, mathematical reasoning, and voting algorithms. Solving these problems will
further sharpen your skills for technical interviews, especially for senior-level C# developer
roles where efficiency and problem-solving are key.

Feel free to ask if you'd like more examples or detailed explanations!


4o

You said:

more
ChatGPT said:

ChatGPT

Here are 5 more coding problems with full solutions and explanations to continue enhancing
your C# interview preparation:

16. Subarray Sum Equals K

Problem:

Given an array of integers and an integer k, find the total number of continuous subarrays
whose sum equals to k.

Code:

csharp
Copy code
public int SubarraySum(int[] nums, int k) {
var sumCounts = new Dictionary<int, int>(); // Step 1: Store
cumulative sums and their frequencies.
sumCounts[0] = 1; // Initial condition to handle subarrays starting
from index 0.

int sum = 0, count = 0;

// Step 2: Iterate through the array.


foreach (var num in nums) {
sum += num; // Update cumulative sum.

// Step 3: Check if there is a previous subarray with sum `sum -


k`.
if (sumCounts.ContainsKey(sum - k)) {
count += sumCounts[sum - k]; // Increment count by the
frequency of that sum.
}

// Step 4: Update the frequency of the current cumulative sum.


if (sumCounts.ContainsKey(sum)) {
sumCounts[sum]++;
} else {
sumCounts[sum] = 1;
}
}

return count; // Step 5: Return the total count of subarrays that sum
to `k`.
}
Explanation:

 The solution uses a prefix sum and a hashmap to track how many times a cumulative
sum has occurred.
 For each element in the array, it calculates the cumulative sum and checks if there is a
previous sum that would give the required subarray sum.
 This method runs in O(n) time and space.

17. Find Kth Largest Element in an Array

Problem:

Given an integer array nums and an integer k, return the k-th largest element in the array.

Code:

csharp
Copy code
public int FindKthLargest(int[] nums, int k) {
PriorityQueue<int, int> minHeap = new PriorityQueue<int, int>();

// Step 1: Iterate through the array.


foreach (int num in nums) {
minHeap.Enqueue(num, num); // Step 2: Add elements to the min
heap.

// Step 3: If heap size exceeds k, remove the smallest element.


if (minHeap.Count > k) {
minHeap.Dequeue();
}
}

return minHeap.Peek(); // Step 4: The top of the heap is the k-th


largest element.
}

Explanation:

 This solution uses a min-heap (priority queue) to keep the top k largest elements. The
smallest element in the heap is removed when the heap size exceeds k.
 At the end of the process, the root of the heap is the k-th largest element.
 This approach has a time complexity of O(n log k), where n is the size of the array.

18. Find All Duplicates in an Array

Problem:

Given an array of integers where 1 ≤ a[i] ≤ n (n = size of the array), some elements appear
twice and others appear once. Find all the elements that appear twice.
Code:

csharp
Copy code
public IList<int> FindDuplicates(int[] nums) {
List<int> result = new List<int>();

// Step 1: Iterate through the array.


for (int i = 0; i < nums.Length; i++) {
int index = Math.Abs(nums[i]) - 1; // Step 2: Get the index
corresponding to the value.

// Step 3: If the value at that index is negative, the number has


been seen before.
if (nums[index] < 0) {
result.Add(index + 1);
} else {
nums[index] = -nums[index]; // Mark the number as seen by
negating the value.
}
}

return result; // Step 4: Return the result list with duplicate


elements.
}

Explanation:

 The idea is to treat the array elements as indices and negate the values at those indices
to mark them as "visited."
 If we encounter a value that points to a previously visited index (negative value), we
know that the element has appeared twice.
 This algorithm runs in O(n) time and uses O(1) extra space since the input array is
modified in place.

19. Coin Change Problem

Problem:

You are given an integer array coins representing different coin denominations and an
integer amount representing a total amount of money. Return the fewest number of coins that
make up that amount. If that amount cannot be made up by any combination of the coins,
return -1.

Code:

csharp
Copy code
public int CoinChange(int[] coins, int amount) {
int[] dp = new int[amount + 1];
Array.Fill(dp, amount + 1); // Step 1: Initialize the DP array with a
large value.
dp[0] = 0; // Base case: 0 coins needed to make amount 0.
// Step 2: Iterate through each amount.
for (int i = 1; i <= amount; i++) {
foreach (int coin in coins) {
if (i - coin >= 0) {
dp[i] = Math.Min(dp[i], dp[i - coin] + 1); // Step 3:
Update the DP table.
}
}
}

return dp[amount] > amount ? -1 : dp[amount]; // Step 4: Return the


result.
}

Explanation:

 This is a dynamic programming solution where we keep track of the minimum


number of coins needed to make each amount up to amount in the dp array.
 We fill the array with a large value and iteratively update it based on the coins
available.
 The time complexity is O(n * m), where n is the amount and m is the number of coins.

20. Find Minimum in Rotated Sorted Array

Problem:

Suppose an array sorted in ascending order is rotated at some pivot unknown to you
beforehand. You need to find the minimum element in this rotated array.

Code:

csharp
Copy code
public int FindMin(int[] nums) {
int left = 0, right = nums.Length - 1;

// Step 1: Binary search.


while (left < right) {
int mid = left + (right - left) / 2;

// Step 2: If middle element is greater than the rightmost element,


search in the right half.
if (nums[mid] > nums[right]) {
left = mid + 1;
}
// Step 3: If the middle element is less than or equal to the
rightmost element, search in the left half.
else {
right = mid;
}
}
return nums[left]; // Step 4: The left pointer will point to the
minimum element.
}

Explanation:

 This solution leverages binary search to find the minimum element in O(log n) time.
 The key observation is that if the middle element is greater than the rightmost
element, the minimum must be in the right half of the array. Otherwise, it is in the left
half.

These additional problems cover dynamic programming, binary search, and array
manipulation using advanced data structures like heaps and hashmaps. Mastering these
problems will further solidify your preparation for senior-level C# interviews.

Let me know if you need more examples or explanations!

4o

You said:

more
ChatGPT said:

ChatGPT

Here are 5 more coding problems with full explanations and solutions in C# to further build
your interview preparation:

21. Longest Consecutive Sequence

Problem:

Given an unsorted array of integers, find the length of the longest consecutive elements
sequence. You must implement the algorithm in O(n) time complexity.

Code:

csharp
Copy code
public int LongestConsecutive(int[] nums) {
if (nums.Length == 0) return 0;

HashSet<int> numSet = new HashSet<int>(nums); // Step 1: Use a HashSet


for O(1) lookups.
int longestStreak = 0;

// Step 2: Iterate through each number in the array.


foreach (int num in numSet) {
if (!numSet.Contains(num - 1)) { // Only start a new sequence if
num-1 is not in the set.
int currentNum = num;
int currentStreak = 1;

// Step 3: Keep increasing the streak if the next consecutive


number exists.
while (numSet.Contains(currentNum + 1)) {
currentNum += 1;
currentStreak += 1;
}

// Step 4: Update the longest streak if necessary.


longestStreak = Math.Max(longestStreak, currentStreak);
}
}

return longestStreak;
}

Explanation:

 We use a HashSet to quickly check the existence of numbers in O(1) time.


 For each number, we only start counting the consecutive sequence if it's the start of
the sequence (i.e., num - 1 is not in the set).
 This ensures that each sequence is counted only once, leading to an O(n) time
complexity.

22. Merge Intervals

Problem:

Given a collection of intervals, merge all overlapping intervals.

Code:

csharp
Copy code
public int[][] Merge(int[][] intervals) {
if (intervals.Length == 0) return new int[0][];

// Step 1: Sort intervals based on the start time.


Array.Sort(intervals, (a, b) => a[0].CompareTo(b[0]));

List<int[]> merged = new List<int[]>();


int[] currentInterval = intervals[0];

// Step 2: Iterate through each interval.


foreach (int[] interval in intervals) {
// Step 3: Check if intervals overlap (if current's end >= next's
start).
if (currentInterval[1] >= interval[0]) {
// Merge the intervals.
currentInterval[1] = Math.Max(currentInterval[1], interval[1]);
} else {
// Add the current merged interval and update current interval.
merged.Add(currentInterval);
currentInterval = interval;
}
}

merged.Add(currentInterval); // Step 4: Add the last interval.


return merged.ToArray(); // Convert the list to a 2D array.
}

Explanation:

 We first sort the intervals by their starting time.


 Then, we iterate through the intervals, merging them when they overlap, and adding
non-overlapping intervals to the result.
 Sorting takes O(n log n), and iterating through the intervals is O(n), so the overall
complexity is O(n log n).

23. Product of Array Except Self

Problem:

Given an array nums of n integers, return an array answer such that answer[i] is equal to the
product of all the elements of nums except nums[i]. You must solve it in O(n) without using
division.

Code:

csharp
Copy code
public int[] ProductExceptSelf(int[] nums) {
int n = nums.Length;
int[] answer = new int[n];

// Step 1: Calculate the left product for each element.


answer[0] = 1;
for (int i = 1; i < n; i++) {
answer[i] = answer[i - 1] * nums[i - 1];
}

// Step 2: Calculate the right product for each element and multiply it
with the left product.
int right = 1;
for (int i = n - 1; i >= 0; i--) {
answer[i] *= right;
right *= nums[i];
}

return answer;
}

Explanation:
 First, we compute the left product for each element, storing it in the answer array.
 Then, we calculate the right product and multiply it with the corresponding left
product.
 This approach runs in O(n) time and uses O(1) additional space (excluding the output
array).

24. Validate Binary Search Tree (BST)

Problem:

Given the root of a binary tree, determine if it is a valid binary search tree (BST).

Code:

csharp
Copy code
public bool IsValidBST(TreeNode root) {
return Validate(root, null, null);
}

private bool Validate(TreeNode node, int? low, int? high) {


if (node == null) return true;

// Step 1: Check if the current node's value is out of bounds.


if ((low != null && node.val <= low) || (high != null && node.val >=
high)) {
return false;
}

// Step 2: Recursively validate the left and right subtrees with


updated bounds.
return Validate(node.left, low, node.val) && Validate(node.right,
node.val, high);
}

Explanation:

 We use recursive bounds checking to validate the tree.


 For each node, we check if its value lies within the valid range (low and high) and
recursively validate its left and right subtrees.
 This approach runs in O(n) time and space, where n is the number of nodes.

25. Trapping Rain Water

Problem:

Given n non-negative integers representing an elevation map where the width of each bar is
1, compute how much water it can trap after raining.
Code:

csharp
Copy code
public int Trap(int[] height) {
if (height.Length == 0) return 0;

int n = height.Length;
int[] leftMax = new int[n];
int[] rightMax = new int[n];

// Step 1: Compute leftMax for each index.


leftMax[0] = height[0];
for (int i = 1; i < n; i++) {
leftMax[i] = Math.Max(leftMax[i - 1], height[i]);
}

// Step 2: Compute rightMax for each index.


rightMax[n - 1] = height[n - 1];
for (int i = n - 2; i >= 0; i--) {
rightMax[i] = Math.Max(rightMax[i + 1], height[i]);
}

// Step 3: Calculate trapped water.


int water = 0;
for (int i = 0; i < n; i++) {
water += Math.Min(leftMax[i], rightMax[i]) - height[i];
}

return water;
}

Explanation:

 We first compute the leftMax and rightMax arrays, which store the maximum height
to the left and right of each element.
 Then, for each element, the trapped water is determined by the minimum of the left
and right maximum heights minus the current height.
 This algorithm runs in O(n) time and space.

These additional problems focus on topics like binary trees, dynamic programming, prefix
products, and more advanced data structures. With these examples, you will be better
prepared to tackle more complex coding challenges that often appear in technical interviews
for senior C# developer roles.

Feel free to ask if you'd like further explanations or more problems!

4o

You said:

more
ChatGPT said:
ChatGPT

Here are 5 additional coding problems with full explanations and solutions in C# to
continue enhancing your interview preparation:

26. Kth Smallest Element in a BST

Problem:

Given a binary search tree, write a function to find the k-th smallest element in it.

Code:

csharp
Copy code
public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;

public TreeNode(int val = 0, TreeNode left = null, TreeNode right =


null) {
this.val = val;
this.left = left;
this.right = right;
}
}

public int KthSmallest(TreeNode root, int k) {


Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode current = root;

while (true) {
// Step 1: Go to the leftmost node.
while (current != null) {
stack.Push(current);
current = current.left;
}

// Step 2: Visit the node.


current = stack.Pop();
k--;

// Step 3: If we have visited k nodes, return the current node's


value.
if (k == 0) {
return current.val;
}

// Step 4: Move to the right subtree.


current = current.right;
}
}

Explanation:
 This solution uses an in-order traversal approach using a stack to explore the BST.
 We push nodes to the stack until we reach the leftmost node, pop nodes to visit them,
and decrement k until we find the k-th smallest element.
 The algorithm runs in O(h + k) time, where h is the height of the tree.

27. Combination Sum

Problem:

Given an array of distinct integers candidates and a target integer target, return all unique
combinations of candidates where the chosen numbers sum to target. You may return the
combinations in any order.

Code:

csharp
Copy code
public IList<IList<int>> CombinationSum(int[] candidates, int target) {
var result = new List<IList<int>>();
Backtrack(candidates, target, 0, new List<int>(), result);
return result;
}

private void Backtrack(int[] candidates, int remain, int start, IList<int>


combination, IList<IList<int>> result) {
if (remain == 0) {
result.Add(new List<int>(combination)); // Step 1: If remain is 0,
we found a valid combination.
return;
}
if (remain < 0) return; // Step 2: If remain is negative, no valid
combination.

for (int i = start; i < candidates.Length; i++) {


combination.Add(candidates[i]); // Step 3: Choose the current
candidate.
Backtrack(candidates, remain - candidates[i], i, combination,
result); // Recur with reduced remain.
combination.RemoveAt(combination.Count - 1); // Step 4: Backtrack
and remove the last chosen candidate.
}
}

Explanation:

 The approach uses backtracking to explore all combinations.


 If the remaining target becomes zero, we add the current combination to the result. If
it becomes negative, we terminate that path.
 We recursively explore each candidate and backtrack to try other combinations,
maintaining a time complexity of O(2^n).
28. Count Primes

Problem:

Count the number of prime numbers less than a non-negative integer n.

Code:

csharp
Copy code
public int CountPrimes(int n) {
if (n <= 2) return 0;

bool[] isPrime = new bool[n]; // Step 1: Create an array to track


prime numbers.
Array.Fill(isPrime, true); // Initialize all numbers as prime.

for (int i = 2; i * i < n; i++) { // Step 2: Use the Sieve of


Eratosthenes.
if (isPrime[i]) {
for (int j = i * i; j < n; j += i) {
isPrime[j] = false; // Mark multiples of i as non-prime.
}
}
}

// Step 3: Count all prime numbers.


int count = 0;
for (int i = 2; i < n; i++) {
if (isPrime[i]) count++;
}

return count; // Step 4: Return the count of prime numbers.


}

Explanation:

 This solution implements the Sieve of Eratosthenes algorithm, which efficiently


finds all prime numbers less than n.
 We mark non-prime numbers by iterating through each integer and marking its
multiples as non-prime.
 The algorithm runs in O(n log log n) time, making it efficient for large values of n.

29. First Unique Character in a String

Problem:

Given a string s, find the first non-repeating character in it and return its index. If it doesn't
exist, return -1.

Code:
csharp
Copy code
public int FirstUniqChar(string s) {
var charCount = new Dictionary<char, int>();

// Step 1: Count the occurrences of each character.


foreach (char c in s) {
if (charCount.ContainsKey(c)) {
charCount[c]++;
} else {
charCount[c] = 1;
}
}

// Step 2: Find the first non-repeating character.


for (int i = 0; i < s.Length; i++) {
if (charCount[s[i]] == 1) {
return i; // Step 3: Return the index of the first unique
character.
}
}

return -1; // Step 4: Return -1 if no unique character exists.


}

Explanation:

 We use a dictionary to count the occurrences of each character in the string.


 After counting, we loop through the string again to find the first character that appears
exactly once.
 The overall complexity is O(n) for both counting and searching.

30. Rotate Array

Problem:

Given an array, rotate the array to the right by k steps, where k is non-negative.

Code:

csharp
Copy code
public void Rotate(int[] nums, int k) {
k %= nums.Length; // Step 1: Handle cases where k is larger than the
array size.
Reverse(nums, 0, nums.Length - 1); // Step 2: Reverse the entire
array.
Reverse(nums, 0, k - 1); // Step 3: Reverse the first k elements.
Reverse(nums, k, nums.Length - 1); // Step 4: Reverse the remaining
elements.
}

private void Reverse(int[] nums, int start, int end) {


while (start < end) {
int temp = nums[start];
nums[start] = nums[end];
nums[end] = temp; // Step 5: Swap elements to reverse the segment.
start++;
end--;
}
}

Explanation:

 This solution uses the reverse array technique to rotate the elements.
 We first reverse the entire array, then reverse the first k elements and the remaining
elements.
 This method runs in O(n) time, where n is the length of the array.

You might also like