fork download
  1.  
  2. /*
  3. PROBLEM: Last Task Finish Time
  4.  
  5. Given:
  6. - startTimes: Arrival time of each task.
  7. - executionTime: Time required to execute each task.
  8. - maxCpus: Maximum number of CPUs available.
  9.  
  10. Every task takes the SAME execution time.
  11.  
  12. Rules:
  13. 1. Each CPU executes only one task at a time.
  14. 2. Tasks cannot start before their arrival time.
  15. 3. Tasks are non-preemptive:
  16.   Once started, they run until completion.
  17. 4. CPUs are identical.
  18.  
  19. Return the time when the last task finishes.
  20.  
  21.  
  22. APPROACH: Greedy + CPU Availability Array
  23.  
  24. For each task:
  25. - Choose the CPU that becomes free earliest.
  26. - Start the task as soon as both the task
  27.   and the selected CPU are available.
  28. - Update that CPU's next available time.
  29.  
  30.  
  31. ALGORITHM:
  32.  
  33. 1. Sort all task arrival times.
  34.  
  35. 2. Initialize freeAt[]:
  36.   freeAt[i] = Earliest time CPU i is available.
  37.  
  38. 3. For every task:
  39.   a. Find the CPU with the smallest freeAt value.
  40.   b. Calculate:
  41.   begin = max(task arrival, CPU availability)
  42.   c. Calculate:
  43.   end = begin + executionTime
  44.   d. Update freeAt[cpu] = end.
  45.   e. Update the latest finish time.
  46.  
  47. 4. Return the latest finish time.
  48.  
  49.  
  50. TIME COMPLEXITY: O(N log N + N * K)
  51.  
  52. N = Number of tasks
  53. K = min(maxCpus, N)
  54.  
  55. - Sorting: O(N log N)
  56. - Finding earliest available CPU: O(K) per task
  57. - Processing N tasks: O(N * K)
  58.  
  59. SPACE COMPLEXITY: O(N + K)
  60.  
  61. - Sorted copy of startTimes: O(N)
  62. - CPU availability array: O(K)
  63. */
  64.  
  65.  
  66. // ==================== SOLUTION ====================
  67.  
  68. function lastTaskFinishTime(startTimes, executionTime, maxCpus) {
  69.  
  70. // STEP 1: Sort tasks by arrival time.
  71. //
  72. // Tasks may be given in any order.
  73. //
  74. // Example:
  75. // startTimes = [3, 0, 2, 1]
  76. // starts = [0, 1, 2, 3]
  77. //
  78. // We process earlier-arriving tasks first.
  79. //
  80. // [...startTimes] creates a copy so that
  81. // the original input array is not modified.
  82. const starts = [...startTimes].sort((a, b) => a - b);
  83.  
  84.  
  85. // STEP 2: Determine how many CPUs to track.
  86. //
  87. // Example:
  88. // maxCpus = 10
  89. // number of tasks = 3
  90. //
  91. // We only need to track 3 CPUs because
  92. // at most 3 tasks can execute simultaneously.
  93. //
  94. // If maxCpus = 2 and tasks = 5,
  95. // we track only 2 CPUs.
  96. const cpus = Math.min(maxCpus, starts.length);
  97.  
  98.  
  99. // STEP 3: Initialize CPU availability times.
  100. //
  101. // freeAt[i] represents the earliest time
  102. // CPU i becomes available for another task.
  103. //
  104. // Example:
  105. // freeAt = [0, 0]
  106. //
  107. // Both CPUs are initially available at time 0.
  108. //
  109. // Later:
  110. // freeAt = [8, 5]
  111. //
  112. // CPU 0 becomes free at time 8.
  113. // CPU 1 becomes free at time 5.
  114. const freeAt = new Array(cpus).fill(0);
  115.  
  116.  
  117. // STEP 4: Track the latest task completion time.
  118. //
  119. // We want the time when ALL tasks are finished,
  120. // not the time when the first task finishes.
  121. let finish = 0;
  122.  
  123.  
  124. // STEP 5: Process each task in arrival order.
  125. for (const start of starts) {
  126.  
  127. // Assume CPU 0 is our best choice initially.
  128. //
  129. // We will compare it against other CPUs
  130. // to find the one available earliest.
  131. let cpu = 0;
  132.  
  133.  
  134. // STEP 5A: Find the earliest available CPU.
  135. //
  136. // Example:
  137. // freeAt = [8, 5, 10]
  138. //
  139. // CPU 1 is available earliest at time 5.
  140. //
  141. // So we select cpu = 1.
  142. //
  143. // We use < rather than <=.
  144. // If two CPUs have the same availability,
  145. // we keep the CPU with the smaller index.
  146. for (let i = 1; i < cpus; i++) {
  147.  
  148. if (freeAt[i] < freeAt[cpu]) {
  149. cpu = i;
  150. }
  151. }
  152.  
  153.  
  154. // STEP 5B: Determine when the task can begin.
  155. //
  156. // Two conditions must be satisfied:
  157. //
  158. // 1. The task must have arrived.
  159. // 2. The CPU must be available.
  160. //
  161. // Therefore, choose the LATER time.
  162. //
  163. // Example 1:
  164. // start = 2
  165. // freeAt[cpu] = 4
  166. //
  167. // The task arrived at time 2,
  168. // but the CPU is busy until time 4.
  169. //
  170. // begin = max(2, 4) = 4
  171. //
  172. // Example 2:
  173. // start = 10
  174. // freeAt[cpu] = 4
  175. //
  176. // The CPU is already available,
  177. // but the task arrives only at time 10.
  178. //
  179. // begin = max(10, 4) = 10
  180. const begin = Math.max(start, freeAt[cpu]);
  181.  
  182.  
  183. // STEP 5C: Update when the CPU becomes free.
  184. //
  185. // The task starts at 'begin' and runs
  186. // continuously for 'executionTime'.
  187. //
  188. // Because tasks are NON-PREEMPTIVE,
  189. // the CPU cannot execute another task
  190. // during this interval.
  191. //
  192. // Example:
  193. // begin = 4
  194. // executionTime = 4
  195. //
  196. // CPU becomes available at time 8.
  197. //
  198. // freeAt[cpu] = 8
  199. freeAt[cpu] = begin + executionTime;
  200.  
  201.  
  202. // STEP 5D: Update the overall finish time.
  203. //
  204. // Example:
  205. // finish = 8
  206. // freeAt[cpu] = 9
  207. //
  208. // finish becomes 9.
  209. //
  210. // We take the maximum because the answer
  211. // is the LATEST completion across all CPUs.
  212. finish = Math.max(finish, freeAt[cpu]);
  213. }
  214.  
  215.  
  216. // STEP 6: Return when the last task finishes.
  217. //
  218. // Example:
  219. // freeAt = [8, 9]
  220. //
  221. // All tasks are completed by time 9.
  222. return finish;
  223. }
  224.  
  225.  
  226. // ==================== TEST CASES ====================
  227.  
  228. /*
  229. TEST COVERAGE CHECKLIST:
  230.  
  231. 1. Single task - imp.
  232. 2. Multiple CPUs with overlapping tasks - imp.
  233. 3. More tasks than CPUs - imp.
  234. 4. All tasks arrive simultaneously - imp.
  235. 5. Unsorted arrival times - imp.
  236. 6. Tasks arrive after CPUs become free - imp.
  237. 7. Only one CPU - imp.
  238. 8. More CPUs than tasks
  239. 9. Multiple tasks with identical arrival times - imp.
  240. 10. Empty input
  241. 11. Zero execution time
  242. 12. Large gaps between arrivals
  243. */
  244.  
  245.  
  246. const tests = [
  247.  
  248. {
  249. name: "Single task - imp.",
  250. startTimes: [3],
  251. executionTime: 5,
  252. maxCpus: 2,
  253. expected: 8
  254. },
  255.  
  256. {
  257. name: "Overlapping tasks - imp.",
  258. startTimes: [0, 1, 2, 3],
  259. executionTime: 4,
  260. maxCpus: 2,
  261. expected: 9
  262. },
  263.  
  264. {
  265. name: "More tasks than CPUs - imp.",
  266. startTimes: [0, 0, 0, 0, 0],
  267. executionTime: 3,
  268. maxCpus: 2,
  269. expected: 9
  270. },
  271.  
  272. {
  273. name: "All tasks arrive simultaneously - imp.",
  274. startTimes: [0, 0, 0, 0],
  275. executionTime: 5,
  276. maxCpus: 2,
  277. expected: 10
  278. },
  279.  
  280. {
  281. name: "Unsorted arrival times - imp.",
  282. startTimes: [3, 0, 2, 1],
  283. executionTime: 4,
  284. maxCpus: 2,
  285. expected: 9
  286. },
  287.  
  288. {
  289. name: "CPUs become free before arrivals - imp.",
  290. startTimes: [0, 10, 20],
  291. executionTime: 3,
  292. maxCpus: 2,
  293. expected: 23
  294. },
  295.  
  296. {
  297. name: "Only one CPU - imp.",
  298. startTimes: [0, 1, 2],
  299. executionTime: 4,
  300. maxCpus: 1,
  301. expected: 12
  302. },
  303.  
  304. {
  305. name: "More CPUs than tasks",
  306. startTimes: [0, 1],
  307. executionTime: 5,
  308. maxCpus: 10,
  309. expected: 6
  310. },
  311.  
  312. {
  313. name: "Identical arrival times - imp.",
  314. startTimes: [2, 2, 2],
  315. executionTime: 4,
  316. maxCpus: 2,
  317. expected: 10
  318. },
  319.  
  320. {
  321. name: "Empty input",
  322. startTimes: [],
  323. executionTime: 5,
  324. maxCpus: 2,
  325. expected: 0
  326. },
  327.  
  328. {
  329. name: "Zero execution time",
  330. startTimes: [1, 3, 5],
  331. executionTime: 0,
  332. maxCpus: 2,
  333. expected: 5
  334. },
  335.  
  336. {
  337. name: "Large gaps between arrivals",
  338. startTimes: [0, 100, 200],
  339. executionTime: 5,
  340. maxCpus: 1,
  341. expected: 205
  342. }
  343. ];
  344.  
  345.  
  346. // ==================== TEST RUNNER ====================
  347.  
  348. let passed = 0;
  349.  
  350. tests.forEach((test, index) => {
  351.  
  352. const actual = lastTaskFinishTime(
  353. test.startTimes,
  354. test.executionTime,
  355. test.maxCpus
  356. );
  357.  
  358. const isCorrect = actual === test.expected;
  359.  
  360. if (isCorrect) passed++;
  361.  
  362. console.log(`Test ${index + 1}: ${test.name}`);
  363. console.log("Expected:", test.expected);
  364. console.log("Actual: ", actual);
  365. console.log("Result: ", isCorrect ? "PASS" : "FAIL");
  366. console.log("----------------------------------------");
  367. });
  368.  
  369. console.log(`Total passed: ${passed}/${tests.length}`);
  370.  
