Top 10 DSA Questions in C#

Top 10 DSA Questions in C#

🚀 Top 10 DSA Questions in C#

For Interviews & Practice

1. Reverse a String

string str = "hello";
char[] arr = str.ToCharArray();
Array.Reverse(arr);
Console.WriteLine(new string(arr));

2. Palindrome Check

string str = "madam";
string rev = new string(str.Reverse().ToArray());
Console.WriteLine(str == rev ? "Palindrome" : "Not");

3. Maximum in Array

int[] arr = {1,5,3,9,2};
int max = arr[0];
foreach(int i in arr)
{
    if(i > max) max = i;
}
Console.WriteLine(max);

4. Fibonacci Series

int a = 0, b = 1;
for(int i = 0; i < 10; i++)
{
    Console.Write(a + " ");
    int temp = a + b;
    a = b;
    b = temp;
}

5. Two Sum

int[] nums = {2,7,11,15};
int target = 9;
Dictionary<int,int> map = new Dictionary<int,int>();

for(int i=0;i<nums.Length;i++)
{
    int diff = target - nums[i];
    if(map.ContainsKey(diff))
        Console.WriteLine(map[diff] + "," + i);
    map[nums[i]] = i;
}

6. Remove Duplicates

int[] arr = {1,2,2,3};
var res = arr.Distinct();
foreach(var i in res)
    Console.Write(i);

7. Missing Number

int[] arr = {1,2,4,5};
int n = 5;
int sum = n*(n+1)/2;
Console.WriteLine(sum - arr.Sum());

8. Binary Search

int[] arr = {1,2,3,4,5};
int target = 4;
int l=0,r=arr.Length-1;

while(l<=r)
{
    int mid=(l+r)/2;
    if(arr[mid]==target) break;
    else if(arr[mid]<target) l=mid+1;
    else r=mid-1;
}

9. Valid Parentheses

Stack<char> s = new Stack<char>();
string str="()[]{}";

foreach(char c in str)
{
    if("([{".Contains(c)) s.Push(c);
    else s.Pop();
}
Console.WriteLine(s.Count==0?"Valid":"Invalid");

10. Sliding Window

int[] arr = {2,1,5,1,3,2};
int k = 3, sum = 0, max = 0;

for(int i=0;i<arr.Length;i++)
{
    sum += arr[i];
    if(i>=k-1)
    {
        max = Math.Max(max,sum);
        sum -= arr[i-(k-1)];
    }
}
Console.WriteLine(max);

Created by Koustubh Javheri

Keep Coding 🚀

Comments

Popular posts from this blog

DSA Easy Notes (C#)