JavaScript Coding Practice Challenges — Strings

Problems and Solutions in JavaScript

Photo by Daniel McCullough on UnsplashPhoto by Daniel McCullough on Unsplash

Challenge # 1 — Counting duplicate characters

A very common programming interview question is that given a string you need to find out the duplicate characters in the string.

Input: “adsjfdsfsfjsdjfhacabcsbajda”

Output: { a: 5, b: 2, c: 2, d: 4, f: 4, j: 4, s: 5 }

There are two solutions to this problem.

Solution # 1

The first solution iterates the string characters and use a dictionary <key, value> to store the characters as keys and the number of occurences as values.

  • If the current character was never added to the dictionary then add it as <character, 1>.

  • If the current character exists in the dictionary then simply increase its occurrences by 1.

Solution # 2

We turn the string into a character array and then sort the array and put them together to form a new string. As this string is sorted, we can use a regular expression (here is /(.)\1+/g) to match the repeated characters.

This is the output in both two cases:

const str = “adsjfdsfsfjsdjfhacabcsbajda”

count_duplicate_characters(str)

{ a: 5, b: 2, c: 2, d: 4, f: 4, j: 4, s: 5 }

Can you solve this problem with Unicode characters? Share your solution here with your comments.

Challenge # 2— Finding the first non-repeated character

Write a JavaScript program to find the first non-repeated character in a String is a common question on coding challenges. We can solve the problem in a single traversal of the string or in more complete/partial traversals.

Input: "cbcbdde"

Output: e

Solutions

We will re-solve the problem in the single traversal approach. Here, we use a flag array with 256 items to store non-repeated characters and then we find smallest index containing a non-repeated character.

Try to test this approach.

console.log(first_non_repeated_character("cbcbdde"))
<< e

Challenge # 3 — Reversing letters and words

Reversing letters means you write certain letters (or numbers) backward or upside down. This is sometimes referred to as mirror writing.

Input: "I evol uoy os !hcum"

Output: I love you so much!

Solutions

It is easy to reverse letters and words using buil-in functions.

Here is the output.

var test_string = "emocleW ot SJ ni nialP hsilgnE"
reverse(test_string)

<< Welcome to JS in Plain English

Challenge # 4 — Generating all permutations

Problems that involve permutations commonly involve recursivity as well. Basically, recursivity is defined as a process where some initial state is given and each successive state is defined in terms of the preceding state.

Input: ABC

Output: ABC, ACB, BCA, BAC, CAB, CBA

Solutions

You can call it like so

permute_and_print(“ABC”)

This will produce the following output:

ABC ACB BCA BAC CAB CBA

Challenge # 5— Checking whether a string is a palindrome

Just as a quick reminder, a palindrome looks unchanged when it's reversed. This means that processing a palindrome can be done from both directions and the same result will be obtained

For example, the word madam is a palindrome, while the word madame is not.

Solutions

The implementation relies on the while statement.

We can rewrite the preceding solution in a more concise approach will consist of relying on a for statement instead of a while statement, as follows.

Can we reduce to a single line of code?

Challenge # 6— Sorting an array of strings by length

We are given an array of strings, we need to sort the array in increasing order of string lengths

Input: ["You", "are", "beautiful", "looking"]

Output: [“You", "are", "looking", "beautiful"]

Solutions

The first thing that comes to mind when sorting is the use of a comparator. In this case, the solution should compare lengths of strings, and so the integers are returned by calling .length for each string in the given array.

Challenge # 7— Checking that a string contains a substring

Solutions

A very simple, one line of code solution relies on the .includes() function.

const string = “foo”
const substring = “oo”

string.includes(substring)
<< true

Alternatively, a solution can be implemented by relying on String.prototype.indexOf() as follows:

string.indexOf(substring) !== -1
<< true

Challenge # 8 — Checking whether two strings are anagrams

An anagram of a string is another string that contains same characters, only the order of characters can be different. For example, “abcd” and “dabc” are anagram of each other.

Solutions

We create a count array and initialize all values as 0. For each character in input strings, increment count in the corresponding count array.

for (i = 0; str1[i] && str2[i]; i++) {
    count[str1[i]]++
    count[str2[I]]-—
}

If both strings are of different length. Removing this condition will make the program fail for strings like "aaca" and "aca"

if (str1[i] || str2[i])
    return false

See if there is any non-zero value in count array.

for (i = 0; i < NO_OF_CHARS; i++)
    if (count[i])
        return false

If all doesn't match, return a true value. And here is my full solution. In this case, the time complexity is O(n).

Easy right?

Thanks for reading! 😘

Enjoyed this article?

Share it with your network to help others discover it

Continue Learning

Discover more articles on similar topics