Equal Stacks in C#

Problem Source – Equal Stacks – Hackerrank

You have three stacks of cylinders where each cylinder has the same diameter, but they may vary in height. You can change the height of a stack by removing and discarding its topmost cylinder any number of times.

Find the maximum possible height of the stacks such that all of the stacks are exactly the same height. This means you must remove zero or more cylinders from the top of zero or more of the three stacks until they’re all the same height, then print the height. The removals must be performed in such a way as to maximize the height.

Note: An empty stack is still a stack.

Input Format:

The first line contains three space-separated integers, n1, n2, and n3, describing the respective number of cylinders in stacks 1, 2, and 3. The subsequent lines describe the respective heights of each cylinder in a stack from top to bottom:

  • The second line contains n1 space-separated integers describing the cylinder heights in stack 1.
  • The third line contains n2  space-separated integers describing the cylinder heights in stack 2.
  • The fourth line contains n3  space-separated integers describing the cylinder heights in stack 3.

Constraints:

0 < n1, n2, n3 <= 10^5

0 < height of any cylinder <= 100

Output Format:

Print a single integer denoting the maximum height at which all stacks will be of equal height.

Sample Input:

5 3 4
3 2 1 1 1
4 3 2
1 1 4 1

Sample Output

5

Explanation:

Initially, the stacks look like this:

initial stacks

Observe that the three stacks are not all the same height. To make all stacks of equal height, we remove the first cylinder from stacks 1 and 2, and then remove the top two cylinders from stack 3(shown below).

modified stacks

As a result, the stacks undergo the following change in height:

  1. 8 – 3 = 5
  2. 9 – 4 = 5
  3. 7 – 1 – 1 = 5

Algorithm:

As our task is to find maximum possible height of stacks that means maximum height is common height of all the stacks. Below are the steps to compute common height for all the stacks:

  1. First get the sum of all the cylinders of each stack and hold this sum in separate variables i.e. sum1, sum2, sum3.
  2. Start looping till sum1, sum2 and sum3 are not equal.
    1. check if height of stack1 is higher than other stacks then pop top cylinder and reduce sum1 by that cylinder weight.
    2. check if height of stack2 is higher than other stacks then pop top cylinder and reduce sum2 by that cylinder weight.
    3. check if height of stack3 is higher than other stacks then pop top cylinder and reduce sum3 by that cylinder weight.
  3. Print the sum1. If there is nothing common the it’s value will be 0, otherwise it’ll have common height.

Code in C#:

static void Main(string[] args)
{
    var tokens_n1 = Console.ReadLine().Split(' ');
    var n1 = Convert.ToInt32(tokens_n1[0]);
    var n2 = Convert.ToInt32(tokens_n1[1]);
    var n3 = Convert.ToInt32(tokens_n1[2]);
 
    var h1_temp = new string[n1];
    var h2_temp = new string[n2];
    var h3_temp = new string[n3];
 
    h1_temp = Console.ReadLine().Split(' ');
    h2_temp = Console.ReadLine().Split(' ');
    h3_temp = Console.ReadLine().Split(' ');
 
    var st1 = new Stack<int>();
    var st2 = new Stack<int>();
    var st3 = new Stack<int>();
 
    int sum1 = 0, sum2 = 0, sum3 = 0;
 
    for (int i = h1_temp.Length - 1; i >= 0; i--)
    {
        st1.Push(Convert.ToInt32(h1_temp[i]));
        sum1 += Convert.ToInt32(h1_temp[i]);
    }
 
    for (int i = h2_temp.Length - 1; i >= 0; i--)
    {
        st2.Push(Convert.ToInt32(h2_temp[i]));
        sum2 += Convert.ToInt32(h2_temp[i]);
    }
 
    for (int i = h3_temp.Length - 1; i >= 0; i--)
    {
        st3.Push(Convert.ToInt32(h3_temp[i]));
        sum3 += Convert.ToInt32(h3_temp[i]);
    }
 
    while (!(sum1 == sum2 && sum2 == sum3))
    {
        if (sum1 < sum2 || sum3 < sum2)
        {
            sum2 -= st2.Pop();
        }
 
        if (sum1 < sum3 || sum2 < sum3)
        {
            sum3 -= st3.Pop();
        }
 
        if (sum2 < sum1 && sum3 < sum1)
        {
            sum1 -= st1.Pop();
        }
    }
 
    Console.WriteLine(sum1);
    Console.ReadKey();
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Balanced Brackets

Problem source: Balance Brackets – Hackerrank

Sample Input:

{[()]}
{[(])}
{{[[(())]]}}

Output:

YES
NO
YES

Algorithm:

The logic is quite simple, first check for basic failure conditions like,

  • Total numbers of characters are odd
  • First character is end of brackets like ‘)’, ‘}’, ‘]’

