Rearrange Songs by Author
Learn this problemProblem statement
You are given a 2D string array songs. Each row is [author, song], and every row identifies one distinct song record.
Rearrange all records so that no two consecutive records have the same author. At each position, choose the eligible author with the largest number of unplaced songs. If eligible authors have equal remaining counts, choose the lexicographically smaller author. Within one author, emit songs in lexicographic order.
Return the complete rearranged 2D array. If no valid complete rearrangement exists, return an empty 2D array.
Function
rearrangeSongs(songs: String[][]) → String[][]Examples
Example 1
songs = [["A","alpha"],["A","amber"],["B","beta"],["C","coda"]]return = [["A","alpha"],["B","beta"],["A","amber"],["C","coda"]]Author A starts with two songs, so it is selected first. Authors B and C then tie with one song; B wins lexicographically. The remaining records alternate without equal adjacent authors.
Example 2
songs = [["A","one"],["A","two"],["A","three"],["B","solo"]]return = []After placing two records from author A around the only B record, two A records would still need to be adjacent. A complete valid arrangement is impossible.
Constraints
1 <= songs.length <= 200000songs[i].length == 21 <= songs[i][0].length, songs[i][1].length <= 100- Every row is a distinct
[author, song]pair.