Bhavya

Code -> Break -> Fix -> Blog


Leave a comment

HackerRank: Longest even length word

Problem: Consider a sentence, we want to find the first word in sentence having a length which is both an even number and greater than or equal to the length of any other word of even length in the sentence. If there are no even length words return “00”.

Example 1: GetLongestEvenLengthWord(“Time to write great code”);

Output: Time

Example 2: GetLongestEvenLengthWord(“Write code for a great time”);

Output: code

Example 3: GetLongestEvenLengthWord(“It is a pleasant day today”);

Output: pleasant

Example 4: GetLongestEvenLengthWord(“The one”);

Output: 00

Solution:

public static string LongestEvenLengthWord(string input)
{
string noSuccess = “00”;
if (string.IsNullOrEmpty(input) || input.Length == 1)
{
return noSuccess;
}

int count = 0, max = 0, lastIndex = 0;
for (int i = 0; i < input.Length; i++)
{
if (input[i] == ‘ ‘)
{
if (count % 2 == 0)
{
if (count > max)
{
max = count;
lastIndex = i;
}

count = 0;
}
else
{
count = 0;
}
}
else
{
count++;
}
}

if (max == 0)
{
return count % 2 == 0 ? input.Substring(input.Length – count, count) : noSuccess;
}

return input.Substring(lastIndex – max, max);
}

Advertisements


Leave a comment

HackerRank: Braces

Problem: You are designing a compiler for a C++ program and need to check that braces in any given file are balanced.

Braces in a string are considered to be balanced if the following criteria are met:

  1. All braces must be closed. Braces come in pairs of the form (), {} and []. The left brace opens the pair, and the right one closes it.
  2. In any set of nested braces, the braces between any pair must be closed.

Example 1: AreBalancedBraces(“[{()}]”)

Output: True

Example 2: AreBalancedBraces(“[()]}”)

Output: False

 

Solution:

public static string IsBalanced(string input)
{
var stack = new Stack<char>();
var validChar = new Dictionary<char, char>() { { ‘(‘, ‘)’ }, { ‘[‘, ‘]’ }, { ‘{‘, ‘}’ } };

bool correctFormat = true;
foreach (var ch in input)
{
if (validChar.ContainsKey(ch))
{
stack.Push(ch);
}
else if (validChar.ContainsValue(ch))
{
correctFormat = stack.Any();
if (correctFormat)
{
correctFormat = validChar.Contains(new KeyValuePair<char, char>(stack.Pop(), ch));
}
else
{
break;
}
}
}

return correctFormat ? “YES” : “NO”;
}


Leave a comment

HackerRank: Anagram

Problem: Given two strings, find the number of characters to replace to replace in the second input string to make it an anagram of the first input string.

Example 1: GetMinimumDifferenceForAnagram(“abb”,”bbc”);

Output: 1

Example 2: GetMinimumDifferenceForAnagram(“abb”,”bba”);

Output: 0

Example 3: GetMinimumDifferenceForAnagram(“abb”,”bbad”);

Output: -1

Example 4: GetMinimumDifferenceForAnagram(“Abb”,”bba”);

Output: 1

 

Solution:

public static int GetMinimumDifferenceForAnagram(string a, string b)
{
// Valid input
if (string.IsNullOrEmpty(a) || string.IsNullOrEmpty(b))
{
return -1;
}

// Check length
if (a.Length != b.Length)
{
return -1;
}

a = string.Concat(a.OrderBy(c => c));
b = string.Concat(b.OrderBy(c => c));

// Compare the two sorted string.
if (string.Compare(a, b) == 0)
{
return 0;
}

// Store the char occurance count in a dictionary.
var dictionaryA = a.GroupBy(c => c).OrderBy(c => c.Key).ToDictionary(g => g.Key, g => g.Count());
var dictionaryB = b.GroupBy(c => c).OrderBy(c => c.Key).ToDictionary(g => g.Key, g => g.Count());

// Get the difference.
int finalCount = 0;
foreach(var key in dictionaryA.Keys)
{
finalCount += dictionaryA[key] – (dictionaryB.ContainsKey(key) ? dictionaryB[key] : 0);
}

return finalCount;
}


Leave a comment

Mettl Coding Test : Find the max. distance between two occurrences of a char in a string

Problem Statement:

  1. Write a method to find the max. distance between two occurrences of a char in a string.
  2. Distance is the no. of unique characters (excluding whitespaces and searched character) between two occurrences of the searched character.

Example 1:

SearchLetter(“my name is granar”, “a”);

Output : 7 (i.e. m,e,i,s,g,r,n)

Example 2:

SearchLetter(“the capital of minnesota is saint paul”, “y”);

Output : -1 (no. occurrence of “y”)

Example 3:

SearchLetter(“quick brown fox jumps over the lazy dog”, “a”);

Output : -1 (only 1 occurrence of “a”)

Solution

public static int output1;

