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
 


1 Comment

String replace C# (without using built IN methods)

1. Simple replace:

public static string MyReplaceSimple(this string source, string oldValue, string newValue)
 {
 if (source != null)
 {
 var sourceArr = source.Split(new[] { oldValue }, StringSplitOptions.None);

 var result = new StringBuilder();

 for (int i = 0; i < sourceArr.Length; i++)
 {
 result.Append(sourceArr[i]);

 if (i + 1 != sourceArr.Length)
 {
 result.Append(newValue);
 }
 }

 return result.ToString();
 }
 return null;
 }

2. Replace using LINQ:

public static string MyReplaceLinq(this string source, string oldValue, string newValue)
 {
 if (source != null)
 {
 var sourceArr = source.Split(new[] { oldValue }, StringSplitOptions.None);
 var start = sourceArr.Take(1);
 var end =
 from originalString in sourceArr.Skip(1)
 from newString in new[] { newValue, originalString }
 select newString;
 var result = String.Join("", start.Concat(end));
 return result;
 }

 return null;
 }

Happy coding…

~BS