Qualtrics | Phone Screen | Stock Executor

I was asked this question for my qulatrics phone screen.

Stock executor:

You are givien a list of stock order, where each stock order is a list of string with following information order[i] = [orderType, id, price, ammount] amounti orders have been placed of type orderTypei at the price pricei. The orderTypei is:
“SELL” if it is a SELL order
“Buy” if it is a buy order
Note that order[i] represents a batch of amount_i independent orders with same price and order type. All orders represent by orders[i] will be placed before all orders represented by orders[i+1] for all valid i.

There is a backlog that consists of orders that have not been executed. The backlog is initially empty. When an order is placed, the following happens:

If the order is a buy order, you look at the sell order with the smallest price in the backlog. If that sell order's price is smaller than or equal to the current buy order's price, they will match and be executed, and that sell order will be removed from the backlog. Else, the buy order is added to the backlog.
Vice versa, if the order is a sell order, you look at the buy order with the largest price in the backlog. If that buy order's price is larger than or equal to the current sell order's price, they will match and be executed, and that buy order will be removed from the backlog. Else, the sell order is added to the backlog.
The earlier order should be executed first.

Print out the order being executed with the following information seperate by “,"
Previous order id
Current order id
previous order price
ammount executed.

Example:
[[“BUY”, “0”, “10”, “5”], [“BUY”, “3”, “30”, “4”], [“SELL”, “2”, “25”, “1”], [“SELL”, “1”, “15”, “2”]]
Result:
“2,3,25,1"
“1,3,15,2”

The part where it says "The earlier order should be executed first." is the one tham I am stuck at. The other part of the question can easily be solved by taking 2 PQs.

Comments (4)