Skip to main content

Ace Your .NET Core Coding Interview: Top 20 Algorithmic & Problem-Solving Questions

 Beyond knowing the ins and outs of .NET Core, a successful technical interview often hinges on your ability to solve fundamental coding problems. These questions test your logical thinking, algorithm design, and grasp of basic data structures. This blog post provides 20 essential coding interview questions, complete with explanations and example approaches in C#, to help you shine in your next .NET Core technical assessment.




1. Reverse a String Without Built-in Functions

Explanation: A classic that tests your understanding of loops and string manipulation.

Question: Write a C# method to reverse a given string without using built-in Reverse() or ToArray() methods.

Answer:

C#
public string ReverseString(string input)
{
    if (string.IsNullOrEmpty(input))
    {
        return input;
    }

    char[] charArray = input.ToCharArray();
    int left = 0;
    int right = charArray.Length - 1;

    while (left < right)
    {
        // Swap characters
        char temp = charArray[left];
        charArray[left] = charArray[right];
        charArray[right] = temp;

        left++;
        right--;
    }

    return new string(charArray);
}

// Example Usage:
// string original = "hello";
// string reversed = ReverseString(original); // "olleh"

Explanation: The method converts the string to a character array for mutability. It uses two pointers, left and right, starting at the beginning and end of the array, respectively. It then iteratively swaps the characters at these pointers, moving left forward and right backward until they meet or cross, ensuring the entire string is reversed.


2. Count Occurrences of Each Character in a String

Explanation: Tests dictionary usage and iteration.

Question: Given a string, write a C# method to count the occurrences of each character and return them as a dictionary.

Answer:

C#
public Dictionary<char, int> CountCharOccurrences(string input)
{
    Dictionary<char, int> charCounts = new Dictionary<char, int>();

    if (string.IsNullOrEmpty(input))
    {
        return charCounts;
    }

    foreach (char c in input)
    {
        if (charCounts.ContainsKey(c))
        {
            charCounts[c]++;
        }
        else
        {
            charCounts.Add(c, 1);
        }
    }

    return charCounts;
}

// Example Usage:
// string text = "programming";
// var counts = CountCharOccurrences(text);
// // counts will be: { 'p': 1, 'r': 2, 'o': 1, 'g': 2, 'a': 1, 'm': 2, 'i': 1, 'n': 1 }

Explanation: A Dictionary<char, int> is used to store characters as keys and their counts as values. The method iterates through each character in the input string. If the character is already a key in the dictionary, its count is incremented; otherwise, it's added as a new key with a count of 1.


3. Check if a String is a Palindrome

Explanation: Combines string manipulation with conditional logic.

Question: Write a C# method to check if a given string is a palindrome (reads the same forwards and backwards, ignoring case).

Answer:

C#
public bool IsPalindrome(string input)
{
    if (string.IsNullOrEmpty(input))
    {
        return true; // An empty string or null can be considered a palindrome
    }

    string cleanedInput = new string(input.Where(char.IsLetterOrDigit).ToArray()).ToLower();

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

    while (left < right)
    {
        if (cleanedInput[left] != cleanedInput[right])
        {
            return false;
        }
        left++;
        right--;
    }

    return true;
}

// Example Usage:
// bool result1 = IsPalindrome("madam"); // true
// bool result2 = IsPalindrome("A man, a plan, a canal: Panama"); // true
// bool result3 = IsPalindrome("hello"); // false

Explanation: First, the input string is cleaned by removing non-alphanumeric characters and converted to lowercase to handle case insensitivity. Then, two pointers (left and right) are used to compare characters from both ends of the cleaned string. If a mismatch is found, it's not a palindrome.


4. Find the Largest Number in an Array

Explanation: A basic array traversal problem.

Question: Write a C# method to find the largest number in an integer array.

Answer:

