Group Shifted String

Balaji MJ
1 min readNov 4, 2021

--

When I interviewed for Facebook, I got this problem in my Phone Interview, I faced this problem.

The string is given and we can “shift” it each of its letter to its successive letter, for example: "abc" -> "bcd". We have to be keep "shifting" which forms the sequence:

"abc" -> "bcd" -> ... -> "xyz"

Given the list of strings which contains only lowercase alphabets, group all strings that belong to the same shifting sequence.

For example, given: ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"],

Example solution is given below:

[
["abc","bcd","xyz"],
["az","ba"],
["acef"],
["a","z"]
]

As soon the problem given, first thing comes is the “Hashtable” Apporach.

As my language of choice is Python, I went with “defaultdict” Python and grouping them.

Why defaultdict?

Genrally the standard dictionary includes the method setdefault() for retrieving a value and establishing a default if the value does not exist.

By contrast, defaultdict lets the caller specify the default(value to be returned) up front when the container is initialized."

This code explains in detail about the implementation part of the problem.

--

--

Balaji MJ

I write about Software Engineering, Backend Development, Algorithmic Trading, Quantitative Finance, and our Mind and Universe.