If basic checks are clear then we need to check for traverse whole input string and match start and end brackets and to do so we can use STACK. Follow below rules to verify perfect match:

  1. For every start bracket like ‘(‘, ‘{‘, ‘[‘, push it to stack.
  2. If Stack is empty and next bracket is ‘)’ or ‘}’ or ‘]’ then then it’s a failure.
  3. If Stack is not empty then check whether current item and popped item is match or not if not then it’s a failure.

Code in C#:

static void StackMethod()
{
    int n = Convert.ToInt32(Console.ReadLine());
    for (int i = 0; i < n; i++)
    {
        Stack<char> balancedBracket = new Stack<char>();
        string strInput = Console.ReadLine();
        bool isMatched = true;
        if (strInput.Length % 2 != 0 || strInput[0] == ')' 
            || strInput[0] == '}' || strInput[0] == ']')
        {
            Console.WriteLine("NO");
            continue;
        }
 
        foreach (var item in strInput)
        {
            if (item == '(' || item == '{' || item == '[')
            {
                balancedBracket.Push(item);
            }
            else if (balancedBracket.Count == 0 && (item == ')' 
                || item == '}' 
                || item == ']')
                )
            {
                isMatched = false;
                break;
            }
            else if (balancedBracket.Count > 0 && ((item == ')' 
                && balancedBracket.Pop() != '(') 
                || (item == '}' && balancedBracket.Pop() != '{') 
                || (item == ']' && balancedBracket.Pop() != '[')
                ))
            {
                isMatched = false;
                break;
            }
        }
        if (isMatched && balancedBracket.Count == 0)
        {
            Console.WriteLine("YES");
        }
        else
        {
            Console.WriteLine("NO");
        }
    }
    Console.ReadKey();
}

Find all pair of Array of Integers whose sum is equal to a given number in C#

It’s been a long time since I was trying to solve this problem. Whenever I tried I couldn’t solve it. I always miss some boundary conditions or something else. But today finally I solved it and it’s funny because approach is quite simple and I was trying code like building time machine 😛

Array : [2, 4, 3, 5, 6, -2, 4, 7, 8, 9]
Given sum : 7
pairs whose sum is equal to value : 7
(2, 5) , (4, 3) , (-2, 9)

Array : [0, 14, 0, 4, 7, 8, 3, 5, 7]
Sum : 11
pairs whose sum equals: 11
(7, 4) , (3, 8) , (7, 4)

Array : [10, 9, 5, 9, 0, 10, 2, 10, 1, 9]
Sum : 12
pairs whose sum equals 12
(2, 10)

There are two ways of doing this,

Method 1: Brute Force approach – use two nested loops and make a pair and compare sum of them with given number. Its time complexity would be O(n^2).

Method 2: In this method we loop over the array only once. For each item of array, subtract this item from given number and if array item doesn’t exist in our list then add it otherwise print this item and subtraction of array item and given number. Its time complexity would be O(n) as we loop over only once and comparison are also less.

Code in C#:

static void Main(string[] args)
{
    int[] arr = { 0, 14, 0, 4, 7, 11,8, 3, 5, 7 };
    int n = 11;
    PrintPairs(arr, n);
    Console.ReadKey();
}
 
