Блог пользователя Vik

Автор Vik, история, 4 года назад, По-английски

Problem

Constraints:

Size of the array: [1 10^5]

Element: 1 <= a[i] <= 10^6

Brute force won't work because of the constraints. I tried thinking of various ways but all were convoluted. I feel there is an easier way to think about it but I am missing some observation.

Any help would be highly appreciated.

Thanks!

  • Проголосовать: нравится
  • -25
  • Проголосовать: не нравится

»
4 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

You can use graph to solve this problem, put an edge between each element of each pair .

  • »
    »
    4 года назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится

    How will you do it in O(n)?

    • »
      »
      »
      4 года назад, # ^ |
        Проголосовать: нравится 0 Проголосовать: не нравится

      Draw an undirected edge between every element in the pair. You know that the ends of the array must have degree 1, as they are only adjacent to 1 element. Just find any node with degree 1, run a dfs from there, and return the order in which you visited the elements in the dfs. One other thing to note is that you can "coordinate-compress" the values in the array, so your runtime is $$$O(N)$$$, not $$$O(N+A)$$$, where $$$A$$$ is the maximum value of an array element.

»
4 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Since all the values are different we can construct a graph from the pairs. Suppose we have pair [a, b] , lets make an edge a — b. After we built the graph we can find the vertex with degree of 1 and make a simple dfs to print the array.