Array, String and String Builder in C#

 Q1. How do you reverse a string in C#?

Answer

public string ReverseString(string input)
{
    char[] charArray = input.ToCharArray();
    Array.Reverse(charArray);
    return new string(charArray);
}

Explanation: This method converts the string to a character array, reverses it, and then constructs a new string from the reversed array.

 Q2. How can you check if a string is a palindrome?

Answer

public bool IsPalindrome(string input)
{
    int min = 0;
    int max = input.Length - 1;
    while (true)
    {
        if (min >= max)
        {
            return true;
        }
        char minChar = input[min];
        char maxChar = input[max];
        if (char.ToLower(minChar) != char.ToLower(maxChar))
        {
            return false;
        }
        min++;
        max--;
    }
}

Explanation: This method compares characters from the start and end of the string moving towards the center. If all characters match, the string is a palindrome.

 Q3. How do you find the longest common prefix in an array of strings?

Answer

public string LongestCommonPrefix(string[] strs)
{
    if (strs == null || strs.Length == 0) return "";
    string prefix = strs[0];
    for (int i = 1; i < strs.Length; i++)
    {
        while (strs[i].IndexOf(prefix) != 0)
        {
            prefix = prefix.Substring(0, prefix.Length - 1);
            if (string.IsNullOrEmpty(prefix)) return "";
        }
    }
    return prefix;
}

Explanation: This method iterates through the array, reducing the prefix until it matches the start of each string.

 Q4. How can you find the most frequent element in an array?

Answer

public int MostFrequentElement(int[] arr)
{
    Dictionary frequency = new Dictionary();
    foreach (int num in arr)
    {
        if (frequency.ContainsKey(num))
        {
            frequency[num]++;
        }
        else
        {
            frequency[num] = 1;
        }
    }
    return frequency.Aggregate((l, r) => l.Value > r.Value ? l : r).Key;
}

Explanation: This method uses a dictionary to count occurrences of each element and returns the one with the highest count.

 Q5. How do you check if two strings are anagrams?

Answer

public bool AreAnagrams(string s1, string s2)
{
    if (s1.Length != s2.Length) return false;
    var charCount = new int[26];
    foreach (char c in s1)
    {
        charCount[c - 'a']++;
    }
    foreach (char c in s2)
    {
        if (--charCount[c - 'a'] < 0)
        {
            return false;
        }
    }
    return true;
}

Explanation: This method counts the occurrences of each character in both strings and compares the counts.

 Q6. How can you remove duplicates from an array?

Answer

public int[] RemoveDuplicates(int[] arr)
{
    return arr.Distinct().ToArray();
}

Explanation: This method uses LINQ's Distinct method to remove duplicates from the array.

 Q7. How do you find the second largest element in an array?

Answer

public int SecondLargest(int[] arr)
{
    int largest = int.MinValue, secondLargest = int.MinValue;
    foreach (int num in arr)
    {
        if (num > largest)
        {
            secondLargest = largest;
            largest = num;
        }
        else if (num > secondLargest && num != largest)
        {
            secondLargest = num;
        }
    }
    return secondLargest;
}

Explanation: This method iterates through the array to find the largest and second largest elements.

 Q8. How can you merge two sorted arrays into one sorted array?

Answer

public int[] MergeSortedArrays(int[] arr1, int[] arr2)
{
    int[] mergedArray = new int[arr1.Length + arr2.Length];
    int i = 0, j = 0, k = 0;
    while (i < arr1.Length && j < arr2.Length)
    {
        if (arr1[i] < arr2[j])
        {
            mergedArray[k++] = arr1[i++];
        }
        else
        {
            mergedArray[k++] = arr2[j++];
        }
    }
    while (i < arr1.Length)
    {
        mergedArray[k++] = arr1[i++];
    }
    while (j < arr2.Length)
    {
        mergedArray[k++] = arr2[j++];
    }
    return mergedArray;
}

Explanation: This method merges two sorted arrays by comparing elements and adding the smaller one to the result array.

 Q9. How do you find the intersection of two arrays?

Answer

public int[] Intersection(int[] arr1, int[] arr2)
{
    return arr1.Intersect(arr2).ToArray();
}

Explanation: This method uses LINQ's Intersect method to find common elements between two arrays.

 Q10. How can you rotate an array to the right by k steps?

Answer

public void RotateArray(int[] arr, int k)
{
    k = k % arr.Length;
    Reverse(arr, 0, arr.Length - 1);
    Reverse(arr, 0, k - 1);
    Reverse(arr, k, arr.Length - 1);
}

private void Reverse(int[] arr, int start, int end)
{
    while (start < end)
    {
        int temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;
        start++;
        end--;
    }
}

Explanation: This method reverses parts of the array to achieve the desired rotation.

 Q11. How do you check if a string contains only digits?

Answer