private static void PrintPairs(int[] arr, int n)
{
    var arrayItemList = new List<int>();
    foreach (var item in arr)
    {
        int remainingvalue = n - item;
        if (arrayItemList.Contains(remainingvalue))
        {
            Console.WriteLine($"({ item},{remainingvalue})");
        }
        else
        {
            arrayItemList.Add(item);
        }
    }
}

Stack Maximum Element and performance

Problem Source: Maximum Element – Hackerrank

You have an empty sequence, and you will be given N queries. Each query is one of these three types:

1 x  -Push the element x into the stack.
2    -Delete the element present at the top of the stack.
3    -Print the maximum element in the stack.

Input Format

The first line of input contains an integer, N. The next N lines each contain an above mentioned query. (It is guaranteed that each query is valid.)

Constraints

1 <= N <= 10^5

1 <= x <= 10^9

Sample Input:

10
1 97
2
1 20
2
1 26
1 20
2
3
1 91
3

Sample Output

26
91

C# code:

class Test
{
    class CustomStack
    {
        public long Value { getset; }
        public long MaxValue { getset; }
    }
    static void Main(string[] args)
    {
        int N = Convert.ToInt32(Console.ReadLine());
        Stack<CustomStack> st = new Stack<CustomStack>();
        long maxInStack = 0;
        for (int i = 0; i < N; i++)
        {
            string[] str = Console.ReadLine().Split(' ');
            if (str[0] == "1")
            {
                long temp = Convert.ToInt64(str[1]);
                CustomStack cusSt = new CustomStack();
                if (temp > maxInStack)
                {
                    maxInStack = temp;
                }
                cusSt.Value = temp;
                cusSt.MaxValue = maxInStack;
                st.Push(cusSt);
            }
            else if (str[0] == "2")
            {
                st.Pop();
                if (st.Count > 0)
                {
                    maxInStack = st.Peek().MaxValue;
                }
                else
                {
                    maxInStack = 0;
                }
            }
            else if (str[0] == "3")
            {
                maxInStack = st.Peek().MaxValue;
                Console.WriteLine(maxInStack);
            }
        }
 
        Console.ReadKey();
    }
}

Array Left Rotation in C#

Problem source: Left Rotation – Hackerrank

Input: 

n = number of items in array

r = number of rotations

arr = integer array

Output:

Array items after “r” left rotation.

Example:

n = 5

r = 3

Arr = [1, 2, 3, 4, 5]

Output:

4 5 1 2 3

Explanation: 

Original Array: 1 2 3 4 5

1st rotation: 2 3 4 5 1

2nd rotation: 3 4 5 1 2

3rd rotation: 4 5 1 2 3

Algorithm: 

  1. If r % n = 0 that means there is no need of rotation because array items will be in same position after rotation.
  2. If r % n = i then we’ll split our original array into two parts.
    1. First part will have items from i to n.
    2. Second part will have items form 0 to i -1;
  3. Print this new array.

C# code:

static void Main(String[] args)
{
    var strInput = Console.ReadLine().Split(' ');
    var n = Convert.ToInt32(strInput[0]);
    var r = Convert.ToInt32(strInput[1]);
    var arr = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
    var finalRotationCount = r % n;
    if (finalRotationCount > 0)
    {
        var temp = new int[n];
        for (int i = 0; i < n - finalRotationCount; i++)
        {
            temp[i] = arr[finalRotationCount + i];
        }

        for (int i = 0; i < finalRotationCount; i++)
        {
            temp[n - finalRotationCount + i] = arr[i];
        }

        arr = temp;
    }
    Console.WriteLine(string.Join(" ", arr));
    Console.ReadKey();
}

 

Check whether a very big number is prime or not in C#

Problem source – HackeRrank – Running Time and Complexity

We all know how to check whether a number is prime number or not. As per the definition, a Prime number is a number that can be divisible only with 1 and itself. All other numbers are Non-Primes.

So, 1, 2, 5, 7, 11, 13, 19, 23, 29, 31 … are prime numbers, because all of these numbers can only be divided by either 1 or itself.

That’s theory, no lets see how actually we can check. Suppose you have a number n, so as per theory, if we can find any number other than 1 and n, that is perfect divisor then n is not a Prime number, otherwise it is.

If we try to implement above logic then we’ll have to try all the numbers from 2 to n, but wait a second and think one more time, the biggest divisor of a number can be half of the number.

so, in our case we don’t need to check all the numbers, just check till n/2. Because any number greater than n/2 can never be a divisor of n.

Awesome, now we just cut down half of the iterations and it’s really great in case of a very big number, like 1000000007.

But, half of 1000000007 is still a very big number. If you iterate it one at a time you might get timeout exception. So what do we do now?

hmmm….

hmmm…..

We can do one thing and it’ll solve our problem in case of very BIG NUMBERS. Instead of n/e, if you loop till Square root of n, then we are good. The logic behind this is:

If a number n is not a prime, it can be factored into two factors a and b:

n = a*b

If both a and b were greater than the square root of n, a*b would be greater than n. So at least one of those factors must be less than or equal to the square root of n, and to check if n is prime, we only need to test for factors less than or equal to the square root.

 

So now, we have solution of all the problems, no lets see the actual code:

    class BigPrimeNumbersIssue
    {
        static void Main(string[] args)
        {
            int T = Convert.ToInt16(Console.ReadLine());
            for (int i = 0; i < T; i++)
            {
                decimal number = Convert.ToDecimal(Console.ReadLine());
                if (number == 1)
                {
                    Console.WriteLine("Not prime");
                    continue;
                }
                else
                {
                    Console.WriteLine(IsPrime(number) ? "Prime" : "Not prime");
                }
            }
            Console.ReadKey();
        }

        private static bool IsPrime( decimal number)
        {
            bool isPrime = true;
            for (int j = 2; j * j <= number; j++)
            {
                if (number % j == 0)
                {
                    isPrime = false;
                    break;
                }
            }
            return isPrime;
        }
    }

Fill count of distinct pairs of integers form an array whose sum if a given number in C#

Input: a = [ 2, 4, 3, 5, 6, -2, 4, 7, 8, 9]

Number k = 7

Pair Count = (2, 5), (4, 3), (-2, 9) = 3

Constraints: In a pair numbers should be different and all the pairs should be unique.

Lets say, a = [6, 6, 3, 9, 3, 5, 1]

k = 12

Possible pairs: (6 , 6), (3, 9), (9, 3)

But as per given constraints,  (6, 6) is invalid. And, (3,9) and (9, 3) both are same so we’ll consider only one of them.

Algorithm:

Step1: Prepare a dictionary and add all the items of the array into this dictionary. Array items as KEY and their frequency as VALUE. As we don’t care about the value of this dictionary, we just need a better data structure, to get our item fast, and dictionary is best for such kind of tasks.

Step2: Now as all the unique items have  been inserted in dictionary, so loop over given array and check for (K – array item). If this exists as KEY in dictionary that means there is a pair and it would be (K – array item, array item). But, once we have found a pair we need to check it should not be the same item. If all the constraints are satisfied then increase the count of pairs.

Step3: Now after all these we have number of pairs. But is this our output? Nope.

In our dictionary we have all the unique items of the array, that means for a pair, it contains both the items into this dictionary. For example, items 3,4 both are in dictionary and in our count variable we included pair (3, 4) and (4, 3). But as per our constraints we need to include them only once. So in count of pairs would be our (count variable / 2).

C# Code:

        static void GetNumberOfPairs()
        {
            int[] a = { 2, 4, 3, 5, 6, -2, 4, 7, 8, 9 };
            int k = 7;
            int count = NumberOfPairs(a, k);
            Console.WriteLine(count);
        }
        static int NumberOfPairs(int[] a, long k)
        {
            var count = 0;
            var dict = new Dictionary<int, int>();
            foreach (int item in a)
            {
                if (dict.ContainsKey(item))
                {
                    dict[item]++;
                }
                else
                {
                    dict.Add(item, 1);
                }
            }

            for (int i = 0; i < a.Length; i++)
            {
                if (dict.ContainsKey((int)k - a[i]) && (k - a[i] != a[i]))
                {
                    count++;
                }
            }

            return count / 2;
        }