Bhavya

Code -> Break -> Fix -> Blog

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

Leave a comment

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
 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s