vishal jat
vishal jat

Reputation: 141

Sort a particular sequence in linear time

I am looking at this challenge:

Given a sequence of integers, sorted by their absolute values, return the sequence sorted by their signed value. The following rules apply:

  1. You can traverse the sequence in only one direction
  2. You cannot randomly access the elements at any position: you have to start from the first element and traverse.
  3. you can choose any data structure to take the input of the sequence, on the condition that the data structure does not sort the sequence for you

How can I solve this with a O(n) time complexity?

Upvotes: 0

Views: 59

Answers (1)

trincot
trincot

Reputation: 350310

Here is a possible algorithm using a stack:

  • In a first iteration push the negative values on the stack.
  • Pop values from the stack one by one and output them in that order
  • In a second iteration select and output the non-negative values.

Or with a deque:

  • Iterate the sequence only once, and:
  • When the value is negative push the value in front of the deque
  • When the value is non-negative push the value at the back of the deque
  • Output the deque by pulling values from the front.

Upvotes: 4

Related Questions