fork download
  1. /**
  2.  * PROBLEM: Price at Query Timestamps
  3.  * FOLLOW-UP 3: Price updates arrive live between queries
  4.  *
  5.  * Design a data structure supporting two operations:
  6.  *
  7.  * setPrice(time, price):
  8.  * Add a new price record at the given timestamp.
  9.  *
  10.  * getPrice(query):
  11.  * Return the price corresponding to the largest
  12.  * timestamp that is less than or equal to query.
  13.  *
  14.  * EXAMPLE:
  15.  *
  16.  * setPrice(0, "A")
  17.  * setPrice(50, "B")
  18.  *
  19.  * getPrice(20) -> "A"
  20.  * getPrice(50) -> "B"
  21.  * getPrice(600) -> "B"
  22.  *
  23.  * setPrice(500, "C")
  24.  *
  25.  * getPrice(600) -> "C"
  26.  * getPrice(499) -> "B"
  27.  * getPrice(-10) -> ""
  28.  *
  29.  * ASSUMPTIONS:
  30.  * - Price updates arrive in strictly increasing
  31.  * timestamp order.
  32.  * - Queries can arrive in any order.
  33.  * - Price updates and queries can be interleaved.
  34.  * - Return "" if no valid price record exists.
  35.  * - Initially, the price history is empty.
  36.  *
  37.  * APPROACH:
  38.  *
  39.  * - Maintain an array of price records.
  40.  * - Each record contains a timestamp and its price.
  41.  *
  42.  * - Since updates arrive in increasing timestamp order,
  43.  * simply append each new record to the array.
  44.  * The array remains sorted automatically.
  45.  *
  46.  * - For every query, perform Last True Binary Search
  47.  * to find the rightmost record satisfying:
  48.  *
  49.  * records[mid].time <= query
  50.  *
  51.  * - Whenever a valid candidate is found, store its
  52.  * index in res and continue searching toward the right
  53.  * for a better candidate.
  54.  *
  55.  * - If res === -1, no valid price record exists.
  56.  * Otherwise, return records[res].price.
  57.  *
  58.  * PATTERN:
  59.  * Dynamic sorted array + Last True Binary Search
  60.  *
  61.  * TIME:
  62.  * - setPrice(): O(1) amortized
  63.  * - getPrice(): O(log n)
  64.  *
  65.  * SPACE:
  66.  * - Total storage: O(n)
  67.  * - Auxiliary space per operation: O(1)
  68.  *
  69.  * n = number of price records stored so far.
  70.  */
  71.  
  72. class PriceHistory {
  73. constructor() {
  74. // Stores price records in increasing timestamp order.
  75. this.records = [];
  76. }
  77.  
  78. setPrice(time, price) {
  79. // Since timestamps arrive in increasing order,
  80. // simply append the new record.
  81. this.records.push({ time, price });
  82. }
  83.  
  84. getPrice(query) {
  85. let lo = 0;
  86. let hi = this.records.length - 1;
  87.  
  88. // Index of the latest valid price record.
  89. let res = -1;
  90.  
  91. while (lo <= hi) {
  92. const mid = lo + Math.floor((hi - lo) / 2);
  93.  
  94. if (this.records[mid].time <= query) {
  95.  
  96. // Current record is a valid candidate.
  97. res = mid;
  98.  
  99. // Look for a more recent valid record.
  100. lo = mid + 1;
  101.  
  102. } else {
  103.  
  104. // Current timestamp is too large.
  105. // Search toward the left.
  106. hi = mid - 1;
  107. }
  108. }
  109.  
  110. // Return "" if no valid record was found.
  111. return res === -1 ? "" : this.records[res].price;
  112. }
  113. }
  114.  
  115.  
  116. // ---------------- TEST HARNESS ----------------
  117.  
  118. const tests = [
  119. // Test 1: Query an empty price history
  120. {
  121. operations: [
  122. ["getPrice", 10],
  123. ["getPrice", -10]
  124. ],
  125. expected: ["", ""]
  126. },
  127.  
  128. // Test 2: Normal case with multiple price records
  129. {
  130. operations: [
  131. ["setPrice", 0, "A"],
  132. ["setPrice", 50, "B"],
  133. ["setPrice", 500, "C"],
  134. ["getPrice", -10],
  135. ["getPrice", 20],
  136. ["getPrice", 50],
  137. ["getPrice", 499],
  138. ["getPrice", 600]
  139. ],
  140. expected: ["", "A", "B", "B", "C"]
  141. },
  142.  
  143. // Test 3: Live price updates between queries
  144. {
  145. operations: [
  146. ["setPrice", 0, "A"],
  147. ["setPrice", 50, "B"],
  148. ["getPrice", 600],
  149. ["setPrice", 500, "C"],
  150. ["getPrice", 600],
  151. ["getPrice", 499]
  152. ],
  153. expected: ["B", "C", "B"]
  154. },
  155.  
  156. // Test 4: Queries arrive in unsorted order
  157. {
  158. operations: [
  159. ["setPrice", 5, "low"],
  160. ["setPrice", 12, "mid"],
  161. ["setPrice", 30, "high"],
  162. ["getPrice", 30],
  163. ["getPrice", 4],
  164. ["getPrice", 12],
  165. ["getPrice", 29]
  166. ],
  167. expected: ["high", "", "mid", "mid"]
  168. },
  169.  
  170. // Test 5: Single price record and boundary queries
  171. {
  172. operations: [
  173. ["setPrice", 100, "only"],
  174. ["getPrice", 99],
  175. ["getPrice", 100],
  176. ["getPrice", 1000000000]
  177. ],
  178. expected: ["", "only", "only"]
  179. },
  180.  
  181. // Test 6: Historical queries after new price updates
  182. {
  183. operations: [
  184. ["setPrice", 10, "A"],
  185. ["getPrice", 15],
  186. ["setPrice", 20, "B"],
  187. ["setPrice", 30, "C"],
  188. ["getPrice", 15],
  189. ["getPrice", 25],
  190. ["getPrice", 35]
  191. ],
  192. expected: ["A", "A", "B", "C"]
  193. }
  194. ];
  195.  
  196. tests.forEach(({ operations, expected }, index) => {
  197. const priceHistory = new PriceHistory();
  198. const actual = [];
  199.  
  200. for (const [operation, ...args] of operations) {
  201. if (operation === "setPrice") {
  202. priceHistory.setPrice(...args);
  203. } else if (operation === "getPrice") {
  204. actual.push(priceHistory.getPrice(...args));
  205. }
  206. }
  207.  
  208. const passed =
  209. JSON.stringify(actual) === JSON.stringify(expected);
  210.  
  211. console.log(
  212. `Test ${index + 1}: ${passed ? "PASS" : "FAIL"}\n` +
  213. `Operations: ${JSON.stringify(operations)}\n` +
  214. `Expected: ${JSON.stringify(expected)}\n` +
  215. `Actual: ${JSON.stringify(actual)}\n`
  216. );
  217. });