Success #stdin #stdout 0.03s 5600KB
stdin
Standard input is empty
stdout
Test 1: Single task - imp.
Expected: 8
Actual:   8
Result:   PASS
----------------------------------------
Test 2: Overlapping tasks - imp.
Expected: 9
Actual:   9
Result:   PASS
----------------------------------------
Test 3: More tasks than CPUs - imp.
Expected: 9
Actual:   9
Result:   PASS
----------------------------------------
Test 4: All tasks arrive simultaneously - imp.
Expected: 10
Actual:   10
Result:   PASS
----------------------------------------
Test 5: Unsorted arrival times - imp.
Expected: 9
Actual:   9
Result:   PASS
----------------------------------------
Test 6: CPUs become free before arrivals - imp.
Expected: 23
Actual:   23
Result:   PASS
----------------------------------------
Test 7: Only one CPU - imp.
Expected: 12
Actual:   12
Result:   PASS
----------------------------------------
Test 8: More CPUs than tasks
Expected: 6
Actual:   6
Result:   PASS
----------------------------------------
Test 9: Identical arrival times - imp.
Expected: 10
Actual:   10
Result:   PASS
----------------------------------------
Test 10: Empty input
Expected: 0
Actual:   0
Result:   PASS
----------------------------------------
Test 11: Zero execution time
Expected: 5
Actual:   5
Result:   PASS
----------------------------------------
Test 12: Large gaps between arrivals
Expected: 205
Actual:   205
Result:   PASS
----------------------------------------
Total passed: 12/12