C#
public int FindLargestNumber(int[] numbers)
{
    if (numbers == null || numbers.Length == 0)
    {
        throw new ArgumentException("Array cannot be null or empty.");
    }

    int largest = numbers[0]; // Assume the first element is the largest initially

    for (int i = 1; i < numbers.Length; i++)
    {
        if (numbers[i] > largest)
        {
            largest = numbers[i];
        }
    }

    return largest;
}

// Example Usage:
// int[] arr = { 10, 5, 20, 15, 30 };
// int largest = FindLargestNumber(arr); // 30

Explanation: The method initializes largest with the first element of the array. It then iterates from the second element, comparing each element with the current largest. If a larger element is found, largest is updated. Includes basic error handling for empty or null arrays.


5. Find the Smallest Number in an Array

Explanation: Similar to finding the largest, reinforces array traversal.

Question: Write a C# method to find the smallest number in an integer array.

Answer:

C#
public int FindSmallestNumber(int[] numbers)
{
    if (numbers == null || numbers.Length == 0)
    {
        throw new ArgumentException("Array cannot be null or empty.");
    }

    int smallest = numbers[0];

    for (int i = 1; i < numbers.Length; i++)
    {
        if (numbers[i] < smallest)
        {
            smallest = numbers[i];
        }
    }

    return smallest;
}

// Example Usage:
// int[] arr = { 10, 5, 20, 15, 30 };
// int smallest = FindSmallestNumber(arr); // 5

Explanation: Analogous to finding the largest, but the comparison is for less than (<) instead of greater than (>).


6. Calculate the Factorial of a Number (Iterative and Recursive)

Explanation: Tests understanding of iteration and recursion, fundamental programming concepts.

Question: Write C# methods to calculate the factorial of a given non-negative integer using both iterative and recursive approaches.

Answer:

Iterative:

C#
public long FactorialIterative(int n)
{
    if (n < 0) throw new ArgumentOutOfRangeException("Factorial is not defined for negative numbers.");
    if (n == 0 || n == 1) return 1;

    long result = 1;
    for (int i = 2; i <= n; i++)
    {
        result *= i;
    }
    return result;
}

Recursive:

C#
public long FactorialRecursive(int n)
{
    if (n < 0) throw new ArgumentOutOfRangeException("Factorial is not defined for negative numbers.");
    if (n == 0 || n == 1) return 1;

    return n * FactorialRecursive(n - 1);
}

// Example Usage:
// long fact5Iterative = FactorialIterative(5); // 120
// long fact5Recursive = FactorialRecursive(5); // 120

Explanation:

  • Iterative: Uses a for loop to multiply numbers from 2 up to n.

  • Recursive: Defines a base case (0! and 1! are 1) and a recursive step (n * factorial(n-1)). This demonstrates how a problem can be broken down into smaller, similar sub-problems.


7. Check if a Number is Prime

Explanation: Tests basic number theory and loop optimization.

Question: Write a C# method to check if a given positive integer is a prime number.

Answer:

C#
public bool IsPrime(int number)
{
    if (number <= 1) return false; // 0, 1, and negatives are not prime
    if (number == 2) return true;  // 2 is the only even prime number
    if (number % 2 == 0) return false; // Other even numbers are not prime

    // Check for divisibility from 3 up to sqrt(number), only odd numbers
    for (int i = 3; i * i <= number; i += 2)
    {
        if (number % i == 0)
        {
            return false;
        }
    }

    return true;
}

// Example Usage:
// bool isPrime1 = IsPrime(7); // true
// bool isPrime2 = IsPrime(10); // false

Explanation: The method handles edge cases (<=1, 2, even numbers). For other numbers, it efficiently checks for divisibility only by odd numbers up to the square root of the given number. If any divisor is found, it's not prime.


8. Fibonacci Sequence Generation (Iterative)

Explanation: Introduces sequence generation and array population.

Question: Write a C# method to generate the first n numbers of the Fibonacci sequence.

Answer:

C#
public int[] GenerateFibonacci(int n)
{
    if (n <= 0) return new int[0];
    if (n == 1) return new int[] { 0 };
    if (n == 2) return new int[] { 0, 1 };

    int[] fibSequence = new int[n];
    fibSequence[0] = 0;
    fibSequence[1] = 1;

    for (int i = 2; i < n; i++)
    {
        fibSequence[i] = fibSequence[i - 1] + fibSequence[i - 2];
    }

    return fibSequence;
}

// Example Usage:
// int[] fib = GenerateFibonacci(7); // { 0, 1, 1, 2, 3, 5, 8 }

Explanation: Handles base cases for n=0, 1, 2. For larger n, it initializes the first two numbers (0 and 1) and then iteratively calculates subsequent numbers by summing the previous two, storing them in an array.


9. Find Duplicates in an Array

Explanation: Tests array traversal and potentially hash sets for efficiency.

Question: Write a C# method to find and return all duplicate numbers in an integer array.

Answer:

C#
public List<int> FindDuplicates(int[] numbers)
{
    List<int> duplicates = new List<int>();
    HashSet<int> seenNumbers = new HashSet<int>();

    if (numbers == null) return duplicates;

    foreach (int number in numbers)
    {
        if (seenNumbers.Contains(number))
        {
            // Only add to duplicates if it's not already added to avoid multiple entries for the same duplicate value
            if (!duplicates.Contains(number))
            {
                duplicates.Add(number);
            }
        }
        else
        {
            seenNumbers.Add(number);
        }
    }

    return duplicates;
}

// Example Usage:
// int[] arr = { 1, 2, 3, 2, 4, 5, 1, 6 };
// List<int> dups = FindDuplicates(arr); // { 2, 1 }

Explanation: This solution uses a HashSet<int> called seenNumbers to keep track of numbers encountered so far. If a number is already in seenNumbers, it's a duplicate. An additional check !duplicates.Contains(number) ensures that each unique duplicate value is added only once to the duplicates list.


10. Implement Bubble Sort

Explanation: A foundational sorting algorithm, important for understanding comparison-based sorting.

Question: Implement the Bubble Sort algorithm in C# to sort an integer array in ascending order.

Answer:

C#
public void BubbleSort(int[] arr)
{
    if (arr == null || arr.Length <= 1)
    {
        return; // Already sorted or nothing to sort
    }

    int n = arr.Length;
    bool swapped;

    for (int i = 0; i < n - 1; i++)
    {
        swapped = false;
        for (int j = 0; j < n - 1 - i; j++)
        {
            if (arr[j] > arr[j + 1])
            {
                // Swap arr[j] and arr[j+1]
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
                swapped = true;
            }
        }
        // If no two elements were swapped by inner loop, then array is sorted
        if (!swapped)
        {
            break;
        }
    }
}

// Example Usage:
// int[] numbers = { 64, 34, 25, 12, 22, 11, 90 };
// BubbleSort(numbers); // numbers will be { 11, 12, 22, 25, 34, 64, 90 }

Explanation: Bubble Sort repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which means the list is sorted. The outer loop n-1 times, and the inner loop's upper bound decreases with each pass because the largest element "bubbles up" to its correct position.


11. Implement Binary Search (Iterative)

Explanation: Tests searching in sorted arrays, crucial for efficiency.

Question: Implement the Binary Search algorithm in C# to find an element in a sorted integer array. Return the index if found, otherwise -1.

Answer:

C#
public int BinarySearch(int[] arr, int target)
{
    if (arr == null || arr.Length == 0)
    {
        return -1;
    }

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

    while (left <= right)
    {
        int mid = left + (right - left) / 2; // Avoids potential overflow compared to (left + right) / 2

        if (arr[mid] == target)
        {
            return mid; // Element found
        }
        else if (arr[mid] < target)
        {
            left = mid + 1; // Target is in the right half
        }
        else
        {
            right = mid - 1; // Target is in the left half
        }
    }

    return -1; // Element not found
}

// Example Usage:
// int[] sortedArr = { 2, 5, 8, 12, 16, 23, 38, 56, 72, 91 };
// int index1 = BinarySearch(sortedArr, 23); // 5
// int index2 = BinarySearch(sortedArr, 10); // -1

