Problem · Array

Group Shifted Strings

Learn this problem
MediumMathWorks logoMathWorksFULLTIMEONSITE INTERVIEW

Problem statement

You are given an array of non-empty lowercase English strings. Two strings belong to the same shifting group when they have the same length and one can be transformed into the other by shifting every character forward by the same number of alphabet positions, wrapping from z to a.

Return all shifting groups. Scan strings from left to right: groups must appear in the order of their first member, and strings within each group must retain their input order. Preserve every occurrence, including duplicate strings.

Function

groupStrings(strings: String[]) → String[][]

Examples

Example 1

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

The strings abc, bcd, and xyz share the same cyclic differences between consecutive characters. The pair az and ba also matches across the alphabet boundary, while all one-character strings form one group. The group and member order follows the input.

Example 2

strings = ["a","b","a","aa","bb","za"]return = [["a","b","a"],["aa","bb"],["za"]]

Every one-character string belongs to the same group, and the second occurrence of a is preserved. The strings aa and bb share a zero-difference pattern, while za has a different cyclic pattern.

Constraints

  • 1 <= strings.length <= 10^4
  • 1 <= strings[i].length <= 50
  • The total number of characters across strings is at most 10^5.
  • Every string contains only lowercase English letters.

More MathWorks problems

drafts saved locally
public String[][] groupStrings(String[] strings) {
    // Write your code here.
}
strings["abc","bcd","acef","xyz","az","ba","a","z"]
expected[["abc", "bcd", "xyz", "acef", "az", "ba", "a", "z"]]
checking account