Success #stdin #stdout 0.03s 5712KB
stdin
Standard input is empty
stdout
Test 1: PASS
Operations: [["getPrice",10],["getPrice",-10]]
Expected: ["",""]
Actual: ["",""]

Test 2: PASS
Operations: [["setPrice",0,"A"],["setPrice",50,"B"],["setPrice",500,"C"],["getPrice",-10],["getPrice",20],["getPrice",50],["getPrice",499],["getPrice",600]]
Expected: ["","A","B","B","C"]
Actual: ["","A","B","B","C"]

Test 3: PASS
Operations: [["setPrice",0,"A"],["setPrice",50,"B"],["getPrice",600],["setPrice",500,"C"],["getPrice",600],["getPrice",499]]
Expected: ["B","C","B"]
Actual: ["B","C","B"]

Test 4: PASS
Operations: [["setPrice",5,"low"],["setPrice",12,"mid"],["setPrice",30,"high"],["getPrice",30],["getPrice",4],["getPrice",12],["getPrice",29]]
Expected: ["high","","mid","mid"]
Actual: ["high","","mid","mid"]

Test 5: PASS
Operations: [["setPrice",100,"only"],["getPrice",99],["getPrice",100],["getPrice",1000000000]]
Expected: ["","only","only"]
Actual: ["","only","only"]

Test 6: PASS
Operations: [["setPrice",10,"A"],["getPrice",15],["setPrice",20,"B"],["setPrice",30,"C"],["getPrice",15],["getPrice",25],["getPrice",35]]
Expected: ["A","A","B","C"]
Actual: ["A","A","B","C"]