public static void SearchLetter(string input1, string input2)
{
if (string.IsNullOrEmpty(input1)
|| string.IsNullOrEmpty(input2)
|| input1.Count() < 2
|| input2.Count() != 1)
{
output1 = -1;
return;
}

var firstIndex = input1.IndexOf(input2);
var lastIndex = input1.LastIndexOf(input2);

if (firstIndex == lastIndex)
{
output1 = -1;
return;
}

var distance = lastIndex - firstIndex;
var finalSearchString = input1.Substring(firstIndex + 1, distance - 1);

finalSearchString = finalSearchString.Replace(" ", string.Empty)
.Replace(input2, string.Empty);

string tempString = string.Empty;
string finalString = string.Empty;

foreach (var value in finalSearchString)
{
if (tempString.IndexOf(value) == -1)
{
tempString += value;
finalString += value;
}
}

output1 = finalString.Count();
}

~BJS
 


Leave a comment

Mettl Coding Test : List the duplicate integers in the array

Problem Statement

  1. Create a method which will list out the duplicate entries in a given integer array.
  2. The input array should have only positive integers.
  3. The method should take 2 parameters, 1st is the count of the array and 2nd the actual array
  4. If no duplicate entries are found then return {-1}.

Example 1 :

DuplicateArray(6, new int[] { 4, 4, 7, 8, 8, 9 });

Output={4,8}

Example 2:

DuplicateArray(6, new int[] { 4, 4, -7, 8, 8, 9 });

Output={-1}

Example 3:

DuplicateArray(7, new int[] { 3, 6, 5, 7, 8, 19, 32 });

Output={-1}

 

Soultion

public static int[] output1;

public static void DuplicateArray(int input1, int[] input2)
{
// Validate input1 as it should match with input2.count
// Validate : more than 1 integer present in the array.
// Validate : Positive integers
if (input1 != input2.Count() || input1 &lt; 1
|| input2.FirstOrDefault(x =&gt; x &lt; 0) &lt; 0)
{
output1 = new int[] { -1 };
return;
}

List&lt;int&gt; listDuplicateValues = new List&lt;int&gt;();

// Group by numbers and check the count for duplicate entries.
var groups = input2.GroupBy(x =&gt; x);
foreach (var group in groups)
{
if (group.Count() &gt; 1)
{
listDuplicateValues.Add(group.Key);
}
}

// Validate : if list is empty then set output1 to -1
output1 = listDuplicateValues.Count == 0 ?
new int[] { -1 } : output1 = listDuplicateValues.ToArray();
}

~BJS


Leave a comment

Print the alphabets which are not part of a given string (C#)

Problem Statement: Print the alphabets which are not part of a given string.

Solution


var alpha = new Dictionary&lt;char, bool&gt;();
alpha.Add('a', false);
alpha.Add('b', false);
alpha.Add('c', false);
alpha.Add('d', false);
alpha.Add('e', false);
alpha.Add('f', false);
alpha.Add('g', false);
alpha.Add('h', false);
alpha.Add('i', false);
alpha.Add('j', false);
alpha.Add('k', false);
alpha.Add('l', false);
alpha.Add('m', false);
alpha.Add('n', false);
alpha.Add('o', false);
alpha.Add('p', false);
alpha.Add('q', false);
alpha.Add('r', false);
alpha.Add('s', false);
alpha.Add('t', false);
alpha.Add('u', false);
alpha.Add('v', false);
alpha.Add('w', false);
alpha.Add('x', false);
alpha.Add('y', false);
alpha.Add('z', false);

var inputString = &quot;bhavyajshah&quot;;

foreach(char ch in inputString.ToLower())
alpha[ch] = true;

foreach (var item in alpha)
{
if (item.Value != true)
Console.WriteLine(item.Key);
}


Leave a comment

List duplicates in a given Binary Search Tree

Problem : List all duplicates in a given Binary Search Tree

Assumptions :

1. All “less than” values goes to the LEFT.

2. All “greater than or equal to” values goes to the RIGHT.

List : 5, 3, 10, 5, 4, 3, 7, 5, 5, 5, 2, 4, 10, 8, 10, 5

Output : 3, 4, 5, 5, 5, 5, 5, 10, 10


internal class BST
{
public int Data;
public BST Left;
public BST Right;
}

internal class Program
{
static int lastData;

public static void Main()
{
var root = BuildTree(5, 3, 10, 5, 4, 3, 7, 5, 5, 5, 2, 4, 10, 8, 10, 5);

Console.WriteLine("Duplicate List");
ListDuplicate(root);

Console.ReadLine();
}

private static BST BuildTree(params int[] list)
{
BST temp = null;
BST root = null;

foreach (var l in list)
{
temp = root;
BST node = new BST();
node.Data = l;
node.Left = null;
node.Right = null;

if (temp == null)
{
temp = node;
root = node;
}
else
{
while (temp != null)
{
if (l < temp.Data)
{
if (temp.Left == null)
{
temp.Left = node;
break;
}

temp = temp.Left;
}
else
{
if (temp.Right == null)
{
temp.Right = node;
break;
}

temp = temp.Right;
}
}
}
}

return root;
}

private static void ListDuplicate(BST root)
{
if (root == null)
{
return;
}

ListDuplicate(root.Left);

if (lastData == root.Data)
{
Console.WriteLine(root.Data);
}

lastData = root.Data;

ListDuplicate(root.Right);

}
}

~BS