public bool IsDigitsOnly(string str)
{
    foreach (char c in str)
    {
        if (c < '0' || c > '9') return false;
    }
    return true;
}

Explanation: This method checks each character in the string to ensure it is a digit.

 Q12. How can you find the first non-repeating character in a string?

Answer

public char FirstNonRepeatingChar(string str)
{
    Dictionary charCount = new Dictionary();
    foreach (char c in str)
    {
        if (charCount.ContainsKey(c))
        {
            charCount[c]++;
        }
        else
        {
            charCount[c] = 1;
        }
    }
    foreach (char c in str)
    {
        if (charCount[c] == 1)
        {
            return c;
        }
    }
    return '\0';
}

Explanation: This method counts occurrences of each character and returns the first one that appears only once.

 Q13. How do you remove all whitespace from a string?

Answer

public string RemoveWhitespace(string str)
{
    return new string(str.Where(c => !char.IsWhiteSpace(c)).ToArray());
}

Explanation: This method uses LINQ to filter out all whitespace characters from the string.

 Q14. How can you check if a string is a valid email address?

Answer

public bool IsValidEmail(string email)
{
    try
    {
        var addr = new System.Net.Mail.MailAddress(email);
        return addr.Address == email;
    }
    catch
    {
        return false;
    }
}

Explanation: This method uses the MailAddress class to validate the email format.

 Q15. How do you find the longest substring without repeating characters?

Answer

public string LongestSubstringWithoutRepeating(string str)
{
    int n = str.Length;
    int maxLength = 0, start = 0;
    Dictionary charIndexMap = new Dictionary();
    for (int i = 0; i < n; i++)
    {
        if (charIndexMap.ContainsKey(str[i]))
        {
            start = Math.Max(start, charIndexMap[str[i]] + 1);
        }
        charIndexMap[str[i]] = i;
        maxLength = Math.Max(maxLength, i - start + 1);
    }
    return str.Substring(start, maxLength);
}

Explanation: This method uses a sliding window approach to find the longest substring without repeating characters.


Looking for more Microservice resources? Read our Master Microservices: Top 30 Interview Questions and Answers for 2025  to build a strong foundation!


 Q16. How can you reverse the words in a string?

Answer

public string ReverseWords(string str)
{
    return string.Join(" ", str.Split(' ').Reverse());
}

Explanation: This method splits the string into words, reverses the order of the words, and joins them back into a string.

 Q17. How do you check if a string is a valid palindrome ignoring non-alphanumeric characters?

Answer

public bool IsValidPalindrome(string str)
{
    int left = 0, right = str.Length - 1;
    while (left < right)
    {
        if (!char.IsLetterOrDigit(str[left]))
        {
            left++;
        }
        else if (!char.IsLetterOrDigit(str[right]))
        {
            right--;
        }
        else if (char.ToLower(str[left]) != char.ToLower(str[right]))
        {
            return false;
        }
        else
        {
            left++;
            right--;
        }
    }
    return true;
}

Explanation: This method ignores non-alphanumeric characters and checks if the string is a palindrome.

 Q18. How can you find the shortest palindrome by adding characters at the beginning?

Answer

public string ShortestPalindrome(string s)
{
    string revS = new string(s.Reverse().ToArray());
    for (int i = 0; i < s.Length; i++)
    {
        if (s.StartsWith(revS.Substring(i)))
        {
            return revS.Substring(0, i) + s;
        }
    }
    return "";
}

Explanation: This method finds the shortest palindrome by adding the minimum number of characters to the beginning of the string.


Looking for more ASP.NET Core resources? Read our Most important ASP.NET Web Forms Interview Questions to build a strong foundation!


 Q19. How do you find all permutations of a string?

Answer

public IList Permute(string s)
{
    IList result = new List();
    PermuteHelper(s.ToCharArray(), 0, result);
    return result;
}

private void PermuteHelper(char[] chars, int start, IList result)
{
    if (start == chars.Length - 1)
    {
        result.Add(new string(chars));
    }
    else
    {
        for (int i = start; i < chars.Length; i++)
        {
            Swap(ref chars[start], ref chars[i]);
            PermuteHelper(chars, start + 1, result);
            Swap(ref chars[start], ref chars[i]);
        }
    }
}

private void Swap(ref char a, ref char b)
{
    char temp = a;
    a = b;
    b = temp;
}

Explanation: This method generates all permutations of a string using recursion and swapping.

 Q20. How can you find the length of the last word in a string?

Answer

public int LengthOfLastWord(string s)
{
    s = s.Trim();
    int length = 0;
    for (int i = s.Length - 1; i >= 0; i--)
    {
        if (s[i] == ' ')
        {
            break;
        }
        length++;
    }
    return length;
}

Explanation: This method trims the string and counts the characters in the last word.



Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.

#buttons=(Ok, Go it!) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Ok, Go it!