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


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

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

Our task is to find all the possible pairs (no duplication) of integers whose sum is given. See below examples:

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) , (3, 4) , (-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.

        static void Main(string[] args)
{
int[] arr = { 2, 4, 3, 5, 6, -2, 4, 7, 8, 9 };
int n = 7;
PrintPairs(arr, n);
}

private static void PrintPairs(int[] arr, int n)
{
List<int> 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); } } } # Sum of all proper divisors of a natural number in O(n) Suppose you have a natural number say 20, you need to find out sum of its divisors. How will you start? Input: number = 20 Output: 22 As we all know that a proper divisor can’t be greater than number/2. Also a prime divisor can’t be greater than Squar Root of the number. So now we have two approaches to compute above sum: Method1 – Logic is, a proper divisor can’t be greater than number/2. This logic is preety simple but you have to loop till number/2. So suppose number is 100, then we have to iterate 50 times. Time complexity is O(n). Step1: Loop till condition i <= number/2 is true. Step2: Check foe proper divisors Step3: Sum all the proper divisor. Input: 20 Output: 1 + 2 + 4 + 5 + 10 = 22 class SumOfAllProperDivisors { static void Main(string[] args) { Console.Write("Please enter a number: "); int num = Convert.ToInt32(Console.ReadLine()); int sum = 0; for (int i = 1; i <= num/2; ++i) { if (num % i == 0) { sum += i; } } Console.WriteLine($"Divisor sum: {sum}");
}
}

Method2 – Logic is, a prime divisor can’t be greater than Squar Root of the number. In this case our loop iteration will be considerabily less in compare to Method1. Time complexity is O(n).

Step1: Loop till condition i <= Squar root of number is true.
Step2: Check for proper divisor.
Step3: if it is proper divisor then add this number to our result.
Step3.1: Check for the Quotient, if it is not same as divisor and divisor is not equal to 1 then add quotient to our result.

Input: 20
Output: 1 + (2 + 10) + (4 + 5) = 22

class SumOfAllProperDivisors
{
static void Main(string[] args)
{
Console.Write("Please enter a number : ");
int sum = 0;
for (int i = 1; i <= Math.Sqrt(num); ++i)
{
if (num % i == 0)
{
sum += i;
if ((num / i != i) && i != 1)
{
sum += (num / i);
}
}
}
Console.WriteLine(\$"Divisor sum: {sum}");
}