# 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:

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).

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 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];

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);
}

# 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()
{
for (int i = 0; i < n; i++)
{
Stack<char> balancedBracket = new Stack<char>();
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");
}
}
}

# 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 { get; set; }
public long MaxValue { get; set; }
}
static void Main(string[] args)
{
Stack<CustomStack> st = new Stack<CustomStack>();
long maxInStack = 0;
for (int i = 0; i < N; i++)
{
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);
}
}

}
}

# 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 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));
}


# 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)
{
for (int i = 0; i < T; i++)
{
if (number == 1)
{
Console.WriteLine("Not prime");
continue;
}
else
{
Console.WriteLine(IsPrime(number) ? "Prime" : "Not prime");
}
}
}

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;
}
}

# Remove duplicates from a linked List in C#

Problem source: HackerRank -More Linked Lists

You have a linked list that has n Nodes and their data is in ascending order. A Node object has an integer data field, data, and a Node instance pointer, , pointing to another node (i.e.: the next node in a list). our task is to write a method to remove duplicates from this list and print remaining nodes.

Sample Input

6
1
2
2
3
3
4


Sample Output

1 2 3 4


Explanation

N is total number of Nodes in linked list. The data, 2 and 3 occurs more than one so we need to delete duplicate nodes from the linked list. Once all the duplicate nodes are deleted then print this linked list , which is 1, 2, 3, 4.

class MoreLinkedLists
{
public class Node
{
public int data;
public Node next;
public Node(int d)
{
data = d;
next = null;
}
}
static void Main(string[] args)
{
while (T-- > 0)
{
}

}

{
{
while (start != null)
{
if (start.next != null && start.data == start.next.data)
{
start.next = start.next.next;
}
else
{
start = start.next;
}
}
}
}

public static Node Insert(Node head, int data)
{
Node p = new Node(data);
{
}
{
}
else
{
while (start.next != null)
{
start = start.next;
}
start.next = p;
}
}

{
while (start != null)
{
Console.Write(start.data + " ");
start = start.next;
}
}
}

# 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
{
}