# Solution of Linked List Sum of Nodes Between 0s

Input  : 1->2->3->0->5->4->0->3->2->0 Output : 6->9->5 Input  : 1->2->3->4 Output : 1->2->3->4
    class LinkedListSumOfNodesBetween0s
{
class Node
{
public Node next;
public object value;

public Node(object value)
{
this.value = value;
}
}

static void Main(string[] args)
{
}

{
while (nodeCount-- > 0)
{
}

}

{
{
}

int sum = 0;
while (tempList != null)
{
if (Convert.ToInt32(tempList.value) == 0)
{
modifiedList.value = sum;
modifiedList.next = tempList.next;
tempList = modifiedList.next;
modifiedList = modifiedList.next;
sum = 0;
}
else
{
sum += Convert.ToInt32(tempList.value);
tempList = tempList.next;
}
}
}

static Node InsertNode(Node head, int value)
{
Node newNode = new Node(value);
{
}
else
{
while (temp.next != null)
{
temp = temp.next;
}
temp.next = newNode;
}

}

{
{
Console.Write("->");
}
Console.Write("null");
}
}

# Solution of round the given number to nearest multiple of TEN

Given a positive integer n, round it to nearest whole number having zero as last digit.

Examples:

Input : 2019 Output : 2020 Input : 14 Output : 10 Input : 10 Output: 10 Input : 6 Output: 10
        public void FindNearestMultiple()
{
var isContinue = true;
while (isContinue)
{
if (userInput.ToLower() == "no")
{
isContinue = false;
continue;
}

int n = Convert.ToInt32(userInput);
int temp = n % 10;
if (temp < 5)
{
Console.WriteLine(n - temp);
}
else
{
Console.WriteLine((n - temp) + 10);
}
}
}

# Find duplicate characters in string

Our task is simple, find all the duplicate characters in a string.

Input: I am test program

Output: a m t r

Algorithm: Logic is quite simple, see below steps:

1. Check for input string validity.
1. If string is not valid prompt user.
2. Create a dictionary that has character as KEY and, their count as VALUE.
3. Loop over the input string,
1. If current character is already exists in dictionary then increment its count by 1.
2. If current character doesn’t exist in dictionary than add it to the dictionary and set 1 as it’s count because we have found it once.
4. Loop over the dictionary and check for value, if you find any item whose value is higher than 1 then print it.
5. If there is no item whose value is not higher than 1 then prompt user.

Code in C#:

void PrintDuplicateCharacters(string strInput)
{
if (string.IsNullOrWhiteSpace(strInput))
{
Console.WriteLine("Input is not valid");
}
else
{
var dict = new Dictionary<char, int>();
foreach (var item in strInput)
{
if (Equals(item, ' '))
{
continue;
}

if (dict.ContainsKey(item))
{
dict[item]++;
}
else
{
}
}

bool isAnyCharacterFound = false;
foreach (var item in dict)
{
if (item.Value > 1)
{
Console.WriteLine(item.Key);
isAnyCharacterFound = true;
}
}

if (!isAnyCharacterFound)
{
Console.WriteLine("No duplicate character found");
}
}
}

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

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

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

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

}