Advertisement
amt

DSs

amt
Aug 16th, 2024 (edited)
879
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* 1143. Longest Common Subsequence. Medium
  2.  
  3. console.log(longestCommonSubsequence("abcde", "ace")); // Output: 3
  4. dp
  5. [0, 0, 0, 0]
  6. [0, 1, 1, 1]
  7. [0, 1, 1, 1]
  8. [0, 1, 2, 2]
  9. [0, 1, 2, 2]
  10. [0, 1, 2, 3]
  11. */
  12. console.log(longestCommonSubsequence("abc", "abc")); // Output: 3
  13. console.log(longestCommonSubsequence("abc", "def")); // Output: 0
  14.  
  15. Time Complexity:
  16. O(m * n): We need to fill in a table of size m * n where m is the length of text1 and n is the length of text2.
  17. Space Complexity:
  18. O(m * n): We need to store the DP table of size (m+1) x (n+1).
  19. This approach efficiently computes the length of the longest common subsequence using dynamic programming.
  20. */
  21. function longestCommonSubsequence(text1, text2) {
  22.     const m = text1.length;
  23.     const n = text2.length;
  24.    
  25.     // Create a 2D dp array with (m+1) x (n+1) dimensions and fill it with 0
  26.     const dp = Array(m + 1).fill(null).map(() => Array(n + 1).fill(0));
  27.  
  28.     // Fill the dp array, skip first row and column initialized with 0
  29.     for (let i = 1; i <= m; i++) {
  30.         for (let j = 1; j <= n; j++) {
  31.             // check char at index - 1 as we loop from 1, not zero
  32.             if (text1[i - 1] === text2[j - 1]) {
  33.                 // If characters match dp value is 1 more than diagonally previous element
  34.                 dp[i][j] = dp[i - 1][j - 1] + 1;
  35.             } else {
  36.                 // If characters not match dp value is max of top and left element
  37.                 dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
  38.             }
  39.         }
  40.     }
  41.  
  42.     // The answer is the bottom-right cell of the dp array
  43.     return dp[m][n];
  44. }
  45.  
  46.  
  47. /* 1151. Minimum Swaps to Group All 1's Together. Medium.
  48. minSwaps([1,0,1,0,1]) = 1
  49. minSwaps([0,0,0,1,0]) = 0
  50. minSwaps([1,0,1,0,1,0,0,1,1,0,1]) = 3
  51.  
  52. Time Complexity:
  53. O(n): We traverse the array once with a sliding window, where n is the length of the array.
  54. Space Complexity:
  55. O(1): Only a few variables are used, and no extra space is required relative to the input size.
  56. */
  57. function minSwaps(data) {
  58.     const totalOnes = data.reduce((sum, val) => sum + val, 0);
  59.  
  60.     if (totalOnes === 0) return 0; // No 1's in the array, no swaps needed
  61.  
  62.     let maxOnesInWindow = 0;
  63.     let currentOnes = 0;
  64.     let left = 0;
  65.  
  66.     // Sliding window to find the max number of 1's in a window of size `totalOnes`
  67.     for (let right = 0; right < data.length; right++) {
  68.         currentOnes += data[right];
  69.  
  70.         // Once the window reaches the size of totalOnes
  71.         if (right - left + 1 > totalOnes) {
  72.             currentOnes -= data[left];
  73.             left++;
  74.         }
  75.  
  76.         maxOnesInWindow = Math.max(maxOnesInWindow, currentOnes);
  77.     }
  78.  
  79.     // The minimum number of swaps required is the difference between totalOnes and maxOnesInWindow
  80.     return totalOnes - maxOnesInWindow;
  81. }
  82.  
  83. /* 1492. The kth Factor of n. Medium
  84. kthFactor(12, 3) = 3
  85. kthFactor(7, 2) = 7
  86. kthFactor(4, 4) = -1
  87.  
  88. Time Complexity:
  89. The loop runs from 1 to n, hence the time complexity is O(n).
  90. Space Complexity:
  91. The space complexity is O(n) in the worst case because we store all factors of n in an array.
  92. This approach ensures that we efficiently find and return the k-th factor, or -1 if there are fewer than k factors.
  93. */
  94. function kthFactor(n, k) {
  95.     let factors = [];
  96.     for (let i = 1; i <= n; i++) {
  97.         if (n % i === 0) {
  98.             factors.push(i);
  99.         }
  100.     }
  101.     return factors.length >= k ? factors[k - 1] : -1;
  102. }
  103.  
  104.  
  105.  
  106. /* 1676. Lowest Common Ancestor of a Binary Tree IV. Medium.
  107. lowestCommonAncestor([3,5,1,6,2,0,8,null,null,7,4],[4,7]) = 2
  108. lowestCommonAncestor([3,5,1,6,2,0,8,null,null,7,4],[1]) = 1
  109. lowestCommonAncestor([3,5,1,6,2,0,8,null,null,7,4],[7,6,2,4]) = 5
  110.  
  111. Time Complexity:
  112. The time complexity is O(n), where n is the number of nodes in the tree. This is because we potentially visit every node in the tree once during the DFS traversal.
  113. Space Complexity:
  114. The space complexity is O(h), where h is the height of the tree. This is the maximum depth of the recursion stack. In the worst case, the height of the tree can be n (in the case of a skewed tree), making the space complexity O(n). In a balanced tree, the height would be O(log n).
  115. */
  116. class TreeNode {
  117.     constructor(val) {
  118.         this.val = val;
  119.         this.left = this.right = null;
  120.     }
  121. }
  122. function lowestCommonAncestor(root, nodes) {
  123.     const nodeSet = new Set(nodes);
  124.  
  125.     function dfs(node) {
  126.         if (!node) return null;
  127.         if (nodeSet.has(node)) return node;
  128.  
  129.         const left = dfs(node.left);
  130.         const right = dfs(node.right);
  131.  
  132.         if (left && right) return node;
  133.         return left ? left : right;
  134.     }
  135.  
  136.     return dfs(root);
  137. }
  138.  
  139. /* 2268. Minimum Number of Keypresses. Medium
  140. Time Complexity:
  141. Counting frequencies: O(n), where n is the length of the string.
  142. Sorting frequencies: O(26 * log(26)) = O(1), since the alphabet size is fixed at 26 (i.e., there are at most 26 unique characters).
  143. Computing keypresses: O(26) = O(1) due to the fixed size of the alphabet.
  144. Thus, the overall time complexity is O(n), where n is the length of the string.
  145.  
  146. Space Complexity:
  147. The space complexity is O(1) since we only store a fixed number of character frequencies (26 at most for lowercase English letters).
  148. console.log(minimumKeypresses("abcdefghijkl"));  // Output: 15
  149. console.log(minimumKeypresses("apple"));         // Output: 5
  150. */
  151. function minimumKeypresses(s) {
  152.  
  153.     // Create an array to count the occurrences of each character.
  154.     const frequencyCounter = new Array(26).fill(0);
  155.  
  156.     // Increment the frequency count for each character in the string.
  157.     for (const character of s) {
  158.         frequencyCounter[character.charCodeAt(0) - 'a'.charCodeAt(0)]++;
  159.     }
  160.  
  161.     // Sort the frequency array in non-increasing order.
  162.     frequencyCounter.sort((a, b) => b - a);
  163.  
  164.     // Initialize the answer to 0, which will hold the minimum keypresses required.
  165.     let minimumKeyPresses = 0;
  166.  
  167.     /* The number of keystrokes needed to type a character is determined by its  position in the sorted frequency array. The most frequent characters take 1 keystroke, the next 9 take 2 keystrokes, and so on */
  168.     let keystrokes = 1; // Start with 1 keystroke for the most frequent characters.
  169.  
  170.  
  171.     // Loop through the frequency array to calculate the total number of keypresses.
  172.     for (let i = 0; i < 26; ++i) {
  173.         // Calculate the keypresses required for the current character frequency and add it to the minimumKeyPresses total.
  174.         minimumKeyPresses += keystrokes * frequencyCounter[i];
  175.         // Every 9 characters, the number of keypresses increases by 1, since we are basing our calculation on a 9-key keyboard layout
  176.         if ((i + 1) % 9 === 0) {
  177.             keystrokes++;
  178.         }
  179.     }
  180.  
  181.     return minimumKeyPresses;
  182. }
  183.  
  184. /* 2297. Jump Game VIII. Medium
  185. Time Complexity:
  186. O(n): Each index is processed once. The deque operations (insertions and deletions) are amortized O(1), so overall complexity is linear.
  187. Space Complexity:
  188. O(n): The space complexity is primarily due to the DP array and the deque, both of which can store up to n elements. Therefore, the overall space complexity is O(n).
  189.  
  190. console.log(minCost([3,2,4,4,1], [3,7,6,4,2])); // Output: 8
  191. console.log(minCost([0,1,2], [1,1,1])); // Output: 2
  192. */
  193. function minCost(nums, costs) {
  194.     const n = nums.length;
  195.     const dp = Array(n).fill(Infinity);
  196.     dp[0] = 0; // Starting at index 0 costs nothing
  197.    
  198.     let deque = []; // This will store the indices for potential jumps
  199.  
  200.     for (let i = 0; i < n; i++) {
  201.         // Remove elements from the deque that can't be a valid jump for current index i
  202.         while (deque.length > 0 && (
  203.             (nums[i] >= nums[deque[deque.length - 1]] && nums[i] < nums[deque[0]]) ||
  204.             (nums[i] < nums[deque[deque.length - 1]] && nums[i] >= nums[deque[0]])
  205.         )) {
  206.             deque.pop();
  207.         }
  208.  
  209.         // Calculate the minimum cost to reach index i
  210.         if (deque.length > 0) {
  211.             dp[i] = Math.min(dp[i], dp[deque[0]] + costs[i]);
  212.         }
  213.  
  214.         // Add current index to the deque
  215.         deque.push(i);
  216.     }
  217.  
  218.     return dp[n - 1];
  219. }
  220.  
  221.  
  222. /* 2323. Find Minimum Time to Finish All Jobs II. Medium
  223. Time Complexity:
  224. O(n log n): Sorting the jobs and workers arrays takes O(n log n), where n is the length of the array.
  225. O(n): The loop to calculate the required days for each worker is O(n).
  226. Overall, the time complexity is dominated by the sorting step, so it is O(n log n).
  227.  
  228. Space Complexity:
  229. O(1): The space complexity is constant as we only use a few extra variables, regardless of the input size.
  230.  
  231. console.log(minDays([5,2,4], [1,7,5])); // Output: 2
  232. console.log(minDays([3,18,15,9], [6,5,1,3])); // Output: 3
  233. */
  234. function minDays(jobs, workers) {
  235.     // Sort jobs and workers in ascending order
  236.     jobs.sort((a, b) => a - b);
  237.     workers.sort((a, b) => a - b);
  238.    
  239.     let maxDays = 0;
  240.    
  241.     // Pair each job with a worker and calculate the required days
  242.     for (let i = 0; i < jobs.length; i++) {
  243.         const days = Math.ceil(jobs[i] / workers[i]);
  244.         maxDays = Math.max(maxDays, days);
  245.     }
  246.    
  247.     return maxDays;
  248. }
  249.  
  250.  
  251.  
  252.  
  253.  
  254. /* 2330. Valid Palindrome IV. Medium
  255. Time Complexity:
  256. O(n): We traverse the string once from both ends, where n is the length of the string.
  257. Space Complexity:
  258. O(1): We only use a constant amount of extra space for the counters and indices.
  259.  
  260. console.log(canBePalindrome("abcdba")); // Output: true
  261. console.log(canBePalindrome("aa"));      // Output: true
  262. console.log(canBePalindrome("abcdef"));  // Output: false
  263. */
  264. function canBePalindrome(s) {
  265.     let mismatchCount = 0;
  266.     let left = 0;
  267.     let right = s.length - 1;
  268.    
  269.     while (left < right) {
  270.         if (s[left] !== s[right]) {
  271.             mismatchCount++;
  272.         }
  273.         left++;
  274.         right--;
  275.     }
  276.    
  277.     // If there are 0, 1, or 2 mismatches, it's possible to make the string a palindrome with 1 or 2 operations
  278.     return mismatchCount <= 2;
  279. }
  280.  
  281.  
  282. /* 2340. Minimum Adjacent Swaps to Make a Valid Array. Medium
  283. console.log(minimumSwaps([3, 4, 5, 5, 3, 1])); // Output: 6
  284. console.log(minimumSwaps([9]));               // Output: 0
  285.  
  286. Time Complexity:
  287. O(n): The solution involves a single traversal of the array to find the indices of the smallest and largest elements.
  288. Space Complexity:
  289. O(1): The solution only uses a constant amount of extra space for the indices and counters.
  290. This approach is efficient and scales well even for large input arrays.
  291. */
  292. function minimumSwaps(nums) {
  293.     let n = nums.length;
  294.    
  295.     // Finding the leftmost smallest element and its index
  296.     let minIndex = 0;
  297.     for (let i = 1; i < n; i++) {
  298.         if (nums[i] < nums[minIndex]) {
  299.             minIndex = i;
  300.         }
  301.     }
  302.    
  303.     // Finding the rightmost largest element and its index
  304.     let maxIndex = 0;
  305.     for (let i = 1; i < n; i++) {
  306.         if (nums[i] >= nums[maxIndex]) {
  307.             maxIndex = i;
  308.         }
  309.     }
  310.  
  311.     // If minIndex is before maxIndex, the swaps don't interfere
  312.     if (minIndex < maxIndex) {
  313.         return minIndex + (n - 1 - maxIndex);
  314.     } else {
  315.         // If minIndex is after maxIndex, subtract 1 to account for the overlap
  316.         return minIndex + (n - 1 - maxIndex) - 1;
  317.     }
  318. }
  319.  
  320.  
  321.  
  322.  
  323.  
  324. /* 2405. Optimal Partition of String. Medium
  325. minPartitions("abacaba") = 4
  326. minPartitions("ssssss") = 6
  327.  
  328. Time Complexity:
  329. The time complexity is O(n), where n is the length of the string s, since we are iterating through the string once.
  330. Space Complexity:
  331. The space complexity is O(1) for the partitions counter.
  332. The space complexity is O(26) = O(1) for the seen set since it can only store up to 26 unique lowercase English letters.
  333. */
  334. function minPartitions(s) {
  335.     let partitions = 0;
  336.     let seen = new Set();
  337.    
  338.     for (let char of s) {
  339.         if (seen.has(char)) {
  340.             partitions++;
  341.             seen.clear();
  342.         }
  343.         seen.add(char);
  344.     }
  345.    
  346.     return partitions + 1;
  347. }
  348.  
  349. /* 2408. Design SQL. Medium
  350.  
  351. Time Complexity:
  352. Insert Row: O(1) for each insert since we're simply adding a row to the dictionary.
  353. Delete Row: O(1) for each delete since we're removing a key from the dictionary.
  354. Select Cell: O(1) for each cell selection since we're directly accessing an element in a dictionary and an array.
  355. Space Complexity:
  356. O(n + r), where n is the number of tables and r is the total number of rows across all tables. The space is used for storing the tables, rows, and their metadata. */
  357. class SQL {
  358.     constructor(names, columns) {
  359.         this.tables = {};
  360.  
  361.         // Initialize the tables with their respective columns
  362.         for (let i = 0; i < names.length; i++) {
  363.             this.tables[names[i]] = {
  364.                 columns: columns[i],
  365.                 rows: {},
  366.                 nextId: 1
  367.             };
  368.         }
  369.     }
  370.     insertRow(name, row) {
  371.         const table = this.tables[name];
  372.         table.rows[table.nextId] = row;
  373.         table.nextId++;
  374.     }
  375.     deleteRow(name, rowId) {
  376.         const table = this.tables[name];
  377.         delete table.rows[rowId];
  378.     }
  379.     selectCell(name, rowId, columnId) {
  380.         const table = this.tables[name];
  381.         return table.rows[rowId][columnId - 1];
  382.     }
  383. }
  384.  
  385.  
  386. /* 2422. Merge Operations to Turn Array Into a Palindrome. Medium
  387. minOperations([4,3,2,1,2,3,1]) = 2
  388. minOperations([1,2,3,4]) = 3
  389.  
  390. Time Complexity:
  391. O(n): The solution uses a two-pointer approach and each element is processed at most once, where n is the length of the array.
  392. Space Complexity:
  393. O(1): The solution operates in-place, modifying the original array, and only uses a few extra variables for the pointers and the operations count.
  394. */
  395. function minOperations(nums) {
  396.     let left = 0;
  397.     let right = nums.length - 1;
  398.     let operations = 0;
  399.  
  400.     while (left < right) {
  401.         if (nums[left] === nums[right]) {
  402.             left++;
  403.             right--;
  404.         } else if (nums[left] < nums[right]) {
  405.             nums[left + 1] += nums[left];
  406.             left++;
  407.             operations++;
  408.         } else {
  409.             nums[right - 1] += nums[right];
  410.             right--;
  411.             operations++;
  412.         }
  413.     }
  414.  
  415.     return operations;
  416. }
  417.  
  418.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement