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
- private static string ReverseAString(string sInput) {
- string sReverseString = string.Empty;
- int iStringLength = sInput.Length - 1;
- while (iStringLength >= 0) {
- sReverseString += sInput[iStringLength];
- iStringLength--;
- }
-
- return sReverseString;
- }
NoteFor 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
- public class Solution {
- public int Reverse(int x) {
- long lReverse = 0;
- while (x != 0)
- {
- lReverse = (lReverse * 10) + x % 10;
- x = x / 10;
- }
- return lReverse==(int)lReverse?(int)lReverse:0;
- }
- }
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
- public class Solution {
- public int[] ProductExceptSelf(int[] nums) {
- int n = nums.Length;
-
- int[] leftArr = new int[n];
- int[] rightArr = new int[n];
-
- int[] prodArr = new int[n];
-
- leftArr[0] = 1;
- rightArr[n - 1] = 1;
-
- for (int i = 1; i < n; i++)
- {
- leftArr[i] = nums[i - 1] * leftArr[i - 1];
- }
-
-
- for (int i = n - 2; i >= 0; i--)
- {
- rightArr[i] = nums[i + 1] * rightArr[i + 1];
- }
-
-
- for (int i = 0; i < n; i++)
- {
- prodArr[i] = leftArr[i] * rightArr[i];
-
- }
-
- return prodArr;
- }
- }
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
- class Program
- {
- static void Main(string[] args)
- {
- List<int> lst= new List<int>(){12, 15, 9, 8};
- int sum = 20;
-
- Console.WriteLine(ValidateResult(lst, sum) ? "True" : "False");
- Console.Read();
- }
-
- private static bool ValidateResult(List<int> lst, int sum)
- {
- return lst.Any(t => lst.Contains(sum - t));
- }
- }
Hope you enjoyed the content of this blog. Stay Tuned!!!!