Explanation: Binary search works on sorted arrays. It repeatedly divides the search interval in half. It compares the target value with the middle element. If they are not equal, the half in which the target cannot lie is eliminated, and the search continues on the remaining half.


12. Find the Missing Number in a Sequence

Explanation: Tests array manipulation and mathematical properties.

Question: Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one missing number.

Answer:

C#
public int FindMissingNumber(int[] nums)
{
    if (nums == null || nums.Length == 0)
    {
        // If the array is empty, and the sequence is 0...n, the missing number is 0
        // Or throw an exception depending on expected input.
        return 0; // Assuming the smallest possible sequence starts with 0
    }

    int n = nums.Length;
    // Sum of numbers from 0 to n (inclusive)
    int expectedSum = n * (n + 1) / 2;

    int actualSum = 0;
    foreach (int num in nums)
    {
        actualSum += num;
    }

    return expectedSum - actualSum;
}

// Example Usage:
// int[] arr1 = { 3, 0, 1 }; // n = 3, expected sequence 0,1,2,3. Sum = 6. Actual sum = 4. Missing = 2
// int missing1 = FindMissingNumber(arr1); // 2

// int[] arr2 = { 9, 6, 4, 2, 3, 5, 7, 0, 1 }; // n = 9, expected sequence 0..9. Sum = 45. Actual sum = 37. Missing = 8
// int missing2 = FindMissingNumber(arr2); // 8

Explanation: This solution leverages the property of arithmetic series. The sum of numbers from 0 to n can be calculated using the formula n * (n + 1) / 2. By subtracting the actual sum of the numbers in the given array from this expectedSum, the missing number is found.


13. Remove Duplicates from a Sorted Array

Explanation: Tests in-place array modification and handling unique elements.

Question: Given a sorted array nums, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Return the new length of the array.

Answer:

C#
public int RemoveDuplicates(int[] nums)
{
    if (nums == null || nums.Length == 0)
    {
        return 0;
    }

    int i = 0; // Pointer for the next unique element position

    for (int j = 1; j < nums.Length; j++)
    {
        if (nums[j] != nums[i])
        {
            i++;
            nums[i] = nums[j];
        }
    }

    return i + 1; // New length (i is 0-indexed)
}

// Example Usage:
// int[] arr1 = { 1, 1, 2 };
// int newLength1 = RemoveDuplicates(arr1); // 2 (arr1 becomes {1, 2, ...})

// int[] arr2 = { 0, 0, 1, 1, 1, 2, 2, 3, 3, 4 };
// int newLength2 = RemoveDuplicates(arr2); // 5 (arr2 becomes {0, 1, 2, 3, 4, ...})

Explanation: This method uses two pointers. i tracks the position of the last unique element found so far. j iterates through the array. If nums[j] is different from nums[i], it means we've found a new unique element, so we increment i and place nums[j] at nums[i]. This effectively overwrites duplicate values. The final i + 1 gives the count of unique elements.


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

Explanation: Tests character frequency and string traversal.

Question: Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.

Answer:

C#
public int FirstUniqChar(string s)
{
    if (string.IsNullOrEmpty(s))
    {
        return -1;
    }

    // Use a dictionary to store character counts
    Dictionary<char, int> charCounts = new Dictionary<char, int>();

    // First pass: populate character counts
    foreach (char c in s)
    {
        if (charCounts.ContainsKey(c))
        {
            charCounts[c]++;
        }
        else
        {
            charCounts.Add(c, 1);
        }
    }

    // Second pass: find the first character with a count of 1
    for (int i = 0; i < s.Length; i++)
    {
        if (charCounts[s[i]] == 1)
        {
            return i;
        }
    }

    return -1; // No non-repeating character found
}

// Example Usage:
// int index1 = FirstUniqChar("leetcode"); // 0 (l)
// int index2 = FirstUniqChar("loveleetcode"); // 2 (v)
// int index3 = FirstUniqChar("aabb"); // -1

