Google questions

Necklace Split

GoogleOnsiteMedium

A necklace is a circular string s made of the letters D and R. A cut c lies between s[c - 1] and s[c], and cut 0 lies between the last letter and the first. For cuts i < j, the two arcs are s[i:j] and s[j:] + s[:i].

Part 1: Split the necklace

Given a necklace string s, return two cuts [i, j] with 0 <= i < j < len(s) so that the two arcs contain the same number of D letters and the same number of R letters. Each arc must get exactly half of all D letters and half of all R letters; an arc does not need to have equal numbers of D and R.

If several pairs of cuts work, return the pair with the smallest i, then the smallest j. If no pair works, return [-1, -1].

  1. Example 1
    s
    "DRDR"
    Output
    [0,2]

    Why: Cuts 0 and 2 give arcs DR and DR; each has one D and one R. No smaller i than 0 exists.

  2. Example 2
    s
    "DDDRRR"
    Output
    [-1,-1]

    Why: The necklace has three D letters, so no arc can receive exactly half of them. No pair of cuts works.

Constraints

  • 2 <= len(s) <= 10^5
  • len(s) is even
  • Each character of s is 'D' or 'R'
  • s contains the same number of 'D' and 'R'
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question
Necklace Split: Google interview question | LoopCoach