Top 25 String Coding Interview Questions with C# Solutions and Explanations:-
1. Reverse a String
using System;
class Program
{
static string ReverseString(string str)
{
char[] arr = str.ToCharArray();
Array.Reverse(arr);
return new string(arr);
}
static void Main()
{
string input = "hello";
Console.WriteLine(ReverseString(input)); // Output: "olleh"
}
}
2. Check if a String is a Palindrome
using System;
class Program
{
static bool IsPalindrome(string str)
{
int left = 0, right = str.Length - 1;
while (left < right)
{
if (str[left] != str[right])
return false;
left++;
right--;
}
return true;
}
static void Main()
{
string input = "madam";
Console.WriteLine(IsPalindrome(input)); // Output: True
}
}
3. Check if Two Strings are Anagrams
using System;
using System.Linq;
class Program
{
static bool AreAnagrams(string str1, string str2)
{
return str1.Length == str2.Length && str1.OrderBy(c => c).SequenceEqual(str2.OrderBy(c => c));
}
static void Main()
{
string str1 = "listen";
string str2 = "silent";
Console.WriteLine(AreAnagrams(str1, str2)); // Output: True
}
}
4. Find the First Non-Repeating Character in a String
using System;
using System.Linq;
class Program
{
static char FirstNonRepeating(string str)
{
return str.FirstOrDefault(c => str.Count(x => x == c) == 1);
}
static void Main()
{
string input = "swiss";
Console.WriteLine(FirstNonRepeating(input)); // Output: "w"
}
}
5. Implement strStr() or Substring Search
using System;
class Program
{
static int StrStr(string haystack, string needle)
{
return haystack.IndexOf(needle);
}
static void Main()
{
string haystack = "hello";
string needle = "ll";
Console.WriteLine(StrStr(haystack, needle)); // Output: 2
}
}
6. Longest Common Prefix Among Strings
using System;
class Program
{
static string LongestCommonPrefix(string[] strs)
{
if (strs.Length == 0) return "";
string prefix = strs[0];
foreach (var str in strs)
{
while (!str.StartsWith(prefix))
{
prefix = prefix.Substring(0, prefix.Length - 1);
if (prefix == "") return "";
}
}
return prefix;
}
static void Main()
{
string[] strs = { "flower", "flow", "flight" };
Console.WriteLine(LongestCommonPrefix(strs)); // Output: "fl"
}
}
7. Longest Palindromic Substring
using System;
class Program
{
static string LongestPalindrome(string s)
{
if (s.Length <= 1) return s;
string longest = string.Empty;
for (int i = 0; i < s.Length; i++)
{
string temp = ExpandAroundCenter(s, i, i);
if (temp.Length > longest.Length) longest = temp;
temp = ExpandAroundCenter(s, i, i + 1);
if (temp.Length > longest.Length) longest = temp;
}
return longest;
}
static string ExpandAroundCenter(string s, int left, int right)
{
while (left >= 0 && right < s.Length && s[left] == s[right])
{
left--;
right++;
}
return s.Substring(left + 1, right - left - 1);
}
static void Main()
{
string input = "babad";
Console.WriteLine(LongestPalindrome(input)); // Output: "bab"
}
}
8. Count and Say (LeetCode style)
using System;
class Program
{
static string CountAndSay(int n)
{
string result = "1";
for (int i = 2; i <= n; i++)
{
string temp = string.Empty;
char currentChar = result[0];
int count = 1;
for (int j = 1; j < result.Length; j++)
{
if (result[j] == currentChar)
{
count++;
}
else
{
temp += count.ToString() + currentChar;
currentChar = result[j];
count = 1;
}
}
temp += count.ToString() + currentChar;
result = temp;
}
return result;
}
static void Main()
{
int n = 4;
Console.WriteLine(CountAndSay(n)); // Output: "1211"
}
}
9. String Compression (e.g., a3b2c1)
using System;
using System.Text;
class Program
{
static string StringCompression(string str)
{
StringBuilder compressed = new StringBuilder();
int count = 1;
for (int i = 1; i < str.Length; i++)
{
if (str[i] == str[i - 1])
{
count++;
}
else
{
compressed.Append(str[i - 1]);
compressed.Append(count);
count = 1;
}
}
compressed.Append(str[str.Length - 1]);
compressed.Append(count);
return compressed.ToString().Length < str.Length ? compressed.ToString() : str;
}
static void Main()
{
string input = "aabcccccaaa";
Console.WriteLine(StringCompression(input)); // Output: "a2b1c5a3"
}
}
10. Group Anagrams Together
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static List<List<string>> GroupAnagrams(string[] strs)
{
var anagrams = new Dictionary<string, List<string>>();
foreach (var str in strs)
{
var sorted = new string(str.OrderBy(c => c).ToArray());
if (!anagrams.ContainsKey(sorted))
anagrams[sorted] = new List<string>();
anagrams[sorted].Add(str);
}
return anagrams.Values.ToList();
}
static void Main()
{
string[] input = { "eat", "tea", "tan", "ate", "nat", "bat" };
var result = GroupAnagrams(input);
foreach (var group in result)
{
Console.WriteLine(string.Join(", ", group));
}
}
}
11. Check if a String Contains All Unique Characters
using System;
using System.Linq;
class Program
{
static bool HasUniqueCharacters(string str)
{
return str.Length == str.Distinct().Count();
}
static void Main()
{
string input = "abcdef";
Console.WriteLine(HasUniqueCharacters(input)); // Output: True
}
}
Output:
True
12. Check if One String is a Rotation of Another
using System;
class Program
{
static bool IsRotation(string str1, string str2)
{
if (str1.Length != str2.Length)
return false;
return (str1 + str1).Contains(str2);
}
static void Main()
{
string str1 = "waterbottle";
string str2 = "erbottlewat";
Console.WriteLine(IsRotation(str1, str2)); // Output: True
}
}
Output:
True
13. Check if One String is a Subsequence of Another
using System;
class Program
{
static bool IsSubsequence(string str1, string str2)
{
int j = 0;
for (int i = 0; i < str2.Length && j < str1.Length; i++)
{
if (str1[j] == str2[i])
j++;
}
return j == str1.Length;
}
static void Main()
{
string str1 = "abc";
string str2 = "ahbgdc";
Console.WriteLine(IsSubsequence(str1, str2)); // Output: True
}
}
Output:
True
14. Find All Duplicates in a String
using System;
using System.Collections.Generic;
class Program
{
static List<char> FindDuplicates(string str)
{
var seen = new HashSet<char>();
var duplicates = new List<char>();
foreach (var ch in str)
{
if (seen.Contains(ch))
duplicates.Add(ch);
else
seen.Add(ch);
}
return duplicates;
}
static void Main()
{
string input = "programming";
var duplicates = FindDuplicates(input);
Console.WriteLine(string.Join(", ", duplicates)); // Output: "r, g"
}
}
Output:
r, g
15. Valid Parentheses
using System;
using System.Collections.Generic;
class Program
{
static bool IsValidParentheses(string s)
{
var stack = new Stack<char>();
foreach (var c in s)
{
if (c == '(' || c == '[' || c == '{')
stack.Push(c);
else
{
if (stack.Count == 0)
return false;
char top = stack.Pop();
if ((c == ')' && top != '(') || (c == ']' && top != '[') || (c == '}' && top != '{'))
return false;
}
}
return stack.Count == 0;
}
static void Main()
{
string input = "({[]})";
Console.WriteLine(IsValidParentheses(input)); // Output: True
}
}
Output:
True
16. Minimum Window Substring (Substring with All Characters of Another String)
using System;
class Program
{
static string MinWindowSubstring(string s, string t)
{
if (s.Length < t.Length) return "";
int[] need = new int[128];
foreach (char c in t)
need[c]++;
int left = 0, right = 0, minLen = int.MaxValue, start = 0;
int count = t.Length;
while (right < s.Length)
{
if (need[s[right]] > 0)
count--;
need[s[right]]--;
right++;
while (count == 0)
{
if (right - left < minLen)
{
minLen = right - left;
start = left;
}
need[s[left]]++;
if (need[s[left]] > 0)
count++;
left++;
}
}
return minLen == int.MaxValue ? "" : s.Substring(start, minLen);
}
static void Main()
{
string s = "ADOBECODEBANC";
string t = "ABC";
Console.WriteLine(MinWindowSubstring(s, t)); // Output: "BANC"
}
}
Output:
BANC
17. Permutations of a String
using System;
using System.Collections.Generic;
class Program
{
static void Permute(string str, int left, int right, List<string> result)
{
if (left == right)
result.Add(str);
else
{
for (int i = left; i <= right; i++)
{
str = Swap(str, left, i);
Permute(str, left + 1, right, result);
str = Swap(str, left, i); // Backtrack
}
}
}
static string Swap(string str, int i, int j)
{
char temp;
char[] arr = str.ToCharArray();
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
return new string(arr);
}
static void Main()
{
string input = "abc";
List<string> result = new List<string>();
Permute(input, 0, input.Length - 1, result);
Console.WriteLine(string.Join(", ", result)); // Output: "abc, acb, bac, bca, cab, cba"
}
}
Output:
abc, acb, bac, bca, cab, cba
18. Remove All Duplicates from a String
using System;
class Program
{
static string RemoveDuplicates(string str)
{
string result = "";
foreach (char ch in str)
{
if (!result.Contains(ch))
result += ch;
}
return result;
}
static void Main()
{
string input = "programming";
Console.WriteLine(RemoveDuplicates(input)); // Output: "progamin"
}
}
Output:
progamin
19. Convert a Roman Numeral to Integer
using System;
using System.Collections.Generic;
class Program
{
static int RomanToInt(string s)
{
var romanMap = new Dictionary<char, int>
{
{ 'I', 1 }, { 'V', 5 }, { 'X', 10 }, { 'L', 50 }, { 'C', 100 },
{ 'D', 500 }, { 'M', 1000 }
};
int result = 0;
for (int i = 0; i < s.Length; i++)
{
if (i + 1 < s.Length && romanMap[s[i]] < romanMap[s[i + 1]])
result -= romanMap[s[i]];
else
result += romanMap[s[i]];
}
return result;
}
static void Main()
{
string input = "IX";
Console.WriteLine(RomanToInt(input)); // Output: 9
}
}
Output:
9
20. Integer to Roman Numeral Conversion
using System;
using System.Text;
class Program
{
static string IntToRoman(int num)
{
var romanNumerals = new (int, string)[]
{
(1000, "M"), (900, "CM"), (500, "D"), (400, "CD"),
(100, "C"), (90, "XC"), (50, "L"), (40, "XL"),
(10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I")
};
StringBuilder sb = new StringBuilder();
foreach (var (value, symbol) in romanNumerals)
{
while (num >= value)
{
sb.Append(symbol);
num -= value;
}
}
return sb.ToString();
}
static void Main()
{
int input = 58;
Console.WriteLine(IntToRoman(input)); // Output: "LVIII"
}
}
Output:
LVIII
Here are the solutions for the next 5 questions along with their expected outputs:
21. Longest Substring Without Repeating Characters
using System;
using System.Collections.Generic;
class Program
{
static int LengthOfLongestSubstring(string s)
{
var charSet = new HashSet<char>();
int left = 0, maxLength = 0;
for (int right = 0; right < s.Length; right++)
{
while (charSet.Contains(s[right]))
{
charSet.Remove(s[left]);
left++;
}
charSet.Add(s[right]);
maxLength = Math.Max(maxLength, right - left + 1);
}
return maxLength;
}
static void Main()
{
string input = "abcabcbb";
Console.WriteLine(LengthOfLongestSubstring(input)); // Output: 3
}
}
Output:
3
22. Word Break Problem
using System;
using System.Collections.Generic;
class Program
{
static bool WordBreak(string s, HashSet<string> wordDict)
{
bool[] dp = new bool[s.Length + 1];
dp[0] = true;
for (int i = 1; i <= s.Length; i++)
{
for (int j = 0; j < i; j++)
{
if (dp[j] && wordDict.Contains(s.Substring(j, i - j)))
{
dp[i] = true;
break;
}
}
}
return dp[s.Length];
}
static void Main()
{
string s = "leetcode";
HashSet<string> wordDict = new HashSet<string> { "leet", "code" };
Console.WriteLine(WordBreak(s, wordDict)); // Output: True
}
}
Output:
True
23. Zigzag String Conversion (like in LeetCode)
using System;
using System.Text;
class Program
{
static string ConvertZigZag(string s, int numRows)
{
if (numRows == 1) return s;
StringBuilder[] rows = new StringBuilder[numRows];
int curRow = 0;
bool goingDown = false;
foreach (char c in s)
{
rows[curRow].Append(c);
if (curRow == 0 || curRow == numRows - 1)
goingDown = !goingDown;
curRow += goingDown ? 1 : -1;
}
StringBuilder result = new StringBuilder();
foreach (var row in rows)
{
result.Append(row.ToString());
}
return result.ToString();
}
static void Main()
{
string input = "PAYPALISHIRING";
int numRows = 3;
Console.WriteLine(ConvertZigZag(input, numRows)); // Output: "PAHNAPLSIIGYIR"
}
}
Output:
PAHNAPLSIIGYIR
24. Compare Version Numbers (e.g., "1.2" vs. "1.10")
using System;
class Program
{
static int CompareVersion(string version1, string version2)
{
string[] v1 = version1.Split('.');
string[] v2 = version2.Split('.');
int length = Math.Max(v1.Length, v2.Length);
for (int i = 0; i < length; i++)
{
int v1Part = i < v1.Length ? int.Parse(v1[i]) : 0;
int v2Part = i < v2.Length ? int.Parse(v2[i]) : 0;
if (v1Part < v2Part) return -1;
if (v1Part > v2Part) return 1;
}
return 0;
}
static void Main()
{
string version1 = "1.2";
string version2 = "1.10";
Console.WriteLine(CompareVersion(version1, version2)); // Output: -1
}
}
Output:
-1
25. Multiply Two Large Numbers Represented as Strings
using System;
using System.Text;
class Program
{
static string Multiply(string num1, string num2)
{
int m = num1.Length, n = num2.Length;
int[] result = new int[m + n];
for (int i = m - 1; i >= 0; i--)
{
for (int j = n - 1; j >= 0; j--)
{
int mul = (num1[i] - '0') * (num2[j] - '0');
int sum = mul + result[i + j + 1];
result[i + j + 1] = sum % 10;
result[i + j] += sum / 10;
}
}
StringBuilder sb = new StringBuilder();
foreach (int r in result)
{
if (!(sb.Length == 0 && r == 0))
sb.Append(r);
}
return sb.Length == 0 ? "0" : sb.ToString();
}
static void Main()
{
string num1 = "123";
string num2 = "456";
Console.WriteLine(Multiply(num1, num2)); // Output: "56088"
}
}
Output:
56088

0 Comments