Explanation: This approach uses a two-pass strategy. The first pass populates a dictionary with character frequencies. The second pass then iterates through the string again, checking the count of each character. The first character encountered with a count of 1 is the answer.


15. Merge Two Sorted Arrays

Explanation: Tests array manipulation and efficient merging.

Question: Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. Assume nums1 has enough space to hold elements from both arrays.

Answer:

C#
public void MergeSortedArrays(int[] nums1, int m, int[] nums2, int n)
{
    // Pointers for nums1 (end of valid elements), nums2 (end), and merge position
    int p1 = m - 1; // Last element of original nums1
    int p2 = n - 1; // Last element of nums2
    int p = m + n - 1; // Last position in nums1

    // Merge from the end of the arrays
    while (p1 >= 0 && p2 >= 0)
    {
        if (nums1[p1] > nums2[p2])
        {
            nums1[p] = nums1[p1];
            p1--;
        }
        else
        {
            nums1[p] = nums2[p2];
            p2--;
        }
        p--;
    }

    // If there are remaining elements in nums2, copy them
    while (p2 >= 0)
    {
        nums1[p] = nums2[p2];
        p2--;
        p--;
    }
    // No need to copy remaining from nums1 because they are already in place
}

// Example Usage:
// int[] nums1 = { 1, 2, 3, 0, 0, 0 }; int m = 3;
// int[] nums2 = { 2, 5, 6 }; int n = 3;
// MergeSortedArrays(nums1, m, nums2, n);
// // nums1 will be { 1, 2, 2, 3, 5, 6 }

Explanation: This solution merges from the end of nums1 to avoid overwriting existing valid elements. It uses three pointers: p1 for nums1's valid elements, p2 for nums2, and p for the current merge position in nums1. It compares elements from both arrays and places the larger one at the current p position, then decrements the respective pointer and p. Any remaining elements in nums2 are then copied.


16. Implement a Basic Stack (using Array or List)

Explanation: Tests understanding of LIFO (Last-In, First-Out) data structure.

Question: Implement a basic Stack data structure in C# with Push, Pop, and Peek operations. Handle potential StackEmptyException.

Answer:

C#
public class CustomStack<T>
{
    private List<T> _items;

    public CustomStack()
    {
        _items = new List<T>();
    }

    public int Count => _items.Count;

    public bool IsEmpty => _items.Count == 0;

    public void Push(T item)
    {
        _items.Add(item);
    }

    public T Pop()
    {
        if (IsEmpty)
        {
            throw new InvalidOperationException("Stack is empty.");
        }
        T item = _items[_items.Count - 1];
        _items.RemoveAt(_items.Count - 1);
        return item;
    }

    public T Peek()
    {
        if (IsEmpty)
        {
            throw new InvalidOperationException("Stack is empty.");
        }
        return _items[_items.Count - 1];
    }
}

// Example Usage:
// var myStack = new CustomStack<int>();
// myStack.Push(10);
// myStack.Push(20);
// Console.WriteLine(myStack.Peek()); // 20
// Console.WriteLine(myStack.Pop()); // 20
// Console.WriteLine(myStack.Pop()); // 10
// // myStack.Pop(); // Throws InvalidOperationException

Explanation: The CustomStack class uses a List<T> internally to store elements. Push adds to the end of the list. Pop removes and returns the last element, while Peek just returns it, both throwing an exception if the stack is empty.


17. Implement a Basic Queue (using Array or List)

Explanation: Tests understanding of FIFO (First-In, First-Out) data structure.

Question: Implement a basic Queue data structure in C# with Enqueue, Dequeue, and Peek operations. Handle potential QueueEmptyException.

Answer:

C#
public class CustomQueue<T>
{
    private List<T> _items;

    public CustomQueue()
    {
        _items = new List<T>();
    }

    public int Count => _items.Count;

    public bool IsEmpty => _items.Count == 0;

    public void Enqueue(T item)
    {
        _items.Add(item);
    }

