We all know the importance of the algorithm in computer programming. Solving algorithms helps us to hone our coding and program solving skills. I am currently practicing various algorithms and had a thought to share with the community so that I can get suggestions, better solutions on it and also it will help others.
In this series, I will be sharing some algorithm problems and my solutions to the algorithm. The solutions are written in C#.
Problem 1- Reverse a String
Difficulty level- Easy
Test Cases:
Input- Test Output- tseT

Solution
  1. private static string ReverseAString(string sInput) {
  2. string sReverseString = string.Empty;
  3. int iStringLength = sInput.Length - 1;
  4. while (iStringLength >= 0) {
  5. sReverseString += sInput[iStringLength];
  6. iStringLength--;
  7. }
  8. return sReverseString;
  9. }
Note
For Reverse string using a stack, you can refer to my blog.
Problem 2- Reverse an integer
Given a 32-bit signed integer, reverse digits of an integer.
Note
The function should return 0 when the reversed integer overflows.
Difficulty level- Easy
Test Cases-
Input- 1234 Output-4321
Input-1534236469 Output-0
Solution
  1. public class Solution {
  2. public int Reverse(int x) {
  3. long lReverse = 0;
  4. while (x != 0)
  5. {
  6. lReverse = (lReverse * 10) + x % 10;
  7. x = x / 10;
  8. }
  9. return lReverse==(int)lReverse?(int)lReverse:0;
  10. }
  11. }
Problem 3
Product of an Array. Given an integer array nums where n > 1, return an output array such that output[i] is equal to the product of all the elements of nums except nums[i].
Difficulty level- Medium
Test Cases
Input- [1, 2, 3, 4, 5] Output- [24,12,8,6]
Input- [3, 2, 1] Output- [2, 3, 6].
Solution
  1. public class Solution {
  2. public int[] ProductExceptSelf(int[] nums) {
  3. int n = nums.Length;
  4. int[] leftArr = new int[n];
  5. int[] rightArr = new int[n];
  6. int[] prodArr = new int[n];
  7. leftArr[0] = 1;
  8. rightArr[n - 1] = 1;
  9. for (int i = 1; i < n; i++)
  10. {
  11. leftArr[i] = nums[i - 1] * leftArr[i - 1];
  12. }
  13. for (int i = n - 2; i >= 0; i--)
  14. {
  15. rightArr[i] = nums[i + 1] * rightArr[i + 1];
  16. }
  17. for (int i = 0; i < n; i++)
  18. {
  19. prodArr[i] = leftArr[i] * rightArr[i];
  20. }
  21. return prodArr;
  22. }
  23. }
Problem 4
Given a list of numbers and a number Sum, return whether any two numbers from the list add up to Sum.
Difficulty level- Easy
Test Case- Given [12, 15, 9, 8] and Sum of 20, return true since 12 + 8 is 20.
Solution
  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. List<int> lst= new List<int>(){12, 15, 9, 8};
  6. int sum = 20;
  7. Console.WriteLine(ValidateResult(lst, sum) ? "True" : "False");
  8. Console.Read();
  9. }
  10. private static bool ValidateResult(List<int> lst, int sum)
  11. {
  12. return lst.Any(t => lst.Contains(sum - t));
  13. }
  14. }
Hope you enjoyed the content of this blog. Stay Tuned!!!!