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

Manage Hotmail via Microsoft Office Outlook 2010

A good way to manage your Hotmail or Live account via Office Outlook.

Below are the steps to configure Hotmail account to Microsoft Office Outlook

Download Outlook Hotmail Connector available here

Double click the downloaded setup i.e. OutlookConnector.exe

Accept the terms and click on Install

Installer 1

The setup will do the installation.

Click on Finish

Installer 2.PNG

Open Outlook

Click on File -> Info

Under Account Information, click on Add Account button.

Account 5

 

In the Add New Account dialog box, select Manually configure server settings or additional server types and click Next.

Account 1.PNG

Select Other and select Microsoft Outlook Hotmail Connector from the list.

Account 2.PNG

Enter user information in the Windows Live Hotmail Settings dialog box. Click Ok.

Account 3

Click Finish to complete the setup.

Account 4.PNG

 

Hope this helps.

~BJS


1 Comment

Visual Studio : C# Interactive Window

Recently I came across C# (comeback) feature, Interactive Window, which comes with Visual Studio 2015 Update 1. The interactive Window is a REPL which executes the program piecewise.

You will no longer have to create small ConsoleApplication projects just to try out a small piece of code (bye bye ConsoleApplication42…). With Interactive Window, developers can get output for small code snippets without any project creation,  code file or any assembly. Just type in the code and get the result.

C# Interactive Window is part of Visual Studio which makes it easy to learn new language features and experiment with .NET technologies similar to CShell (not completely) but within Visual Studio.

To open Interactive Window, got to View -> Other Windows and select C# Interactive. As shown below.

Navigate.png

Helpful REPL commands to remember before you start:

#help : Display help on specified command, or all available commands and key bindings if none specified.

#clear/#cls : Clears the contents of the editor window, leaving history and execution context intact.

#reset : Reset the execution environment to the initial state, keep history.

As always lets start with Hello World example:

Hello World 1

You can see in the above code, we created 2 strings variables str1 & str2 and wrote the output to the console. Important things to note here, 1. A ‘;’ will make the statement part of the execution context. 2. Pressing ‘Enter’ after the statement without ‘;’ executes the context. Like here it displays the output ‘Hello World’. 3. Even after we got the output the execution context is still intact. So if I execute Console.WriteLine(str1 + str2), the output will be the same. Use #reset command to reset the execution context. 4. No need to specify the namespace.

I can also create a method in the execution context, and use it later. like

Method.PNG

I created a method HelloName(string name) and calling it in the same context gets me the desired output but when I reset the execution context and call the method again, an error is displayed stating “The name ‘HelloName’ does not exist in the current context”.

You can also save your script in a file on the disk and can execute it via VS Command Prompt (extension is not important).

Script 1

Script 2

How to reference a DLL and use it
You use the #r directive to reference a DLL.
I have created a simple class library named SimpleMath.dll for easy learning:

Class Library.PNG

Using the #r directive, I can reference my SimpleMath.dll in the Interactive Window’s execution context.
ClassLibrary Reference.PNG

Documentation : https://github.com/dotnet/roslyn/wiki/interactive-window
Hope this helps.

Let me know you comments below.

~BS