Question 01: Length of Shortest Repeating String


Date: 2021-09-20
Language: Python
Code Link: Github

Background

Had a technical interview for a IT role and they asked the question below to see how a person would work through and solve the problem
Key items they were looking for:
  • Ask questions about the problem and seek help for any clarity required
  • Talk through with them how the problem is being solved while solving it
  • At the end, explain how the problem was solved
  • How efficient the solution code was and the Nth value required
  • Communication skills
  • Coding methodology and process. Whether it follows good practice or just ad-hoc style

Problem

Find the length of the shortest repeating string.

def shortest_repeating(string: str) -> int:
pass #TODO: Implement logic

Test cases:
> shortest_repeating("ababab")
Output: 2
> shortest_repeating("aaaaa")
Output: 1
> shortest_repeating("abc")
Output: 3

Solution

This was the initial solution below which is not good at all and what you should avoid. However, under time pressure it is important to stay cool and take things slowly. In the end if you are qualified you can succeed.
Poor Answer
def shortest_repeating(string: str) -> int:
  final_result = None

  for idx, letter in enumerate(string):
      letter_split = string[:idx+1]
      result = string.split(letter_split)
      result_len = len(result)
      counter = 0
      if idx+1 == len(string):
          final_result = len(string)
          break
      for checker in result:
          if checker == '':
              counter += 1
          else:
              break
      if counter == result_len:
          repeating = letter_split
          final_result = len(repeating)
          break
  print('bye')
  return int(final_result)


if __name__ == '__main__':
  test_str = "abc"
  result = shortest_repeating(test_str)
  print(result)

Better Answer

def shortest_repeating(string: str) -> int:
string_len_half = int(len(string))/2

for idx, letter in enumerate(string):
    if idx == string_len_half:
        return len(string)

    letter_split = string[:idx+1]
    letter_list = string.split(letter_split)
    empty_check = all(v == '' for v in letter_list)

    if empty_check:
        return int(len(letter_split))


if __name__ == '__main__':
test_cases = ['ababab', 'aaaaa', 'abc']
for item in test_cases:
    result = shortest_repeating(item)
    print(f'Output: {result}')