    public T Dequeue()
    {
        if (IsEmpty)
        {
            throw new InvalidOperationException("Queue is empty.");
        }
        T item = _items[0];
        _items.RemoveAt(0); // This can be inefficient for large queues
        return item;
    }

    public T Peek()
    {
        if (IsEmpty)
        {
            throw new InvalidOperationException("Queue is empty.");
        }
        return _items[0];
    }
}

// Example Usage:
// var myQueue = new CustomQueue<string>();
// myQueue.Enqueue("first");
// myQueue.Enqueue("second");
// Console.WriteLine(myQueue.Peek()); // first
// Console.WriteLine(myQueue.Dequeue()); // first
// Console.WriteLine(myQueue.Dequeue()); // second
// // myQueue.Dequeue(); // Throws InvalidOperationException

Explanation: The CustomQueue class also uses a List<T>. Enqueue adds to the end. Dequeue removes and returns the first element, while Peek just returns it. Note: List<T>.RemoveAt(0) can be inefficient for very large queues as it requires shifting all subsequent elements. For production, Queue<T> or a LinkedList<T> would be more efficient for queue operations.


18. Anagram Checker

Explanation: Tests string manipulation, character frequency, and dictionary usage.

Question: Given two strings s and t, return true if t is an anagram of s, and false otherwise. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Answer:

C#
public bool IsAnagram(string s, string t)
{
    if (s.Length != t.Length)
    {
        return false;
    }

    // Using a simple int array for ASCII characters, or a Dictionary<char, int> for Unicode
    // int[] charCounts = new int[26]; // For lowercase English letters

    Dictionary<char, int> charCounts = new Dictionary<char, int>();

    foreach (char c in s)
    {
        if (charCounts.ContainsKey(c))
        {
            charCounts[c]++;
        }
        else
        {
            charCounts.Add(c, 1);
        }
    }

    foreach (char c in t)
    {
        if (!charCounts.ContainsKey(c) || charCounts[c] == 0)
        {
            return false; // Character not found or count is zero
        }
        charCounts[c]--;
    }

    // At this point, all counts should be zero if it's an anagram.
    // No need to explicitly check all values if logic is sound.
    // (If s.Length == t.Length and all chars in t found in s, implies it's an anagram)
    return true;
}

// Example Usage:
// bool result1 = IsAnagram("anagram", "nagaram"); // true
// bool result2 = IsAnagram("rat", "car"); // false

Explanation: The method first checks if the lengths are equal. Then, it counts character frequencies for the first string (s) using a dictionary. It then iterates through the second string (t), decrementing counts. If a character is not found or its count is already zero, it's not an anagram. If all characters in t are successfully accounted for, it's an anagram.


19. Find the Longest Substring Without Repeating Characters

Explanation: A common sliding window problem, tests character tracking and window management.

Question: Given a string s, find the length of the longest substring without repeating characters.

Answer:

C#
public int LengthOfLongestSubstring(string s)
{
    if (string.IsNullOrEmpty(s))
    {
        return 0;
    }

    int maxLength = 0;
    int left = 0; // Left pointer of the sliding window
    HashSet<char> charSet = new HashSet<char>(); // To track characters in the current window

    for (int right = 0; right < s.Length; right++)
    {
        while (charSet.Contains(s[right]))
        {
            // If the character is already in the set, shrink the window from the left
            charSet.Remove(s[left]);
            left++;
        }
        // Add the new character to the set
        charSet.Add(s[right]);
        // Update max length
        maxLength = Math.Max(maxLength, right - left + 1);
    }

    return maxLength;
}

// Example Usage:
// int len1 = LengthOfLongestSubstring("abcabcbb"); // 3 (abc)
// int len2 = LengthOfLongestSubstring("bbbbb"); // 1 (b)
// int len3 = LengthOfLongestSubstring("pwwkew"); // 3 (wke or kew)

Explanation: This solution uses a "sliding window" approach with a HashSet<char> to efficiently check for duplicate characters within the current window. The right pointer expands the window. If a duplicate is found, the left pointer moves forward, removing characters from the set, until the duplicate is no longer in the window. maxLength is updated at each step.


20. Two Sum Problem

Explanation: A very common interview question, tests hash table/dictionary usage for efficient lookup.

Question: Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. Assume that each input would have exactly one solution, and you may not use the same element twice.

Answer:

C#
public int[] TwoSum(int[] nums, int target)
{
    if (nums == null || nums.Length < 2)
    {
        throw new ArgumentException("Input array must contain at least two elements.");
    }

    // Use a dictionary to store number -> index mappings
    Dictionary<int, int> numMap = new Dictionary<int, int>();

    for (int i = 0; i < nums.Length; i++)
    {
        int complement = target - nums[i];

        // Check if the complement exists in the dictionary
        if (numMap.ContainsKey(complement))
        {
            return new int[] { numMap[complement], i };
        }

        // Add the current number and its index to the dictionary
        // Only add if not already present (handles cases where target/2 might be involved)
        // If an element can be used only once, and there's exactly one solution,
        // it's safe to just add if it's not the complement.
        if (!numMap.ContainsKey(nums[i]))
        {
            numMap.Add(nums[i], i);
        }
    }

    // According to the problem statement, there's always exactly one solution.
    // This line should theoretically not be reached if inputs are valid.
    return new int[] { }; // Or throw an exception if no solution is guaranteed
}

// Example Usage:
// int[] nums1 = { 2, 7, 11, 15 }; int target1 = 9;
// int[] result1 = TwoSum(nums1, target1); // { 0, 1 } (because nums[0] + nums[1] == 9)

// int[] nums2 = { 3, 2, 4 }; int target2 = 6;
// int[] result2 = TwoSum(nums2, target2); // { 1, 2 } (because nums[1] + nums[2] == 6)

Explanation: This solution uses a Dictionary<int, int> (hash table) for efficient lookups. For each number nums[i] in the array, it calculates the complement needed to reach the target. It then checks if this complement already exists in the dictionary. If it does, we've found our pair, and their indices are returned. Otherwise, the current number and its index are added to the dictionary for future lookups. This approach achieves O(n) time complexity.


Conclusion:

Mastering these algorithmic and problem-solving questions, alongside your .NET Core framework knowledge, will significantly boost your confidence and performance in technical interviews. Practice implementing these solutions, understand their time and space complexities, and be prepared to discuss trade-offs and alternative approaches. Good luck!

Comments

Popular posts from this blog

Top 30 Tricky C# Coding Interview Questions (With Solutions)

  1. Reverse a String Without Built-in Methods Q: Write a C# method to reverse a string without using built-in reverse functions. A: string Reverse(string input) {     char[] result = new char[input.Length];     for (int i = 0; i < input.Length; i++)         result[i] = input[input.Length - 1 - i];     return new string(result); } 2. Find Duplicates in an Integer Array Q: Detect and print duplicates in an integer array. A: void FindDuplicates(int[] arr) {     var seen = new HashSet<int>();     foreach (int num in arr) {         if (seen.Contains(num))             Console.WriteLine("Duplicate: " + num);         else             seen.Add(num);   ...

Cracking the Code: Your Guide to the Top 60 C# Interview Questions

So, you're gearing up for a C# interview? Fantastic! This powerful and versatile language is a cornerstone of modern software development, and landing that C# role can open up a world of exciting opportunities. But navigating the interview process can feel like traversing a complex codebase. Fear not! We've compiled a comprehensive list of the top 60 C# interview questions, complete with detailed answers, to help you ace your next technical challenge. Whether you're just starting your C# journey or you're a seasoned pro looking to brush up your knowledge, this guide has something for you. We've broken down the questions into three levels: Beginner, Intermediate, and Advanced, allowing you to focus on the areas most relevant to your experience. Let's dive in and equip you with the knowledge you need to shine! Beginner Level (1–20) 1. What is C#? C# is a modern, object-oriented programming language developed by Microsoft as part of its .NET platform. It is design...