question_slug stringlengths 3 77 | title stringlengths 1 183 | slug stringlengths 12 45 | summary stringlengths 1 160 ⌀ | author stringlengths 2 30 | certification stringclasses 2
values | created_at stringdate 2013-10-25 17:32:12 2025-04-12 09:38:24 | updated_at stringdate 2013-10-25 17:32:12 2025-04-12 09:38:24 | hit_count int64 0 10.6M | has_video bool 2
classes | content stringlengths 4 576k | upvotes int64 0 11.5k | downvotes int64 0 358 | tags stringlengths 2 193 | comments int64 0 2.56k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
final-array-state-after-k-multiplication-operations-i | C++ || Heap | c-heap-by-shishirrsiam-ytna | Complexity
Time complexity:
Space complexity:
Code | shishirRsiam | NORMAL | 2024-12-16T03:28:39.110697+00:00 | 2024-12-16T03:28:39.110697+00:00 | 297 | false | \n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\ntypedef pair<long, int> pi;\nclass Solution {\npublic:\n vector<int> getFinalState(vector<int>& nums, int k, int multiplier) \n {\n priority_queue<pi, vector<pi>, greater<pi>>minHeap;\n \n int n = nums.size();\n for(int i=0;i<n;i++)\n minHeap.push({nums[i], i});\n \n while(k--)\n {\n auto [val, idx] = minHeap.top(); minHeap.pop();\n minHeap.push({val * multiplier, idx});\n }\n\n vector<int>ans(n);\n while(!minHeap.empty())\n {\n auto [val, idx] = minHeap.top(); minHeap.pop();\n ans[idx] = val;\n }\n return ans;\n }\n};\n``` | 4 | 0 | ['Array', 'Math', 'Heap (Priority Queue)', 'Simulation', 'C++'] | 0 |
final-array-state-after-k-multiplication-operations-i | ✅ Easy to Understand | 100% | Heap | Detailed Video Explanation | Java | C++ | Python🔥 | easy-to-understand-100-heap-detailed-vid-ypzm | IntuitionThe problem involves modifying the smallest elements of an array multiple times while keeping track of their positions. A priority queue (min-heap) is | sahilpcs | NORMAL | 2024-12-16T03:08:22.194915+00:00 | 2024-12-16T03:08:22.194915+00:00 | 914 | false | # Intuition\nThe problem involves modifying the smallest elements of an array multiple times while keeping track of their positions. A priority queue (min-heap) is well-suited for efficiently extracting and updating the smallest elements. By maintaining the order of elements based on value and index, we can efficiently perform the required operations.\n\n# Approach\n1. **Priority Queue Initialization**: Use a priority queue (min-heap) to store the elements of the array along with their indices. The priority queue will sort elements by their value, and in case of a tie, by their original index.\n2. **Insert Elements**: Push all elements of the array into the priority queue as pairs `(value, index)`.\n3. **Modify Smallest Elements**: For `k` iterations:\n - Extract the smallest element from the priority queue.\n - Update the corresponding value in the original array by multiplying it with the `multiplier`.\n - Push the updated value along with its index back into the priority queue.\n4. **Return Result**: After `k` iterations, the modified array is returned as the result.\n\n# Complexity\n- **Time complexity**: \n The time complexity is determined by the operations on the priority queue:\n - Inserting all elements takes $$O(n \\log n)$$, where $$n$$ is the size of the array.\n - For each of the $$k$$ iterations, we perform a `poll` and an `offer` operation, each taking $$O(\\log n)$$.\n - Total time complexity: $$O(n \\log n + k \\log n)$$.\n\n- **Space complexity**: \n The space complexity is $$O(n)$$ for the priority queue, as it stores all elements of the array along with their indices.\n\n\n# Code\n```java []\nclass Solution {\n // This method modifies the array by multiplying the smallest elements k times with a given multiplier\n public int[] getFinalState(int[] nums, int k, int multiplier) {\n int n = nums.length;\n\n // Priority queue to maintain elements in ascending order based on value,\n // with a tie-breaker based on their original index\n PriorityQueue<int[]> pq = new PriorityQueue<>(\n (a, b) -> {\n if (a[0] == b[0]) return a[1] - b[1]; // Compare indices if values are equal\n return a[0] - b[0]; // Otherwise, compare based on values\n }\n );\n\n // Add all elements of nums along with their indices into the priority queue\n for (int i = 0; i < n; i++) {\n pq.offer(new int[]{nums[i], i});\n }\n\n // Perform the operation k times\n while (k-- > 0) {\n // Poll the smallest element from the queue\n int[] t = pq.poll();\n int v = t[0]; // Value of the smallest element\n int i = t[1]; // Index of the smallest element\n\n // Update the value in the original array by multiplying with the multiplier\n nums[i] = v * multiplier;\n\n // Push the updated value back into the priority queue\n pq.offer(new int[]{nums[i], i});\n }\n\n // Return the modified array\n return nums;\n }\n}\n\n```\n```c++ []\n#include <vector>\n#include <queue>\nusing namespace std;\n\nclass Solution {\npublic:\n vector<int> getFinalState(vector<int>& nums, int k, int multiplier) {\n int n = nums.size();\n\n // Min-heap to store pairs of (value, index)\n priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;\n\n // Add all elements with their indices to the heap\n for (int i = 0; i < n; i++) {\n pq.push({nums[i], i});\n }\n\n // Perform k modifications\n while (k-- > 0) {\n auto [val, idx] = pq.top(); // Get the smallest value and its index\n pq.pop(); // Remove it from the heap\n\n nums[idx] = val * multiplier; // Update the value in the array\n pq.push({nums[idx], idx}); // Push the updated value back to the heap\n }\n\n return nums; // Return the modified array\n }\n};\n\n```\n```python []\nfrom heapq import heappop, heappush\n\nclass Solution:\n def getFinalState(self, nums, k, multiplier):\n n = len(nums)\n\n # Min-heap to store pairs of (value, index)\n pq = []\n for i, num in enumerate(nums):\n heappush(pq, (num, i))\n\n # Perform k modifications\n while k > 0:\n k -= 1\n val, idx = heappop(pq) # Get the smallest value and its index\n\n nums[idx] = val * multiplier # Update the value in the array\n heappush(pq, (nums[idx], idx)) # Push the updated value back to the heap\n\n return nums\n\n```\n\n\nLeetCode 3264 Final Array State After K Multiplication Operations I | Heap | Asked in Amazon\nhttps://youtu.be/qZLmio7PXE0 | 4 | 0 | ['Array', 'Heap (Priority Queue)', 'Python', 'C++', 'Java'] | 1 |
final-array-state-after-k-multiplication-operations-i | Efficient Array Transformation Using Min-Heap Optimization || Eassy Solution | efficient-array-transformation-using-min-c38e | IntuitionThe task involves transforming an integer array by repeatedly selecting the minimum element, multiplying it by a constant, and updating the array. Usin | Aman_8808_Singh | NORMAL | 2024-12-16T02:46:43.247414+00:00 | 2024-12-16T02:46:43.247414+00:00 | 97 | false | # Intuition\nThe task involves transforming an integer array by repeatedly selecting the minimum element, multiplying it by a constant, and updating the array. Using a min-heap allows efficient access to the smallest element, ensuring we process elements correctly in ascending order.\n\n# Approach\n1. Initialization:\n\n - Use a min-heap (priority queue) to track the smallest element in the array.\n2. Simulation:\n\n - For k iterations:\n - Extract the minimum element from the heap.\n - Find the first occurrence of this element in the original array.\n - Update this element by multiplying it by mult.\n - Insert the updated value back into the heap.\n3. Return Result:\n\n - Return the modified array.\n\n# Complexity\n- Time complexity:\nO(k(n+logn))\n\n- Space complexity:\nO(n)\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<int> getFinalState(vector<int>& nums, int k, int mult) {\n priority_queue<int, vector<int>, greater<int>> mp;\n for(int i : nums) mp.push(i);\n for(int i=0;i<k;i++){\n int a=mp.top();\n mp.pop();\n for(int& j : nums){\n if(j==a){\n j=mult*a;\n mp.push(j);\n break;\n }\n }\n }\n return nums;\n }\n};\n``` | 4 | 0 | ['Array', 'Heap (Priority Queue)', 'C++'] | 1 |
final-array-state-after-k-multiplication-operations-i | Simple Java || C++ Code ☠️ | simple-java-c-code-by-abhinandannaik1717-8bmf | \n\n# Code\njava []\nclass Solution {\n public int[] getFinalState(int[] nums, int k, int multiplier) {\n while(k!=0){\n int[] ans = help(n | abhinandannaik1717 | NORMAL | 2024-08-25T07:45:43.520010+00:00 | 2024-08-25T07:45:43.520039+00:00 | 922 | false | \n\n# Code\n```java []\nclass Solution {\n public int[] getFinalState(int[] nums, int k, int multiplier) {\n while(k!=0){\n int[] ans = help(nums);\n int min = ans[0];\n int mi = ans[1];\n min *= multiplier;\n nums[mi] = min;\n k--;\n }\n return nums;\n }\n public int[] help(int[] nums){\n int n = nums.length;\n int min = nums[0],mi = 0;\n for(int i=1;i<n;i++){\n if(min > nums[i]){\n min = nums[i];\n mi = i;\n }\n }\n int[] arr = {min,mi};\n return arr;\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n vector<int> getFinalState(vector<int>& nums, int k, int multiplier) {\n while(k!=0){\n vector<int> ans = help(nums);\n int min = ans[0];\n int mi = ans[1];\n min *= multiplier;\n nums[mi] = min;\n k--;\n }\n return nums;\n }\n vector<int> help(vector<int>& nums){\n int n = nums.size();\n int min = nums[0],mi = 0;\n for(int i=1;i<n;i++){\n if(min > nums[i]){\n min = nums[i];\n mi = i;\n }\n }\n vector<int> arr = {min,mi};\n return arr;\n }\n};\n```\n\n\n\n\n### Explanation\n\nThe code is implemented in C++ within a class `Solution`, and consists of two main functions:\n1. `getFinalState(vector<int>& nums, int k, int multiplier)`\n2. `help(vector<int>& nums)`\n\n#### 1. `getFinalState` Function\nThis function performs `k` operations on the `nums` array.\n\n- **Input Parameters:**\n - `vector<int>& nums`: A reference to the input array.\n - `int k`: The number of operations to perform.\n - `int multiplier`: The multiplier used to replace the minimum value.\n\n- **Logic:**\n - The function enters a `while` loop that continues as long as `k` is not zero.\n - In each iteration:\n - It calls the helper function `help(nums)` to find the minimum value in the array and its index.\n - The helper function returns a vector `ans` with two elements:\n - `ans[0]`: The minimum value (`min`).\n - `ans[1]`: The index of the minimum value (`mi`).\n - The code multiplies this minimum value by the `multiplier`.\n - The updated value is then assigned back to the original index (`mi`) in the `nums` array.\n - `k` is decremented by 1, indicating that one operation has been completed.\n - The process repeats until all `k` operations have been performed.\n - Finally, the function returns the modified `nums` array.\n\n#### 2. `help` Function\nThis helper function finds the minimum value in the array `nums` and its index.\n\n- **Input Parameters:**\n - `vector<int>& nums`: A reference to the input array.\n\n- **Logic:**\n - It initializes two variables:\n - `min` to the first element of `nums`.\n - `mi` to 0, representing the index of the minimum value.\n - It then iterates through the `nums` array starting from the second element.\n - For each element, it checks if the current element is smaller than `min`.\n - If so, it updates `min` to this element and `mi` to the current index.\n - After traversing the entire array, the function returns a vector containing the `min` value and its index (`mi`).\n\n### Step-by-Step Walkthrough of the Code Execution:\n\nLet\'s illustrate the code execution with an example:\n\n**Example:**\n- `nums = [4, 3, 2, 1]`\n- `k = 2`\n- `multiplier = 2`\n\n**Execution:**\n\n1. **First Iteration of `getFinalState`:**\n - Call `help(nums)`:\n - Finds minimum value `1` at index `3`.\n - Replace `1` with `1 * 2 = 2`.\n - Updated `nums`: `[4, 3, 2, 2]`.\n - Decrement `k` to `1`.\n\n2. **Second Iteration of `getFinalState`:**\n - Call `help(nums)` again:\n - Finds minimum value `2` at index `2` (first occurrence of the minimum value `2`).\n - Replace `2` with `2 * 2 = 4`.\n - Updated `nums`: `[4, 3, 4, 2]`.\n - Decrement `k` to `0`.\n\n3. **End of Loop:**\n - `k` is now `0`, exit the `while` loop.\n - Return the final `nums` array: `[4, 3, 4, 2]`.\n\n### Complexity Analysis:\n\n- **Time Complexity:** ```O(n * k)```\n - `getFinalState`: Runs in \\(O(k \\times n)\\) where \\(n\\) is the size of the `nums` array.\n - The `while` loop runs `k` times.\n - Each call to `help` runs in \\(O(n)\\) to find the minimum value.\n- **Space Complexity:** ```O(1)```\n - The function uses \\(O(1)\\) extra space (excluding the input) since it only uses a few extra variables and the helper function returns a vector of size 2.\n\n\n\n\n\n\n\n | 4 | 0 | ['Array', 'C++', 'Java'] | 0 |
final-array-state-after-k-multiplication-operations-i | Leetcode weekly contest 412 || Simplest Approach || No PriorityQueue || 100% beats || 3ms | leetcode-weekly-contest-412-simplest-app-dnoa | Intuition\nTo solve the problem, you need to perform k operations on an array where each operation involves finding the minimum value, replacing it with its pro | Viswas12 | NORMAL | 2024-08-25T04:12:50.000808+00:00 | 2024-08-25T04:12:50.000827+00:00 | 138 | false | # Intuition\nTo solve the problem, you need to perform k operations on an array where each operation involves finding the minimum value, replacing it with its product with a multiplier, and repeating this process k times. The challenge is to efficiently handle these operations, especially when k is large.\n\n# Approach\n**Data Structure Choice:**\nUse an ArrayList to store the values from the nums array because it allows for dynamic resizing and indexed access.\nIn each operation, find the minimum value using Collections.min() and its index using indexOf(), and then update the value at that index.\n\n**Operations:**\nFor each of the k operations, determine the minimum value in the ArrayList and replace it with the product of the minimum value and the multiplier.\nThis involves scanning the entire list to find the minimum value and its index, then updating it.\n\n**Return Result:**\nAfter all k operations, convert the ArrayList back to a primitive array and return it\n\n# Complexity\n- Time complexity:\nEach operation involves finding the minimum value and its index, which takes O(n) time where n is the number of elements in nums.\nYou perform this operation k times, so the total time complexity is \nO(k\u22C5n).\n\n- Space complexity:\nThe space complexity is O(n) due to the ArrayList storing the elements.Additional space for the result array is also O(n), but this is not a concern since it is a part of the output.\n\n# Code\n```java []\nclass Solution {\n public int[] getFinalState(int[] nums, int k, int multiplier) {\n List<Integer> ds = new ArrayList<>();\n for(int num:nums){\n ds.add(num);\n }\n for(int i=0;i<k;i++){\n int min = Collections.min(ds);\n int idx = ds.indexOf(min);\n ds.set(idx,multiplier*min);\n }\n int [] result = new int[ds.size()];\n for(int i=0;i<ds.size();i++){\n result[i] = ds.get(i);\n }\n return result;\n }\n}\n``` | 4 | 0 | ['Java'] | 1 |
final-array-state-after-k-multiplication-operations-i | Java Simple Solution | Linear Solution | java-simple-solution-linear-solution-by-1fs4j | Code\njava []\nclass Solution {\n private int helper(int[] nums){\n int min_idx = 0;\n int min = nums[0];\n for(int i=1;i<nums.length; i | Shree_Govind_Jee | NORMAL | 2024-08-25T04:03:30.123464+00:00 | 2024-08-25T04:03:30.123499+00:00 | 449 | false | # Code\n```java []\nclass Solution {\n private int helper(int[] nums){\n int min_idx = 0;\n int min = nums[0];\n for(int i=1;i<nums.length; i++){\n if(min > nums[i]){\n min = nums[i];\n min_idx=i;\n }\n }\n return min_idx;\n }\n \n public int[] getFinalState(int[] nums, int k, int multiplier) {\n for(int i=0; i<k; i++){\n int idx = helper(nums);\n nums[idx] *= multiplier;\n }\n return nums;\n }\n}\n```\n```java[]\nclass Solution {\n public int[] getFinalState(int[] nums, int k, int multiplier) {\n PriorityQueue<int[]> pq = new PriorityQueue<>((a, b)->a[0]==b[0]?a[1]-b[1]:a[0]-b[0]);\n for(int i=0; i<nums.length; i++){\n pq.offer(new int[]{nums[i], i});\n }\n \n for(int i=0; i<k; i++){\n int[] top = pq.remove();\n \n int new_num = ((top[0]*multiplier));\n nums[top[1]] = new_num;\n \n pq.offer(new int[]{new_num, top[1]});\n }\n return nums;\n }\n}\n``` | 4 | 1 | ['Array', 'Math', 'Heap (Priority Queue)', 'Java'] | 0 |
final-array-state-after-k-multiplication-operations-i | simple solution with simple logic | simple-solution-with-simple-logic-by-muh-zrp3 | IntuitionApproachcreate a new array with the elements of nums (for tracking the out put array).
create a while loop for checking the condition to break the loop | Muhamed_Reswan | NORMAL | 2024-12-16T05:18:30.577958+00:00 | 2024-12-16T05:18:30.577958+00:00 | 168 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\ncreate a new array with the elements of nums (for tracking the out put array). \ncreate a while loop for checking the condition to break the loop.\nif k > 0 enter with in the loop.\nthen take the minimum value by using Math.min method.\nthen find the indexof that value from array.\nthen replace the value (by using array method splice) with value multiply with multiplier.\nreduce the count of k.\nwhile loop is over return the array.\n\n\n# Complexity\n- Time complexity:O(n * k)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```javascript []\n/**\n * @param {number[]} nums\n * @param {number} k\n * @param {number} multiplier\n * @return {number[]}\n */\nvar getFinalState = function (nums, k, multiplier) {\n let array = nums\n while (k > 0) {\n let val = Math.min(...array)\n let index = array.indexOf(val)\n array.splice(index, 1, val * multiplier)\n k--\n }\n return array\n};\n``` | 3 | 0 | ['Array', 'JavaScript'] | 0 |
final-array-state-after-k-multiplication-operations-i | ✅✅ Most easy and simple solution 🔥🔥 | most-easy-and-simple-solution-by-ishanba-il7a | Intuition
The problem is asking us to perform k operations on an array, where each operation involves finding the smallest element in the array, multiplying it | ishanbagra | NORMAL | 2024-12-16T05:07:21.363188+00:00 | 2024-12-16T05:07:21.363188+00:00 | 152 | false | Intuition\nThe problem is asking us to perform k operations on an array, where each operation involves finding the smallest element in the array, multiplying it by a multiplier, and replacing it with the updated value. After completing the k operations, we return the final state of the array.\n\nWe can efficiently achieve this using a priority queue (min-heap). The priority queue helps us retrieve the minimum value in O(log n) time, and since we need to perform k operations, the heap allows us to update the smallest element efficiently.\n\nApproach\nMin-Heap:\n\nWe push each element of the array along with its index into a min-heap. This allows us to efficiently retrieve the smallest element and track its original index.\nPerform Operations:\n\nFor k iterations, we pop the smallest element from the heap, multiply it by the multiplier, and then push the updated value along with its index back into the heap.\nFinal State:\n\nAfter performing k operations, we extract all elements from the heap and place them back into the result array ans at their original indices.\nComplexity\nTime complexity:\nEach operation (push and pop) on a priority queue takes O(log n), where n is the size of the array. Since we perform k operations and then process the entire array to build the result, the total time complexity is:\nO(k\u22C5logn+n\u22C5logn)\nSpace complexity:\nThe space complexity is dominated by the storage of the heap, which requires O(n) space to store the elements, and the result array ans which also takes O(n) space. Therefore, the space complexity is:\nO(n)\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<int> getFinalState(vector<int>& nums, int k, int multiplier) {\n vector<int> ans(nums.size());\n using P = pair<int, int>;\n priority_queue<P, vector<P>, greater<>> minHeap;\n\n for (int i = 0; i < nums.size(); ++i) {\n minHeap.emplace(nums[i], i);\n }\n\n while (k-- > 0) {\n P top = minHeap.top();\n int num = top.first;\n int idx = top.second;\n minHeap.pop();\n minHeap.emplace(num * multiplier, idx);\n }\n\n while (!minHeap.empty()) {\n P top = minHeap.top();\n int num = top.first;\n int idx = top.second;\n minHeap.pop();\n ans[idx] = num;\n }\n\n return ans;\n }\n};\n\n\n```\n\n | 3 | 0 | ['Array', 'Heap (Priority Queue)', 'C++'] | 1 |
final-array-state-after-k-multiplication-operations-i | Python || Heap | test-by-shishirrsiam-mvpx | Complexity
Time complexity:
Space complexity:
Code | shishirRsiam | NORMAL | 2024-12-16T03:16:36.337530+00:00 | 2024-12-16T03:22:49.902684+00:00 | 262 | false | \n\n# Complexity\n- Time complexity: \n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nclass Solution:\n def getFinalState(self, nums: List[int], k: int, multiplier: int) -> List[int]:\n minHeap = [(val, idx) for idx, val in enumerate(nums)]\n heapify(minHeap)\n\n for _ in range(k):\n val, idx = heappop(minHeap)\n heappush(minHeap, (val * multiplier, idx))\n \n ans = [0] * len(nums)\n while minHeap:\n val, idx = heappop(minHeap)\n ans[idx] = val\n return ans\n``` | 3 | 0 | ['Array', 'Math', 'Heap (Priority Queue)', 'Simulation', 'Python', 'Python3'] | 1 |
final-array-state-after-k-multiplication-operations-i | Kotlin Heap | kotlin-heap-by-agent-10-0ine | Code\nkotlin []\nclass Solution {\n fun getFinalState(nums: IntArray, k: Int, multiplier: Int): IntArray {\n val pq = PriorityQueue<Int>() { a,b->\n | agent-10 | NORMAL | 2024-10-11T12:04:27.527600+00:00 | 2024-10-11T12:04:27.527631+00:00 | 30 | false | # Code\n```kotlin []\nclass Solution {\n fun getFinalState(nums: IntArray, k: Int, multiplier: Int): IntArray {\n val pq = PriorityQueue<Int>() { a,b->\n val cr = nums[a].compareTo(nums[b])\n if(cr != 0) cr else a.compareTo(b)\n }\n pq.addAll(nums.indices)\n repeat(k) {\n val i = pq.remove()\n nums[i] *= multiplier\n pq.add(i)\n }\n\n return nums\n }\n}\n``` | 3 | 0 | ['Kotlin'] | 3 |
final-array-state-after-k-multiplication-operations-i | Simple || Easy to Understand || 100% Beats | simple-easy-to-understand-100-beats-by-k-6nwv | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | kdhakal | NORMAL | 2024-09-03T18:15:17.396380+00:00 | 2024-09-03T18:15:17.396412+00:00 | 3 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int[] getFinalState(int[] nums, int k, int multiplier) {\n \n while(k > 0) {\n int minVal = Integer.MAX_VALUE, minIndex = 101;\n boolean flag = false;\n for(int i = 0; i < nums.length; i++) {\n if(nums[i] < minVal) {\n minVal = nums[i];\n minIndex = i;\n flag = true;\n }\n }\n \n if(flag) nums[minIndex] = minVal * multiplier;\n k--;\n }\n return nums;\n }\n}\n``` | 3 | 0 | ['Java'] | 0 |
final-array-state-after-k-multiplication-operations-i | Solution | solution-by-zefry7-ebim | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | zefry7 | NORMAL | 2024-08-25T09:57:27.317406+00:00 | 2024-08-25T09:57:27.317445+00:00 | 110 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```javascript []\n/**\n * @param {number[]} nums\n * @param {number} k\n * @param {number} multiplier\n * @return {number[]}\n */\nvar getFinalState = function(nums, k, multiplier) {\n for(let i = 0; i < k; ++i) {\n m = Math.min(...nums)\n index = nums.indexOf(m)\n nums[index] *= multiplier\n }\n return nums\n};\n``` | 3 | 0 | ['JavaScript'] | 0 |
final-array-state-after-k-multiplication-operations-i | Beats 100% Easy Java Solution Using Priority Queue | beats-100-easy-java-solution-using-prior-urxv | Intuition\nThe problem asks us to maximize the sum of an array by multiplying the smallest element by a given multiplier k times. A greedy approach can be used | its264 | NORMAL | 2024-08-25T05:27:26.602933+00:00 | 2024-08-25T05:44:10.905682+00:00 | 137 | false | # Intuition\nThe problem asks us to maximize the sum of an array by multiplying the smallest element by a given multiplier k times. A greedy approach can be used here, where we repeatedly multiply the smallest element until k operations are performed.\n\n# Approach\n1)Create a priority queue: Use a min-heap priority queue to efficiently find and remove the smallest element in the array.\n2)Iterate k times:\n2.1)Find the smallest element in the array using the priority queue.\n2.2)Multiply the smallest element by the multiplier.\n2.3)Update the priority queue with the new value.\n3)Return the sum of the array: After k iterations, return the sum of the elements in the array.\n\n# Complexity\n- Time complexity:\nCreating the priority queue: O(n)\nIterating k times and updating the priority queue: O(k*n*log n) (due to heap operations)\nTherefore, the overall time complexity is **O(k*n*log n).**\n\n- Space complexity:\nThe priority queue stores n elements, so the space complexity is **O(n)**.\n\n# Code\n```java []\nclass Solution {\n public int[] getFinalState(int[] nums, int k, int multiplier) {\n PriorityQueue<Integer> pq=new PriorityQueue<Integer>();\n for(int i=0;i<nums.length;i++){\n pq.add(nums[i]);\n }\n while(k>0){\n for(int i=0;i<nums.length;i++){\n if(nums[i]==pq.peek()){\n nums[i]=nums[i]*multiplier;\n k--;\n pq.poll();\n pq.add(nums[i]);\n break;\n }\n }\n }\n return nums;\n }\n}\n``` | 3 | 0 | ['Array', 'Math', 'Heap (Priority Queue)', 'Java'] | 1 |
final-array-state-after-k-multiplication-operations-i | simple and easy C++ solution 😍❤️🔥 | simple-and-easy-c-solution-by-shishirrsi-a56t | \n# if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n###### Let\'s Connect on LinkedIn: www.linkedin.com/in/shishirrsiam\n###### Let\'s Connect on Facebook | shishirRsiam | NORMAL | 2024-08-25T04:26:45.611096+00:00 | 2024-08-25T04:26:45.611114+00:00 | 349 | false | \n# if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n###### Let\'s Connect on LinkedIn: www.linkedin.com/in/shishirrsiam\n###### Let\'s Connect on Facebook: www.fb.com/shishirrsiam\n\n\n# Complexity\n- Time complexity: O((n+k)logn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\ntypedef pair<long, int> pi;\nclass Solution {\npublic:\n vector<int> getFinalState(vector<int>& nums, int k, int multiplier) \n {\n int mod = 1e9+7;\n priority_queue<pi,vector<pi>,greater<pi>>pq;\n int n = nums.size();\n for(int i=0;i<n;i++)\n pq.push({nums[i], i});\n \n while(k--)\n {\n auto top = pq.top(); pq.pop();\n int val = (top.first * multiplier) % mod;\n int idx = top.second;\n pq.push({val, idx});\n }\n\n vector<int>ans(n);\n while(!pq.empty())\n {\n auto top = pq.top(); pq.pop();\n int val = top.first;\n int idx = top.second;\n ans[idx] = val;\n }\n return ans;\n }\n};\n``` | 3 | 0 | ['Greedy', 'Heap (Priority Queue)', 'C++'] | 4 |
final-array-state-after-k-multiplication-operations-i | Easy Beats 100% | easy-beats-100-by-jaycodingninja-16n3 | Intuition\n Describe your first thoughts on how to solve this problem. \nGet the smallest element and multiply it but the multiplier.\n# Approach\n Describe you | JayCodingNinja | NORMAL | 2024-08-25T04:05:41.548629+00:00 | 2024-08-25T04:05:41.548656+00:00 | 346 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nGet the smallest element and multiply it but the multiplier.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Iterate k times.\n- In each iteration, find the smallest element in the vector nums using min_element.\n- Multiply this smallest element by multiplier.\n\n# Complexity\n- Time complexity:\n O(k * n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(1)\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<int> getFinalState(vector<int>& nums, int k, int mult) {\n for (int i = 0; i < k; ++i) \n {\n auto min_elem = min_element(nums.begin(), nums.end());\n *min_elem *= mult;\n }\n return nums;\n }\n};\n``` | 3 | 0 | ['C++'] | 1 |
final-array-state-after-k-multiplication-operations-i | 1ms 100% beat in java very easiest code 😊. | 1ms-100-beat-in-java-very-easiest-code-b-naxy | Code | Galani_jenis | NORMAL | 2025-01-09T08:32:55.580565+00:00 | 2025-01-09T08:32:55.580565+00:00 | 62 | false | 
# Code
```java []
class Solution {
public int[] getFinalState(int[] nums, int k, int multiplier) {
for (int i = 0; i < k; i++) {
int min = Integer.MAX_VALUE;
for (int j = 0; j < nums.length; j++) {
if (min > nums[j]) {
min = nums[j]; // Update the minimum value found
}
}
for (int j = 0; j < nums.length; j++) {
if (min == nums[j]) {
nums[j] *= multiplier; // Multiply the smallest element by 'multiplier'
break;
}
}
}
return nums;
}
}
``` | 2 | 0 | ['Java'] | 0 |
final-array-state-after-k-multiplication-operations-i | java || 1ms || faster code || easy to understand | java-1ms-faster-code-easy-to-understand-ulb9i | class Solution {\n\n public int[] getFinalState(int[] nums, int k, int multiplier) {\n int n = nums.length;\n\n for (int j = 0; j < k; j++) {\n | Seema_Kumari1 | NORMAL | 2024-12-18T05:20:12.752285+00:00 | 2024-12-18T05:20:12.752321+00:00 | 6 | false | class Solution {\n\n public int[] getFinalState(int[] nums, int k, int multiplier) {\n int n = nums.length;\n\n for (int j = 0; j < k; j++) {\n // Find the index of the smallest element in the array\n int minIndex = 0;\n for (int i = 0; i < n; i++) {\n if (nums[i] < nums[minIndex]) {\n minIndex = i;\n }\n }\n\n // Multiply the smallest element by the multiplier\n nums[minIndex] *= multiplier;\n }\n\n return nums;\n }\n} | 2 | 0 | ['Java'] | 1 |
final-array-state-after-k-multiplication-operations-i | 🔥 BEATS 100% | 💡BEGINNER FRIENDLY |✅ MULTI-LANGUAGE ✅ | 🌟JAVA | C++ | PYTHON | SWIFT | DART🚀 | beats-100-beginner-friendly-multi-langua-4n1s | IntuitionFind the smallest number in the list and multiply it by a given value. Repeat this process k times.ApproachIterate through the list to find the minimum | mehravarun666 | NORMAL | 2024-12-17T10:21:29.952730+00:00 | 2024-12-17T10:21:29.952730+00:00 | 21 | false | \n\n# Intuition\n**Find the smallest number in the list and multiply it by a given value. Repeat this process k times.**\n\n# Approach\n**Iterate through the list to find the minimum element and its index. Multiply it by the multiplier, decrement k, and repeat until k becomes 0. Return the updated list**.\n\n# Complexity\n- Time complexity:\n**O(k\u22C5n), where k is the number of operations, and n is the size of the array.**\n\n- Space complexity: \n**O(1), as no extra space is used apart from variables.**\n\n# Code\n```java []\nimport java.util.*;\n\nclass Solution {\n public int[] getFinalState(int[] nums, int k, int multiplier) {\n while (k != 0) { \n int minimum = nums[0]; // Initialize the minimum value with the first element\n int index = 0; // Store the index of the minimum value\n\n for (int i = 1; i < nums.length; i++) { \n if (nums[i] < minimum) { // Find the minimum value in the array\n minimum = nums[i];\n index = i;\n }\n }\n nums[index] *= multiplier; // Multiply the minimum value by the multiplier\n k--; \n }\n return nums; \n }\n}\n\n\n\n```\n```C++ []\n#include <vector>\nusing namespace std;\n\nclass Solution {\npublic:\n vector<int> getFinalState(vector<int>& nums, int k, int multiplier) {\n while (k != 0) {\n int minimum = nums[0]; // Initialize the minimum value as the first element\n int index = 0; // Track the index of the minimum element\n\n for (int i = 1; i < nums.size(); i++) {\n if (nums[i] < minimum) { // Check for the minimum element in the array\n minimum = nums[i];\n index = i;\n }\n }\n nums[index] *= multiplier; // Update the minimum element by multiplying it\n k--; \n }\n return nums; \n }\n};\n\n```\n```python3 []\nclass Solution:\n def getFinalState(self, nums: List[int], k: int, multiplier: int) -> List[int]:\n while k != 0:\n minimum = nums[0] # Initialize the minimum value with the first element\n index = 0\n for i in range(1, len(nums)):\n if nums[i] < minimum: # Check for the minimum value in the list\n minimum = nums[i]\n index = i\n nums[index] *= multiplier\n k -= 1\n return nums\n\n\n\n```\n```Swift []\nclass Solution {\n func getFinalState(_ nums: [Int], _ k: Int, _ multiplier: Int) -> [Int] {\n var nums = nums\n var k = k\n \n while k != 0 {\n var minimum = nums[0] // Initialize the minimum value as the first element\n var index = 0 // Track the index of the minimum value\n \n for i in 1..<nums.count {\n if nums[i] < minimum { // Find the minimum value and its index\n minimum = nums[i]\n index = i\n }\n }\n nums[index] *= multiplier // Update the minimum value with the multiplier\n k -= 1 \n }\n return nums \n }\n}\n\n```\n```python []\nclass Solution(object):\n def getFinalState(self, nums, k, multiplier):\n """\n :type nums: List[int]\n :type k: int\n :type multiplier: int\n :rtype: List[int]\n """\n while k != 0:\n minimum = nums[0] # Initialize the minimum value with the first element\n index = 0 # Store the index of the minimum value\n \n for i in range(1, len(nums)):\n if nums[i] < minimum: # Check for the minimum value in the list\n minimum = nums[i]\n index = i\n nums[index] *= multiplier # Update the minimum value by multiplying it\n k -= 1 \n return nums \n\n\n\n\n```\n```Dart []\nclass Solution {\n List<int> getFinalState(List<int> nums, int k, int multiplier) {\n while (k != 0) {\n int minimum = nums[0]; // Initialize the minimum value as the first element\n int index = 0; // Store the index of the minimum value\n \n for (int i = 1; i < nums.length; i++) {\n if (nums[i] < minimum) { // Find the minimum value and its position\n minimum = nums[i];\n index = i;\n }\n }\n nums[index] *= multiplier; // Multiply the minimum value by the multiplier\n k--;\n }\n return nums;\n }\n}\n\n\n\n```\n\n```\n```\n```\n```\n```\n```\n\n | 2 | 0 | ['Array', 'Greedy', 'Swift', 'C++', 'Java', 'Python3', 'Dart'] | 0 |
final-array-state-after-k-multiplication-operations-i | Simple solution with Kotlin | simple-solution-with-kotlin-by-penguida-cb2t | Complexity
Time complexity: 1 ms | 100 %
Space complexity: 41.81 mb | 31.58 %
Code | penguida | NORMAL | 2024-12-16T19:13:44.713173+00:00 | 2024-12-16T19:13:44.713173+00:00 | 7 | false | # Complexity\n- Time complexity: 1 ms | 100 %\n\n- Space complexity: 41.81 mb | 31.58 %\n\n# Code\n```kotlin []\nclass Solution {\n fun getFinalState(nums: IntArray, k: Int, multiplier: Int): IntArray {\n if(multiplier == 1) return nums\n\n repeat(k){\n val pos = findMin(nums)\n nums[pos] = nums[pos] * multiplier\n }\n return nums\n\n }\n\n fun findMin(nums: IntArray): Int {\n var min = Integer.MAX_VALUE\n var pos = 0\n \n for(i in nums.indices){\n if(min > nums[i]){\n min = nums[i]\n pos = i\n }\n }\n return pos\n }\n}\n``` | 2 | 0 | ['Kotlin'] | 0 |
final-array-state-after-k-multiplication-operations-i | Final Array State After K Multiplication Operations | final-array-state-after-k-multiplication-2e3y | Approach
Run a loop for k iterations.
In each iteration:
Find the minimum value in the array.
Multiply this minimum value by the multiplier.
Update the array w | HarisubashThangavel | NORMAL | 2024-12-16T16:56:38.344113+00:00 | 2024-12-16T16:56:38.344113+00:00 | 9 | false | # Approach\n<!-- Describe your approach to solving the problem. -->\n1. Run a loop for k iterations.\n2. In each iteration:\n * Find the minimum value in the array.\n * Multiply this minimum value by the multiplier.\n * Update the array with the modified minimum value while keeping other values unchanged.\n\nReturn the updated array after k iterations.\n\n# Complexity\n- Time complexity: O(K\u2217N)\n\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int[] getFinalState(int[] nums, int k, int multiplier) {\n for (int i = 0; i < k; i++) {\n int minIndex = 0;\n for (int j = 1; j < nums.length; j++) {\n if (nums[j] < nums[minIndex]) {\n minIndex = j;\n }\n }\n\n nums[minIndex] *= multiplier;\n }\n \n return nums;\n }\n}\n\n``` | 2 | 0 | ['Java'] | 0 |
final-array-state-after-k-multiplication-operations-i | SIMPLE AND EASY SOLUTION IN JAVA || BEATS 100% USERS..... | simple-and-easy-solution-in-java-beats-1-lcfn | Complexity
Time complexity: O(K*N)
Space complexity: O(1)
Code | abhayCodez | NORMAL | 2024-12-16T16:21:09.980437+00:00 | 2024-12-16T16:21:09.980437+00:00 | 28 | false | # Complexity\n- Time complexity: O(K*N)\n\n- Space complexity: O(1)\n# Code\n```java []\nclass Solution {\n public int[] getFinalState(int[] nums, int k, int multiplier) {\n for(int i=1;i<=k;i++){\n int min = minimum(nums);\n nums[min] *= multiplier;\n }\n return nums;\n }\n\n public int minimum(int[] arr){\n int min=arr[0];\n int minIndex =0;\n for (int i = 1; i < arr.length; i++) {\n if (arr[i] < min) {\n min = arr[i];\n minIndex = i;\n }\n }\n return minIndex;\n }\n}\n``` | 2 | 0 | ['Java'] | 0 |
final-array-state-after-k-multiplication-operations-i | Beats 100% | Brute Force | beats-100-brute-force-by-akshatchawla130-0dty | IntuitionApproachComplexity
Time complexity: O(k*n)
Space complexity:I= O(1)
Code | akshatchawla1307 | NORMAL | 2024-12-16T15:13:25.799775+00:00 | 2024-12-16T15:13:25.799775+00:00 | 8 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(k*n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:I= O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<int> getFinalState(vector<int>& nums, int k, int multiplier) {\n while(k--)\n nums[min_element(nums.begin(),nums.end())-nums.begin()]*=multiplier;\n return nums;\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
final-array-state-after-k-multiplication-operations-i | ||💀|| 1 MS🔥-- BEATS 100%✅-- EASY JAVA SOLUTION | 1-ms-beats-100-easy-java-solution-by-san-bg1x | IntuitionThe problem involves modifying an array by multiplying its smallest element by a given multiplier repeatedly for k iterations. The goal is to return th | sanketborse | NORMAL | 2024-12-16T12:51:46.829699+00:00 | 2024-12-16T12:58:50.889209+00:00 | 12 | false | # Intuition\n\nThe problem involves modifying an array by multiplying its smallest element by a given multiplier repeatedly for k iterations. The goal is to return the modified array after all operations.\n\nThe intuition is straightforward:\n- Find the smallest element in the array.\n- Multiply this smallest element by the given multiplier.\n- Repeat this process k times to simulate the effect of applying the operation sequentially.\n\nThe focus is on maintaining correctness by identifying the current smallest element in each iteration.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nApproach\nIterate k Times:\nFor k iterations, find the smallest element in the array. This ensures we apply the operation the correct number of times.\n\nFinding the Smallest Element:\nUse a helper method (findMinIndex) to traverse the array and find the index of the smallest element in O(n) time.\n\nModify the Smallest Element:\nMultiply the smallest element by the multiplier and update its value in the array.\n\nRepeat:\nRepeat the above process k times, ensuring that after each modification, the updated array is considered for the next smallest element.\n\nReturn Result:\nOnce all k operations are complete, return the modified array.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time Complexity:\n\nFinding the Smallest Element:\nThe findMinIndex method scans the entire array to find the smallest element. This takes O(n) time.\nRepeating for k Iterations:\nThe smallest element is found k times. This results in \nO(n\u22C5k) overall time complexity.\nOverall Time Complexity: \nO(n\u22C5k).\n\n- Space Complexity:\n\nThe algorithm operates directly on the input array without using any additional data structures.\nOnly a few auxiliary variables (e.g., minimum, index, and loop counters) are used.\nOverall Space Complexity: O(1) (constant space).\n\n\n\n# Code\n```java []\nclass Solution {\n public static int[] getFinalState(int[] nums, int k, int multiplier) {\n // Perform the operation `k` times\n for (int i = 1; i <= k; i++) {\n int currentLeastIndex = findMinIndex(nums); // Find the index of the smallest element\n nums[currentLeastIndex] *= multiplier; // Multiply the smallest element by the multiplier\n }\n return nums;\n }\n\n // Helper method to find the index of the smallest element in the array\n public static int findMinIndex(int[] nums) {\n int index = 0;\n int minimum = Integer.MAX_VALUE; // Use a more appropriate constant for maximum integer value\n for (int i = 0; i < nums.length; i++) { // Simplified iteration condition\n if (nums[i] < minimum) { // Update minimum and index when a smaller value is found\n minimum = nums[i];\n index = i;\n }\n }\n return index;\n }\n}\n\n``` | 2 | 0 | ['Array', 'Math', 'Java'] | 0 |
final-array-state-after-k-multiplication-operations-i | ✅Simple Brute force, two loop, ⭐Beats 100%✅ ⭐Java solution⭐✅ | simple-brute-force-two-loop-beats-100-ja-sr58 | IntuitionI applied brute force approach, (first loop) we need to run operation k times, (second loop) In each operation we need to find minimun(x) and then repl | bhaskarindiapandey | NORMAL | 2024-12-16T12:23:42.811666+00:00 | 2024-12-16T12:23:42.811666+00:00 | 11 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nI applied brute force approach, (first loop) we need to run operation k times, (second loop) In each operation we need to find minimun(x) and then replace that one with (x*multiplier).\n# Approach\n<!-- Describe your approach to solving the problem. -->\nBrute Force approach\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(Kn)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n\n# Code\n```java []\nclass Solution {\n public int[] getFinalState(int[] nums, int k, int multiplier) {\n for(int i=0;i<k;i++){\n int min=nums[0];\n int minIndex=0;\n for(int j=1;j<nums.length;j++){\n if(nums[j]<min){\n min=nums[j];\n minIndex=j;\n }\n }\n nums[minIndex]=min*multiplier;\n }\n return nums;\n }\n}\n``` | 2 | 0 | ['Java'] | 0 |
final-array-state-after-k-multiplication-operations-i | Easy Priority Queue Solution 🚀🏆 | easy-priority-queue-solution-by-sanchitb-a5ir | IntuitionWe need to perform k operations on an integer array. In each operation, we identify the smallest value, multiply it by a given multiplier, and then rep | sanchitbajaj02 | NORMAL | 2024-12-16T11:13:42.834706+00:00 | 2024-12-16T11:13:42.834706+00:00 | 78 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe need to perform `k` operations on an integer array. In each operation, we identify the smallest value, multiply it by a given `multiplier`, and then replace the original value with the new one. The main challenge is to efficiently track and update the smallest element in the array.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. We initialize a min heap (priority queue) with a composite key as priority.\n2. We insert all the values of interger array `nums` in a pair of <br> `[nums[idx], idx]`.\n3. Now perform the while loop till `k` times and get the minimum pair from min heap: `[num, idx]`.\n4. Update the integer array `nums` on index `idx` that we get from priority queue and multiply it with the `multiplier` given.\n5. Now re insert the `nums[i]` along with `idx` into the min heap.\n6. In The end, return the `nums` array as answer.\n\n# My solution performance\n\nThe solution is not fast and efficient but it shows a way to implement priority queue in javascript\n\n\n\n# Complexity\n- Time complexity: $$O(k * Log(n))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```javascript []\n/**\n * @param {number[]} nums\n * @param {number} k\n * @param {number} multiplier\n * @return {number[]}\n */\nvar getFinalState = function (nums, k, multiplier) {\n let heap = new MinPriorityQueue({\n priority: ([num, index]) => {\n return num * nums.length + index; // composite key\n }\n });\n\n // Initialize the heap\n nums.forEach((num, idx) => {\n heap.enqueue([num, idx]);\n })\n\n // Process k iterations\n while (k--) {\n let [num, idx] = heap.dequeue().element;\n nums[idx] *= multiplier;\n heap.enqueue([nums[idx], idx]); // Reinsert updated value\n }\n return nums;\n};\n``` | 2 | 0 | ['Heap (Priority Queue)', 'Simulation', 'JavaScript'] | 0 |
final-array-state-after-k-multiplication-operations-i | Swift | Simple | swift-simple-by-rokimkar-vpop | ApproachSort the nums array keeping indices location intact. pick the first number from the array(it will be lowest always and index does not matter), now multi | rokimkar | NORMAL | 2024-12-16T09:37:30.364589+00:00 | 2024-12-16T09:37:30.364589+00:00 | 39 | false | # Approach\nSort the nums array keeping indices location intact. pick the first number from the array(it will be lowest always and index does not matter), now multiply the number with multiplier, delete the number from array and insert it back in the array based on value(binary searh) if multiplied value already exists then maintain the order.\n\n# Complexity\n- Time complexity:\nO(NlogN + klogN)\n\n# Code\n```swift []\nimport Algorithms\nclass Solution {\n func getFinalState(_ nums: [Int], _ k: Int, _ multiplier: Int) -> [Int] {\n var sortedNums = nums.enumerated().map{($0.1,$0.0)}.sorted{$0.0 < $1.0}\n var count = 0\n while count < k {\n var first = sortedNums.first!\n sortedNums.removeFirst()\n first.0 = first.0 * multiplier\n let p = sortedNums.partitioningIndex(where: {($0.0 == first.0 && first.1 < $0.1) || $0.0 > first.0})\n sortedNums.insert(first, at: p)\n print(sortedNums)\n count += 1\n }\n return sortedNums.sorted{$0.1 < $1.1}.map(\\.0)\n }\n}\n``` | 2 | 0 | ['Swift'] | 1 |
final-array-state-after-k-multiplication-operations-i | C++ || Priority Queue || Easy Approach | c-priority-queue-easy-approach-by-that_1-t9bu | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | that_1guy__ | NORMAL | 2024-12-16T09:23:17.037852+00:00 | 2024-12-16T09:23:17.037852+00:00 | 60 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n#define P pair<int,int>\n vector<int> getFinalState(vector<int>& nums, int k, int multiplier) {\n priority_queue<P,vector<P>,greater<P>>pq;\n vector<int>ans(nums.size(),0);\n for(int i = 0;i<nums.size();i++){\n pq.push({nums[i],i});\n }\n while(k>0){\n auto n = pq.top();\n pq.pop();\n n.first*=multiplier;\n pq.push({n.first,n.second});\n k--;\n }\n \n while(!pq.empty()){\n auto n = pq.top();\n int idx= n.second;\n int ele= n.first;\n ans[idx]=ele;\n pq.pop();\n }\n return ans;\n }\n};\n``` | 2 | 0 | ['Array', 'Math', 'Heap (Priority Queue)', 'Simulation', 'C++'] | 1 |
final-array-state-after-k-multiplication-operations-i | Beats 100% of users runtime | beats-100-of-users-runtime-by-dev_bhatt2-46np | Complexity
Time complexity:O(N) | dev_bhatt202 | NORMAL | 2024-12-16T08:44:02.086129+00:00 | 2024-12-16T08:44:02.086129+00:00 | 13 | false | # Complexity\n- Time complexity:O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n```java []\nclass Solution {\n public int[] getFinalState(int[] nums, int k, int multiplier) {\n int[] arr = new int[2];\n\n for (int i = 0; i < k; i++) {\n arr = getMin(nums);\n nums[arr[1]] = arr[0] * multiplier;\n }\n\n return nums;\n }\n\n private int[] getMin(int[] nums) {\n int min = Integer.MAX_VALUE;\n int idx = 0;\n\n for (int i = 0; i < nums.length; i++)\n if (nums[i] < min) {\n min = nums[i];\n idx = i;\n }\n\n return new int[] { min, idx };\n }\n\n}\n``` | 2 | 0 | ['Array', 'Math', 'Heap (Priority Queue)', 'Simulation', 'Java'] | 1 |
final-array-state-after-k-multiplication-operations-i | 0 ms BEATS 100% || EASY 3 LINES OF CODE | 0-ms-beats-100-easy-3-lines-of-code-by-d-btwn | Code | deepakk2510 | NORMAL | 2024-12-16T08:23:35.836946+00:00 | 2024-12-16T08:23:35.836946+00:00 | 68 | false | \n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<int> getFinalState(vector<int>& nums, int k, int multiplier) {\n while(k--){\n auto min_itr = min_element(nums.begin(),nums.end());\n *min_itr = (*min_itr)*multiplier;\n }\n return nums;\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
final-array-state-after-k-multiplication-operations-i | Beats 100% Easy Approach 🔥 | beats-100-easy-approach-by-anushka_011-e06g | IntuitionThe task is to repeatedly update the smallest element in the array by multiplying it with a given multiplier. After k operations, return the final stat | Anushka_011 | NORMAL | 2024-12-16T08:18:36.911024+00:00 | 2024-12-16T08:18:36.911024+00:00 | 69 | false | # Intuition\nThe task is to repeatedly update the smallest element in the array by multiplying it with a given multiplier. After k operations, return the final state of the array.\n\n# Approach\nFor each of the k operations:\n- Find the smallest element in the array using min_element.\n- Update the first occurrence of the smallest element by multiplying it with multiplier.\n- Return the updated array after all operations.\n\n# Complexity\n- Time complexity: O(k\u22C5n)\nFinding the smallest element and updating it each take \n\uD835\uDC42(\uD835\uDC5B), repeated \uD835\uDC58 times.\n\n- Space complexity: O(1)\n\n\n\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<int> getFinalState(vector<int>& nums, int k, int multiplier) {\n vector<int>ans;\n while(k--){\n int mini=*min_element(nums.begin(),nums.end());\n for(int i=0;i<nums.size();i++){\n if(nums[i]==mini){\n nums[i]=multiplier*mini;\n break;\n }\n }\n }\n return nums;\n \n }\n};\n``` | 2 | 0 | ['Array', 'C++'] | 0 |
final-array-state-after-k-multiplication-operations-i | Java Solution | java-solution-by-ruch21-0rgz | Code | ruch21 | NORMAL | 2024-12-16T08:04:21.745043+00:00 | 2024-12-16T08:04:39.258628+00:00 | 163 | false | \n# Code\n```java []\nclass Solution {\n class Node implements Comparable<Node> {\n int num;\n int idx;\n public Node(int num, int idx) {\n this.num = num;\n this.idx = idx;\n }\n @Override\n public int compareTo(Node n) {\n if(this.num == n.num) {\n return this.idx - n.idx;\n }\n else {\n return this.num - n.num;\n }\n }\n }\n public int[] getFinalState(int[] nums, int k, int multiplier) {\n int ans[] = new int[nums.length];\n\n PriorityQueue<Node> pq = new PriorityQueue<>();\n for(int i=0; i<nums.length; i++) {\n pq.add(new Node(nums[i], i));\n ans[i] = nums[i];\n }\n for(int i=0; i<k; i++) {\n Node n = pq.poll();\n pq.add(new Node(n.num * multiplier, n.idx));\n ans[n.idx] = n.num * multiplier;\n }\n\n return ans;\n }\n}\n``` | 2 | 0 | ['Java'] | 1 |
final-array-state-after-k-multiplication-operations-i | 🔥SIMPILL💯 % 🎯 |✨SUPER EASY BEGINNERS 👏 | simpill-super-easy-beginners-by-codewith-hsyg | IntuitionThe problem revolves around performing k operations on an array to modify the smallest element each time. Each modification multiplies the smallest ele | CodeWithSparsh | NORMAL | 2024-12-16T06:56:12.623007+00:00 | 2024-12-16T07:04:58.128115+00:00 | 312 | false | \n\n\n\n---\n\n# Intuition\nThe problem revolves around performing `k` operations on an array to modify the smallest element each time. Each modification multiplies the smallest element by a given multiplier. The key insight is to repeatedly find the smallest element, update it, and return the modified array.\n\n---\n\n# Approach\n1. Loop `k` times.\n2. For each iteration, find the index of the smallest element in the array.\n3. Multiply the smallest element by the given `multiplier`.\n4. Replace the smallest element with the updated value in the array.\n5. Return the modified array.\n\n---\n\n# Complexity\n- **Time Complexity**: \n Finding the smallest element in the array takes \\(O(n)\\), and performing it \\(k\\) times results in a total time complexity of \\(O(k \\times n)\\).\n\n- **Space Complexity**: \n The space complexity is \\(O(1)\\), as we modify the array in place and use only a few auxiliary variables.\n\n---\n\n\n```dart []\nclass Solution {\n List<int> getFinalState(List<int> nums, int k, int multiplier) {\n for (; k > 0; k--) {\n int i = getIndex(nums);\n nums[i] = nums[i] * multiplier;\n }\n return nums;\n }\n\n int getIndex(List<int> array) {\n int min = 999999;\n int index = 0;\n for (int i = 0; i < array.length; i++) {\n if (min > array[i]) {\n min = array[i];\n index = i;\n }\n }\n return index;\n }\n}\n```\n\n\n```python []\nclass Solution:\n def getFinalState(self, nums, k, multiplier):\n for _ in range(k):\n i = self.get_index(nums)\n nums[i] *= multiplier\n return nums\n\n def get_index(self, array):\n min_val = float(\'inf\')\n index = 0\n for i in range(len(array)):\n if array[i] < min_val:\n min_val = array[i]\n index = i\n return index\n```\n\n\n```cpp []\n#include <vector>\n#include <limits>\nusing namespace std;\n\nclass Solution {\npublic:\n vector<int> getFinalState(vector<int>& nums, int k, int multiplier) {\n while (k-- > 0) {\n int i = getIndex(nums);\n nums[i] *= multiplier;\n }\n return nums;\n }\n\nprivate:\n int getIndex(vector<int>& array) {\n int minVal = INT_MAX;\n int index = 0;\n for (int i = 0; i < array.size(); i++) {\n if (array[i] < minVal) {\n minVal = array[i];\n index = i;\n }\n }\n return index;\n }\n};\n```\n\n\n```java []\nimport java.util.*;\n\nclass Solution {\n public int[] getFinalState(int[] nums, int k, int multiplier) {\n for (int i = 0; i < k; i++) {\n int index = getIndex(nums);\n nums[index] *= multiplier;\n }\n return nums;\n }\n\n private int getIndex(int[] array) {\n int min = Integer.MAX_VALUE;\n int index = 0;\n for (int i = 0; i < array.length; i++) {\n if (array[i] < min) {\n min = array[i];\n index = i;\n }\n }\n return index;\n }\n}\n```\n\n\n```javascript []\nclass Solution {\n getFinalState(nums, k, multiplier) {\n while (k-- > 0) {\n let index = this.getIndex(nums);\n nums[index] *= multiplier;\n }\n return nums;\n }\n\n getIndex(array) {\n let min = Infinity;\n let index = 0;\n for (let i = 0; i < array.length; i++) {\n if (array[i] < min) {\n min = array[i];\n index = i;\n }\n }\n return index;\n }\n}\n```\n\n\n```go []\npackage main\n\nfunc getFinalState(nums []int, k int, multiplier int) []int {\n\tfor ; k > 0; k-- {\n\t\tindex := getIndex(nums)\n\t\tnums[index] *= multiplier\n\t}\n\treturn nums\n}\n\nfunc getIndex(array []int) int {\n\tmin := int(^uint(0) >> 1) // Max int value\n\tindex := 0\n\tfor i, val := range array {\n\t\tif val < min {\n\t\t\tmin = val\n\t\t\tindex = i\n\t\t}\n\t}\n\treturn index\n}\n```\n\n---\n\n {:style=\'width:250px\'} | 2 | 0 | ['Array', 'Math', 'C', 'Heap (Priority Queue)', 'C++', 'Java', 'Go', 'Python3', 'JavaScript', 'Dart'] | 1 |
final-array-state-after-k-multiplication-operations-i | Beats 100% of user with C++ | beats-100-of-user-with-c-by-sahilsaw-1lam | IntuitionThe problem involves repeatedly applying a transformation to the smallest element in the array and tracking its position. This suggests using a data st | SahilSaw | NORMAL | 2024-12-16T06:47:50.956419+00:00 | 2024-12-16T06:47:50.956419+00:00 | 17 | false | # Intuition\nThe problem involves repeatedly applying a transformation to the smallest element in the array and tracking its position. This suggests using a data structure that efficiently retrieves and updates the smallest elements, such as a priority queue (min-heap). By keeping track of indices, we ensure the correct elements are updated without modifying the heap structure unnecessarily.\n\n# Approach\n1. Use a priority queue (min-heap) to store pairs of numbers and their indices from the input array `nums`.\n2. Initialize the heap by pushing all elements along with their indices into it.\n3. Perform the following operations `k` times or until the heap is empty:\n - Extract the smallest element from the heap.\n - Multiply the value of the extracted element by the `multiplier`.\n - Update the corresponding element in the `nums` array.\n - Push the updated element back into the heap with its index.\n4. Return the updated `nums` array after all transformations.\n\n# Complexity\n- Time complexity:\n - Building the heap takes $$O(n \\log n)$$, where $$n$$ is the size of the array.\n - Each of the `k` operations involves a pop and a push operation, each taking $$O(\\log n)$$.\n - Overall, the time complexity is $$O(n \\log n + k \\log n)$$.\n\n- Space complexity:\n - The priority queue stores up to $$n$$ elements, so the space complexity is $$O(n)$$.\n\n# Code\n```cpp\nclass Solution {\npublic:\n vector<int> getFinalState(vector<int>& nums, int k, int multiplier) {\n priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>> pq;\n for(int i=0;i<nums.size();i++)\n {\n int it=nums[i];\n pq.push({it,i});\n }\n while(!pq.empty()&&k--)\n {\n auto[val,ind]=pq.top();\n pq.pop();\n pq.push({val*multiplier,ind});\n nums[ind]*=multiplier;\n }\n return nums;\n }\n};\n```\n | 2 | 0 | ['C++'] | 0 |
final-array-state-after-k-multiplication-operations-i | 100% acceptance | 2 methods | using loops | heaps | 100-acceptance-2-methods-using-loops-hea-rvb4 | we can go to the array k times and for each time we will calculate the minimum value as well as its index in the array
that minimum index is then updated with t | Shyyshawarma | NORMAL | 2024-12-16T05:51:44.711658+00:00 | 2024-12-16T05:51:44.711658+00:00 | 83 | false | <!-- # Intuition -->\n\n\nwe can go to the array k times and for each time we will calculate the minimum value as well as its index in the array\nthat minimum index is then updated with the new value\n\n\n\n\nor\n\nuse heaps\nas we want a minimum value we will use a heap so that the small number as well as the small indices are present at the top.\nthe value at top is taken and changes are made at the corressponding indices.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n<!-- # Approach -->\n<!-- Describe your approach to solving the problem. -->\n\n<!-- # Complexity\n- Time complexity: -->\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n<!-- - Space complexity: -->\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<int> getFinalState(vector<int>& nums, int k, int multiplier) {\n priority_queue<pair<int,int>,vector<pair<int,int>>,greater<>> heap;\n for(int i=0;i<nums.size();i++){\n heap.push({nums[i],i});\n } \n for(int i=0;i<k;i++){\n auto [val,ind]=heap.top();\n heap.pop();\n nums[ind]=nums[ind]*multiplier;\n heap.push({nums[ind],ind});\n } \n return nums;\n }\n};\n``` | 2 | 0 | ['C++'] | 1 |
final-array-state-after-k-multiplication-operations-i | 🚀 Efficient Solution using nested loop🌟 | efficient-solution-using-nested-loop-by-waw3n | IntuitionThe problem requires us to modify an array k times by repeatedly multiplying the smallest element by a given multiplier. Each operation seeks the curre | shoaibkhalid65 | NORMAL | 2024-12-16T04:10:44.946898+00:00 | 2024-12-16T04:10:44.946898+00:00 | 167 | false | # Intuition\nThe problem requires us to modify an array k times by repeatedly multiplying the smallest element by a given multiplier. Each operation seeks the current minimum, modifies it, and updates the array. This leads to an iterative optimization of the array values.\n\n# Approach\nInitialization:\nStart with the array nums and perform k iterations to modify the smallest element.\nFind the Minimum:\nIn each iteration, traverse the array to locate the index of the smallest element.\nModify the Minimum:\nOnce the smallest element is found, multiply it by the multiplier and update the array at that index.\nRepeat:\nPerform the above steps for k iterations to complete the transformation.\nReturn the Result:\nAfter processing, return the modified array.\n\n# Complexity\n- Time complexity:\nO(n \xD7 k)\n\n- Space complexity:\n O(1)\n\n\n# Code\n```java []\nclass Solution {\n public int[] getFinalState(int[] nums, int k, int multiplier) {\n int minIndex=0;\n for(int i=0;i<k;i++){\n minIndex=0;\n for(int j=0;j<nums.length;j++){\n if(nums[j]<nums[minIndex]){\n minIndex=j;\n }\n }\n nums[minIndex]=nums[minIndex]*multiplier;\n }\n return nums;\n }\n}\n``` | 2 | 0 | ['Java'] | 1 |
final-array-state-after-k-multiplication-operations-i | C# Solution for Find Array State After K Multiplication Operations I Problem | c-solution-for-find-array-state-after-k-7p3sr | IntuitionThe problem involves performing k operations where the smallest element in the array is updated. Instead of scanning the array repeatedly to find the m | Aman_Raj_Sinha | NORMAL | 2024-12-16T04:02:10.132093+00:00 | 2024-12-16T04:02:10.132093+00:00 | 77 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem involves performing k operations where the smallest element in the array is updated. Instead of scanning the array repeatedly to find the minimum, the intuition behind this solution is to use a priority queue (min-heap) to:\n1.\tEfficiently track the smallest element.\n2.\tUpdate and reinsert it into the heap after each operation.\n\nThis avoids redundant linear scans for the minimum element in every operation, making the process more efficient. The heap structure maintains the smallest element at the top, ensuring O(log n) complexity for insertion and extraction.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1.\tMin-Heap Initialization:\n\t\u2022\tStore each element of the array as a tuple (value, index) in a SortedSet (acting as a min-heap).\n\t\u2022\tThis ensures that elements are sorted by their value, and the smallest value can be accessed efficiently.\n2.\tPerform k Operations:\n\t\u2022\tExtract the smallest element from the heap (based on value).\n\t\u2022\tUpdate its value by multiplying it with the multiplier.\n\t\u2022\tUpdate the corresponding index in the array.\n\t\u2022\tInsert the updated value and its index back into the heap to maintain the sorted structure.\n3.\tReturn the Result:\n\t\u2022\tAfter k operations, the nums array contains the final state.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n1.\tHeap Initialization:\n\t\u2022\tConstructing the heap initially involves adding n elements to the SortedSet, which takes O(n log n).\n2.\tPerform k Operations:\n\t\u2022\tEach operation involves:\n\t\u2022\tExtracting the smallest element from the heap: O(log n).\n\t\u2022\tReinserting the updated value into the heap: O(log n).\n\t\u2022\tFor k operations, this takes O(k log n).\n3.\tTotal Time Complexity: O(n log n + k log n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\u2022\tThe SortedSet stores n elements, requiring O(n) space.\n\u2022\tOther auxiliary variables (e.g., tuples) use O(1) space.\n\u2022\tTotal Space Complexity: O(n)\n\n# Code\n```csharp []\npublic class Solution {\n public int[] GetFinalState(int[] nums, int k, int multiplier) {\n var minHeap = new SortedSet<(int value, int index)>();\n for (int i = 0; i < nums.Length; i++) {\n minHeap.Add((nums[i], i));\n }\n for (int i = 0; i < k; i++) {\n var minElement = minHeap.Min;\n minHeap.Remove(minElement);\n\n int updatedValue = minElement.value * multiplier;\n nums[minElement.index] = updatedValue;\n\n minHeap.Add((updatedValue, minElement.index));\n }\n return nums;\n }\n}\n``` | 2 | 0 | ['C#'] | 0 |
final-array-state-after-k-multiplication-operations-i | Heap vs. Peep: The Battle of Brains vs. Brawn in Multiplying the Smallest! | 2 Solutions | heap-vs-peep-the-battle-of-brains-vs-bra-3u7h | IntuitionThe problem involves repeatedly multiplying the smallest element of an array by a given multiplier k times. The goal is to efficiently determine the fi | ParthSaini1353 | NORMAL | 2024-12-16T04:00:56.566712+00:00 | 2024-12-16T04:00:56.566712+00:00 | 23 | false | # Intuition\nThe problem involves repeatedly multiplying the smallest element of an array by a given multiplier k times. The goal is to efficiently determine the final state of the array.\n\nKey observation: At each step, the smallest element in the array needs to be identified and updated.\nOptimization trade-off: The task can be solved using a priority queue (min-heap) for faster access to the smallest element, or by directly scanning the array in each iteration for a more memory-efficient solution.\n\n# Approach\n# **Approach 1: Using a Min-Heap (Priority Queue)**\nSteps:\nUse a min-heap to efficiently track the smallest element in the array.\nInsert all elements of the array into the heap, storing each element with its index for traceability.\nPerform k operations:\nExtract the smallest element.\nMultiply it by the given multiplier.\nReinsert the updated element back into the heap.\nAfter k updates, reconstruct the modified array from the heap\n\n\n# **Approach 2: Direct Iteration**\nSteps:\nPerform \n\uD835\uDC58\nk iterations:\nFind the smallest element in the array by scanning through it.\nUpdate this element by multiplying it with the multiplier.\nContinue until all \n\uD835\uDC58\nk operations are complete.\nReturn the modified array.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\n// //SPACE O(N)\n// // TIME O(n*log(n))\n// class Solution {\n// public:\n// vector<int> getFinalState(vector<int>& nums, int k, int multiplier) \n// {\n// priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;\n// for(auto it=0;it<nums.size();it++)\n// {\n// pq.push({nums[it],it});\n// }\n// for(int i=0;i<k;i++)\n// {\n// auto less=pq.top();\n// int nu=less.first;\n// int index=less.second;\n// pq.pop();\n// int multi=nu*multiplier;\n// pq.push({multi,index});\n// }\n// vector<int>ans(nums.size());\n// while(!pq.empty())\n// {\n// auto curr = pq.top();\n// ans[curr.second] = curr.first;\n// pq.pop();\n// }\n// return ans;\n\n\n// }\n// };\n\n\n\n\n\n\n//SPACE O(1)\n// TIME O(k*n)\n\nclass Solution {\npublic:\n vector<int> getFinalState(vector<int>& nums, int k, int multiplier) {\n int n = nums.size();\n \n for (int i = 0; i < k; i++)\n {\n \n int mini = 0;\n for (int j = 1; j < n; j++) \n {\n if (nums[j] < nums[mini])\n {\n mini = j;\n }\n }\n \n \n nums[mini] =nums[mini]* multiplier;\n }\n \n return nums;\n }\n};\n\n\n\n\n\nauto init = []() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n cout.tie(nullptr);\n return \'c\';\n}();\n``` | 2 | 0 | ['C++'] | 0 |
final-array-state-after-k-multiplication-operations-i | ✅Final Array State After K Multiplication Operations I - Simple Java Solution | Beats 100%✅ | final-array-state-after-k-multiplication-ohs9 | Intuition 💡The problem asks us to perform a series of operations on an array. In each operation, we find the smallest number, multiply it by a given multiplier, | Ram4366 | NORMAL | 2024-12-16T03:51:55.796216+00:00 | 2024-12-16T03:51:55.796216+00:00 | 26 | false | # Intuition \uD83D\uDCA1\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem asks us to perform a series of operations on an array. In each operation, we find the smallest number, multiply it by a given multiplier, and replace the number in the array. We repeat this process k times.\n\nTo solve this efficiently, we need to:\n\n1. Identify the minimum number in the array each time.\n2. Replace it with its multiplied value.\n3. Continue for k operations.\n\n\n# Approach \uD83E\uDDE0\n<!-- Describe your approach to solving the problem. -->\n\n---\n\n\n1. First Code Approach:\n\n For each of the k operations:\n\n- We find the smallest element in the array (this is done by scanning through the array).\n- Once we find it, we multiply it by the multiplier and update the array.\n- Repeat the process k times.\n\nThis is a straightforward approach but can be a bit slow if the array is large because finding the minimum in each iteration takes O(n) time.\n\n---\n\n\n2. Second Code Approach:\n\n- We use a priority queue (min-heap) to make finding the smallest element faster.\n- First, we put all elements into the heap.\n- For each of the k operations, we pull out the smallest element, multiply it by the multiplier, and push it back into the heap.\n- After each operation, we update the original array where the element changed.\n\nThis approach makes finding the smallest element faster but still requires updating the array after each operation.\n\n# Complexity\n## Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n- First code: In each of the k operations, we scan the whole array to find the minimum element, so the total time complexity is $$O(k * n)$$.\n- Second code: Using a heap makes the time complexity $$O(k * log n)$$ for each operation, but since we also update the original array with $$O(n)$$ for each operation, the overall complexity is $$O(k * log n + k * n)$$.\n\n## Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n- Both approaches use a constant amount of extra space i.e $$O(1)$$ for the first approach and $$O(n)$$ for the second due to the heap.\n\n# Code :\n## First Code\n```java []\nclass Solution {\n public int[] getFinalState(int[] nums, int k, int multiplier) {\n for(int i=0;i<k;i++){\n nums[minIdx(nums)] *= multiplier;\n }\n return nums;\n }\n\n public int minIdx(int []arr){\n int min = 0;\n for(int i=1;i<arr.length;i++){\n if(arr[i] < arr[min]){\n min = i;\n }\n }\n return min;\n }\n}\n```\n\n---\n\n\n## Second Code\n\n```java []\nclass Solution {\n public int[] getFinalState(int[] nums, int k, int multiplier) {\n PriorityQueue<Integer> queue=new PriorityQueue<>();\n for(int i=0;i<nums.length;i++){\n queue.add(nums[i]);\n }\n for(int i=0;i<k;i++){\n int s=queue.poll();\n int m=s*multiplier;\n queue.add(m);\n\n for(int j=0;j<nums.length;j++){\n if(nums[j]==s){\n nums[j]=m;\n break;\n }\n }\n }\n return nums;\n }\n}\n``` | 2 | 0 | ['Array', 'Math', 'Heap (Priority Queue)', 'Simulation', 'Java'] | 0 |
final-array-state-after-k-multiplication-operations-i | (8ms) PriorityQueue(PairComparator) | 8ms-priorityqueuepaircomparator-by-sav20-xe52 | ApproachPriorityQueue(PairComparator)ComplexityCodeAnd this is just an interesting option: | sav20011962 | NORMAL | 2024-12-16T03:29:26.211108+00:00 | 2024-12-16T06:02:45.066061+00:00 | 48 | false | # Approach\nPriorityQueue(PairComparator)\n# Complexity\n\n# Code\n```kotlin []\nclass Solution {\n object PairComparator : Comparator<Pair<Int,Int>> {\n override fun compare(a: Pair<Int,Int>, b: Pair<Int,Int>): Int = if(a.first==b.first) a.second-b.second else a.first-b.first\n }\n fun getFinalState(nums: IntArray, k: Int, multiplier: Int): IntArray {\n val pq_asc = PriorityQueue(PairComparator) \n val len = nums.size\n for (i in 0 until len) {\n pq_asc.add(Pair(nums[i],i))\n }\n for (i in 0 until k) {\n val pair = pq_asc.poll()\n pq_asc.add(Pair(pair.first*multiplier,pair.second))\n }\n for (i in 0 until len) {\n val (zn,ind) = pq_asc.poll()\n nums[ind] = zn\n }\n return nums\n }\n}\n```\n# And this is just an interesting option:\n```\nclass Solution {\n fun getFinalState(nums: IntArray, k: Int, multiplier: Int): IntArray {\n val pq_asc = PriorityQueue<Int>(compareBy ({ nums[it] },{ it }))\n val len = nums.size\n for (i in 0 until len) {\n pq_asc.add(i)\n }\n for (i in 0 until k) {\n val ind = pq_asc.poll()\n nums[ind] = nums[ind] * multiplier\n pq_asc.add(ind)\n }\n return nums\n }\n}\n``` | 2 | 0 | ['Kotlin'] | 1 |
final-array-state-after-k-multiplication-operations-i | C#: Min Heap Approach | c-min-heap-approach-by-niteeshyarra-ad30 | IntuitionAs this question is asking to work with the mininum element each time after an operation is done, think of how you can obtain a minimum element efficen | niteeshyarra | NORMAL | 2024-12-16T01:57:55.179982+00:00 | 2024-12-16T01:57:55.179982+00:00 | 146 | false | # Intuition\nAs this question is asking to work with the mininum element each time after an operation is done, think of how you can obtain a minimum element efficently. Sorting the array? Works!! you sort the array after each operation. you sort the array k time and you will have k * n log n\n\nEven efficient way is to use a heap where you can remove and insert element in log n time and you do it k times its going to be k * log n time compexity\n\n# Approach\nUse a priority queue to maintain the decreasing order of the elements. If elements tie, check based on the index. \n\nEnqueue all the indexes in the priority queue and element, index as priority \n\nDequeue the priority queue K times, Each time updated the origin array with the multiplier. Then enqueue the updated index again\n\nFinally return the original array \n\n# Complexity\n- Time complexity: n + k log n \n\n- Space complexity: n\n\n# Code\n```csharp []\npublic class Solution {\n public int[] GetFinalState(int[] nums, int k, int multiplier) {\n var minHeap = new PriorityQueue<int, (int, int)>(Comparer<(int, int)>.Create((a, b) => {\n if(a.Item1 == b.Item1)\n return a.Item2.CompareTo(b.Item2);\n return a.Item1.CompareTo(b.Item1);\n }));\n\n for(int i = 0; i < nums.Length; i++){\n minHeap.Enqueue(i, (nums[i], i));\n }\n\n while(k > 0){\n var top = minHeap.Dequeue();\n nums[top] = nums[top]*multiplier;\n minHeap.Enqueue(top, (nums[top], top));\n k--;\n }\n\n return nums;\n }\n}\n``` | 2 | 0 | ['C#'] | 2 |
final-array-state-after-k-multiplication-operations-i | One-Line Solution | Beats 100% | C++ | one-line-solution-beats-100-c-by-benjami-9wx0 | IntuitionModify the smallest element in the array k times using the multiplier.ApproachRepeatedly use min_element to find and update the smallest element in the | benjami4n | NORMAL | 2024-12-16T01:29:17.887344+00:00 | 2024-12-16T01:29:17.887344+00:00 | 274 | false | \n\n\n# Intuition\nModify the smallest element in the array `k` times using the multiplier.\n\n# Approach\nRepeatedly use `min_element` to find and update the smallest element in the array `k` times, directly modifying the input.\n\n# Complexity\n- Time complexity: O(k * n) (finding the minimum takes O(n), repeated k times).\n- Space complexity: O(1) (in-place updates).\n\n\n\n\n\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<int> getFinalState(vector<int>& nums, int k, int multiplier) {\n while(k--) *min_element(begin(nums), end(nums)) *= multiplier;\n return nums;\n }\n};\n```\n\n\n\n\n | 2 | 0 | ['C++'] | 0 |
final-array-state-after-k-multiplication-operations-i | Easy Heap | easy-heap-by-mechan0-393j | Complexity
Time complexity:
O(nlogn)
Space complexity:
O(n)
Code | mechan0 | NORMAL | 2024-12-16T00:50:21.062665+00:00 | 2024-12-16T00:50:21.062665+00:00 | 110 | false | # Complexity\n- Time complexity:\nO(nlogn)\n\n- Space complexity:\nO(n)\n\n# Code\n```swift []\nimport Collections\nclass Solution {\n struct Entry: Comparable {\n let val: Int\n let index: Int\n public static func < (lhs: Entry, rhs: Entry) -> Bool {\n return lhs.val == rhs.val ? lhs.index < rhs.index : lhs.val < rhs.val\n }\n }\n func getFinalState(_ nums: [Int], _ k: Int, _ multiplier: Int) -> [Int] {\n var heap = Heap<Entry>(nums.enumerated().map{ Entry(val: $1, index: $0)})\n for i in 0..<k {\n let min = heap.min!\n heap.replaceMin(with: Entry(val: min.val * multiplier, index: min.index))\n }\n return heap.unordered.sorted { $0.index < $1.index }.map{$0.val}\n }\n}\n``` | 2 | 0 | ['Swift', 'Heap (Priority Queue)'] | 2 |
final-array-state-after-k-multiplication-operations-i | Simple brute force Rust solution in 4 lines. Time O(n*k), space O(1). | simple-brute-force-rust-solution-in-4-li-0jor | Approach\nBecause the array is at most 100 elements long it is very fast to find the smallest element each time we perform the operation by doing a linear searc | JSorngard | NORMAL | 2024-11-19T14:33:41.051384+00:00 | 2024-11-19T14:33:41.051419+00:00 | 62 | false | # Approach\nBecause the array is at most 100 elements long it is very fast to find the smallest element each time we perform the operation by doing a linear search.\n\n# Complexity\n- Time complexity: O(n*k)\n\n- Space complexity: O(1)\n\n# Code\n```rust []\nimpl Solution {\n pub fn get_final_state(mut nums: Vec<i32>, k: i32, multiplier: i32) -> Vec<i32> {\n for _ in 0..k {\n // Find the smallest number with a linear search\n // and multiply it by the given multiplier\n *nums.iter_mut().min().unwrap() *= multiplier;\n }\n nums\n }\n}\n``` | 2 | 0 | ['Simulation', 'Rust'] | 0 |
final-array-state-after-k-multiplication-operations-i | Solution with explanation | solution-with-explanation-by-ravi_ksk-66rg | Intuition\n1. We need to maintain the elements of the array in sorted order with their indexes. \na. For this we can use PriorityQueue\nb. Custom compare functi | ravi_ksk | NORMAL | 2024-08-25T06:58:42.819831+00:00 | 2024-08-25T06:58:42.819858+00:00 | 332 | false | # Intuition\n1. We need to maintain the elements of the array in sorted order with their indexes. \na. For this we can use PriorityQueue\nb. Custom compare function to compare element value and their index if they are equal.\n\n```\n [1, 1]\n / \\\n [2, 0] [3, 2]\n / \\\n[5, 3] [6, 4]\n```\n# Approach\n1. Put all the element into the Priority Queue with their index like [value, index]\n2. Loop over the element K time as we need to perform K operation\n3. Extract the element from the Priority Queue\n4. Update the element in the ogirinal array nums by multiplying with multiplier\n5. Update the Priority Queue with updated value\n\n# Complexity\n- Time complexity:\nO(nlogn)\n\n\n- Space complexity:\nO(n)\n\n# Code\n```java []\nclass Solution {\n public int[] getFinalState(int[] nums, int k, int multiplier) {\n PriorityQueue<int[]> pq = new PriorityQueue<>(new Comparator<int[]>() {\n public int compare(int[] a, int[] b) {\n if(a[0] == b[0])\n return a[1] - b[1];\n return a[0] - b[0];\n } \n }); \n for(int i=0; i<nums.length; i++)\n pq.add(new int[]{nums[i], i});\n \n for(int i=0;i<k;i++) {\n int[] val = pq.poll();\n nums[val[1]] *= multiplier;\n val[0] = nums[val[1]];\n pq.add(val);\n }\n return nums;\n \n }\n}\n``` | 2 | 0 | ['Java'] | 0 |
final-array-state-after-k-multiplication-operations-i | Easiest Solution With Explanation Javascript, JAVA | easiest-solution-with-explanation-javasc-jxl5 | Intuition\nThe goal is to repeatedly apply an operation on an array nums to achieve the final state. The operation involves finding the smallest number in the a | hashcoderz | NORMAL | 2024-08-25T04:38:48.571990+00:00 | 2024-08-25T04:38:48.572019+00:00 | 347 | false | ## Intuition\nThe goal is to repeatedly apply an operation on an array nums to achieve the final state. The operation involves finding the smallest number in the array and multiplying it by a given multiplier. We need to perform this operation k times.\n\n## Approach\n1. Initialization: Start by iterating while there are operations left (k > 0).\n2. Find Minimum: In each iteration, find the smallest number in the array and its index.\n3. Apply Operation: Multiply the smallest number by the given multiplier.\n4. Update Operations: Decrement the count of remaining operations (k).\n5. Return Result: After all operations are completed, return the modified array.\n## Complexity\n- Time complexity: \n$$O(n\u22C5k)$$ \nFinding the minimum element in the array takes $$O(n)$$.\nThis process is repeated for each of the k operations.\n- Space complexity: \n$$O(1)$$\nThe space complexity is constant as no additional space is used that grows with input size.\n\n# Code\n```typescript []\nfunction getFinalState(nums, k, multiplier) {\n while (k > 0) {\n let min = Number.MAX_VALUE;\n let minIndex = -1;\n\n for (let i = 0; i < nums.length; i++) {\n if (nums[i] < min) {\n min = nums[i];\n minIndex = i;\n }\n }\n\n nums[minIndex] *= multiplier;\n k--;\n }\n\n return nums;\n}\n\n```\n```java []\nclass Solution {\n public int[] getFinalState(int[] nums, int k, int multiplier) {\n while (k > 0) {\n int min = Integer.MAX_VALUE;\n int minIndex = -1;\n\n for (int i = 0; i < nums.length; i++) {\n if (nums[i] < min) {\n min = nums[i];\n minIndex = i;\n }\n }\n\n nums[minIndex] *= multiplier;\n k--;\n }\n return nums;\n }\n}\n```\n\n## If you like the solution then please upvote me. It helps me to motivate....... | 2 | 0 | ['Java', 'TypeScript', 'JavaScript'] | 0 |
final-array-state-after-k-multiplication-operations-i | beats 100% | beats-100-by-shobit000-dww4 | Intuition\n Repeated Minimization: We need to repeatedly find and modify the smallest value in the array. Given that k operations need to be performed, this mea | shobit000 | NORMAL | 2024-08-25T04:21:26.240228+00:00 | 2024-08-25T04:21:26.240245+00:00 | 82 | false | # Intuition\n Repeated Minimization: We need to repeatedly find and modify the smallest value in the array. Given that k operations need to be performed, this means repeatedly updating the smallest element for a specified number of operations.\n\nOrder Preservation: When multiple minimum values are present, the first occurrence should be selected, ensuring the order is preserved as per problem requirements.\n\nModulo Operation: After all operations, applying modulo 10^9+7 helps in managing large numbers and keeping the results within typical integer limits. \n\n# Approach\nPriority Queue: Use a min-heap (priority queue) to efficiently retrieve and update the smallest element.\n\nInsertion and Removal: A priority queue supports efficient extraction of the minimum element.\nUpdate: After finding and updating the minimum element, re-insert it into the heap with its new value.\nArray Tracking: Maintain the original array to ensure that the order of elements is preserved when applying operations.\n\nTrack the indices of elements being updated to ensure correct position handling.\nModulo Application: After performing all operations, iterate through the array and apply the modulo 10^9+7 to each element.\n\n# Complexity\n- Time complexity: O(klogn+n) \n\n- Space complexity: O(n)\n\n# Code\n```java []\npublic class Solution {\n public int[] getFinalState(int[] nums, int k, int multiplier) {\n for (int i = 0; i < k; i++) {\n int minIndex = 0;\n // Find the index of the first minimum value\n for (int j = 1; j < nums.length; j++) {\n if (nums[j] < nums[minIndex]) {\n minIndex = j;\n }\n }\n // Replace the minimum value with its multiplication\n nums[minIndex] *= multiplier;\n }\n return nums;\n }\n\n public static void main(String[] args) {\n Solution solution = new Solution();\n\n // Example 1\n int[] nums1 = {2, 1, 3, 5, 6};\n int k1 = 5;\n int multiplier1 = 2;\n int[] result1 = solution.getFinalState(nums1, k1, multiplier1);\n System.out.println("Output: " + java.util.Arrays.toString(result1));\n\n // Example 2\n int[] nums2 = {1, 2};\n int k2 = 3;\n int multiplier2 = 4;\n int[] result2 = solution.getFinalState(nums2, k2, multiplier2);\n System.out.println("Output: " + java.util.Arrays.toString(result2));\n }\n}\n\n``` | 2 | 0 | ['Java'] | 2 |
final-array-state-after-k-multiplication-operations-i | beats 100% time ans space||SIMPLE SOLUTION FOR BEGINNERS||JAVA,C++,PYTHON | beats-100-time-ans-spacesimple-solution-yqu5u | \n\nTo solve the problem, we need to perform k operations on the array nums, where in each operation, we DO THE FOLOWING :\n\n1. Find the minimum value in nums. | MD__JAKIR1128__ | NORMAL | 2024-08-25T04:13:37.812064+00:00 | 2024-08-25T05:52:35.704328+00:00 | 21 | false | \n\nTo solve the problem, we need to perform `k` operations on the array `nums`, where in each operation, we DO THE FOLOWING :\n\n1. Find the minimum value in `nums`.\n2. Replace the first occurrence of that minimum value with its product by the `multiplier`.\n\nAfter performing all `k` operations, we return the modified array.\n- **Time Complexity:** \\(O(k * n)\\), where \\(n\\) is the length of `nums`. This is because finding the minimum value and its index takes \\(O(n)\\), and we perform this \\(k\\) times.\n \n- **Space Complexity:** \\(O(1)\\) since we are modifying the array in place and using only a few extra variables\n\n**Python:**\n```python\nclass Solution:\n def getFinalState(self, nums: List[int], k: int, multiplier: int) -> List[int]:\n for _ in range(k):\n # Find the index of the first occurrence of the minimum value in nums\n min_index = nums.index(min(nums))\n # Replace the value at min_index with its product by the multiplier\n nums[min_index] *= multiplier\n return nums\n```\n**C++**:\n```\nclass Solution {\npublic:\n std::vector<int> getFinalState(std::vector<int>& nums, int k, int multiplier) {\n const int MOD = 1e9 + 7;\n int n = nums.size();\n for (int op = 0; op < k; ++op) {\n // Find the minimum value and its index\n int minIndex = 0;\n for (int i = 1; i < n; ++i) {\n if (nums[i] < nums[minIndex]) {\n minIndex = i;\n }\n }\n // Replace the minimum value with its multiplied value\n nums[minIndex] *= multiplier;\n }\n // Apply modulo operation\n for (int i = 0; i < n; ++i) {\n nums[i] %= MOD;\n }\n return nums;\n }\n};\n```\n\n**java**:\n```\nclass Solution {\n public int[] getFinalState(int[] nums, int k, int multiplier) {\n final int MOD = 1000000007;\n int n = nums.length;\n for (int op = 0; op < k; ++op) {\n // Find the minimum value and its index\n int minIndex = 0;\n for (int i = 1; i < n; ++i) {\n if (nums[i] < nums[minIndex]) {\n minIndex = i;\n }\n }\n // Replace the minimum value with its multiplied value\n nums[minIndex] *= multiplier;\n }\n // Apply modulo operation\n for (int i = 0; i < n; ++i) {\n nums[i] %= MOD;\n }\n return nums;\n }\n}\n```\n.\n\n | 2 | 0 | [] | 1 |
final-array-state-after-k-multiplication-operations-i | Using inbuilt functin min_function in 0 ms runtime easy C++ solution | using-inbuilt-functin-min_function-in-0-wlllb | Code | sameerrswami | NORMAL | 2025-04-09T17:27:57.275572+00:00 | 2025-04-09T17:27:57.275572+00:00 | 8 | false |
# Code
```cpp []
class Solution {
public:
vector<int> getFinalState(vector<int>& nums, int k, int m) {
for(int i=0;i<k;i++){
int x=*min_element(nums.begin(),nums.end());
for(int &n:nums){
if(n==x){
n*=m;
break;
}
}
}
return nums;
}
};
``` | 1 | 0 | ['C++'] | 0 |
final-array-state-after-k-multiplication-operations-i | Final Array State After K Multiplication Operations I | final-array-state-after-k-multiplication-53p6 | IntuitionApproachComplexity
Time complexity:
O(n2)
Space complexity:
O(1)Code | Vinil07 | NORMAL | 2025-04-01T04:55:51.971317+00:00 | 2025-04-01T04:55:51.971317+00:00 | 37 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
O(n2)
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
O(1)
# Code
```cpp []
class Solution {
public:
vector<int> getFinalState(vector<int>& nums, int k, int multiplier) {
while(k>0){
int mini=*min_element(nums.begin(),nums.end());
for(int &val:nums){
if(val==mini){
val*=multiplier;
break;
}
}
k--;
}
return nums;
}
};
``` | 1 | 0 | ['Array', 'Math', 'Simulation', 'C++'] | 0 |
final-array-state-after-k-multiplication-operations-i | MinHeap | minheap-by-samuel_k276-oxco | Approach
Heap Initialization:
Store each number along with its index as a tuple (value, index).
This helps us maintain order while modifying values.
Proce | Samuel_k276 | NORMAL | 2025-03-31T20:28:35.884416+00:00 | 2025-03-31T20:28:35.884416+00:00 | 23 | false | # Approach
1. Heap Initialization:
- Store each number along with its index as a tuple `(value, index)`.
- This helps us maintain order while modifying values.
2. Processing k Operations:
- Pop the **smallest value** from the heap (since `heapq` implements a min heap).
- Multiply it by `multiplier` and push it back into the heap.
3. Restoring Original Order:
- The heap now contains modified values, but in an **unsorted** order.
- Sort it based on the **original indices** to return the final result.
# Complexity
- Time complexity: $O(max(k, n) log(n))$
- Space complexity: $O(n)$
# Code
```python3 []
class Solution:
def getFinalState(self, nums: List[int], k: int, multiplier: int) -> List[int]:
# Step 1: Create a min heap of (value, index) pairs
heap = [(nums[i], i) for i in range(len(nums))]
heapq.heapify(heap) # Convert list into a min heap (O(n))
# Step 2: Perform k operations
for _ in range(k):
n, i = heapq.heappop(heap) # Remove the smallest element (O(log n))
heapq.heappush(heap, (n * multiplier, i)) # Push updated value back (O(log n))
# Step 3: Restore original order
res = [x[0] for x in sorted(heap, key=lambda x: x[1])] # O(n log n)
return res
``` | 1 | 1 | ['Heap (Priority Queue)', 'Python3'] | 0 |
final-array-state-after-k-multiplication-operations-i | Java Code || Simple Logic || Beats 100% | java-code-simple-logic-beats-100-by-adit-ok7z | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | AdityaRalhan | NORMAL | 2025-03-19T17:22:13.365808+00:00 | 2025-03-19T17:22:13.365808+00:00 | 61 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public int[] getFinalState(int[] nums, int k, int multiplier) {
while(k>0){
int min=Integer.MAX_VALUE;
int minIndex=-1;
for(int i=0;i<nums.length;i++){
if(nums[i]<min){
min=nums[i];
minIndex=i;
}
}
nums[minIndex]=min*multiplier;
k--;
}
return nums;
}
}
``` | 1 | 0 | ['Java'] | 0 |
final-array-state-after-k-multiplication-operations-i | Simple Solution | simple-solution-by-shreyas_kumar_m-ldcj | Code | Shreyas_kumar_m | NORMAL | 2025-03-02T02:24:17.243719+00:00 | 2025-03-02T02:24:17.243719+00:00 | 23 | false |
# Code
```javascript []
/**
* @param {number[]} nums
* @param {number} k
* @param {number} multiplier
* @return {number[]}
*/
var getFinalState = function(nums, k, multiplier) {
for(let i=0;i<k;i++){
let min = Math.min(...nums);
let ind = nums.indexOf(min);
nums[ind] = min*multiplier;
}
return nums;
};
``` | 1 | 0 | ['JavaScript'] | 0 |
final-array-state-after-k-multiplication-operations-i | Beginner's friendly solution 🔥 | Simple and easy to understand ✅ | beginners-friendly-solution-simple-and-e-xhpf | IntuitionThe problem requires modifying the k smallest elements in an array by multiplying them with a given multiplier. The goal is to update the array k times | NadeemMohammed | NORMAL | 2025-02-28T04:56:37.456799+00:00 | 2025-02-28T04:56:37.456799+00:00 | 20 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
The problem requires modifying the k smallest elements in an array by multiplying them with a given multiplier. The goal is to update the array k times while always modifying the smallest element in each step.
# Approach
<!-- Describe your approach to solving the problem. -->
1. Find the smallest element
• We use Math.min(...nums) to determine the smallest value in the array.
• Then, we use nums.indexOf(smallestValue) to find its index.
2. Modify the smallest element
• Multiply it by multiplier and update its value in place.
3. Repeat for k iterations
• Each iteration finds the new smallest value and modifies it accordingly.
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
If you found my solution helpful, I’d really appreciate it if you could give it an upvote! 🙌 Your support keeps me motivated to share more simple and efficient solutions. Thank you! 😊
# Code
```javascript []
/**
* @param {number[]} nums
* @param {number} k
* @param {number} multiplier
* @return {number[]}
*/
var getFinalState = function (nums, k, multiplier) {
for (let i = 0; i < k; i++) {
let indexOfSmallest = nums.indexOf(Math.min(...nums))
nums[indexOfSmallest] *= multiplier
}
return nums
};
``` | 1 | 0 | ['JavaScript'] | 0 |
final-array-state-after-k-multiplication-operations-i | Java easiest solution | java-easiest-solution-by-shreyagarg63-rdln | Complexity
Time complexity: O(N^2)
Space complexity: O(1)
Code | ShreyaGarg63 | NORMAL | 2025-02-23T18:16:30.931718+00:00 | 2025-02-23T18:16:30.931718+00:00 | 59 | false | # Complexity
- Time complexity: O(N^2)
- Space complexity: O(1)
# Code
```java []
class Solution {
public int[] getFinalState(int[] nums, int k, int multiplier) {
while(k>0){
int min = 0;
for(int i=0; i<nums.length; i++){
if(nums[i] < nums[min]){
min = i;
}
}
nums[min] *= multiplier;
k--;
}
return nums;
}
}
``` | 1 | 0 | ['Array', 'Math', 'Simulation', 'Java'] | 0 |
final-array-state-after-k-multiplication-operations-i | Beat 100% using loops | beat-100-using-loops-by-vamshikrishnan-arqb | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | vamshikrishnan | NORMAL | 2025-02-17T13:38:08.726546+00:00 | 2025-02-17T13:38:08.726546+00:00 | 52 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public int[] getFinalState(int[] nums, int k, int multiplier) {
while(k-->0){
int v=0;
int min=Integer.MAX_VALUE;
for(int i=0;i<nums.length;i++){
if(nums[i]<min){
min=nums[i];
v=i;
}
}
nums[v]=min*multiplier;
}
return nums;
}
}
``` | 1 | 0 | ['Java'] | 0 |
final-array-state-after-k-multiplication-operations-i | 100 % beats | | C++ 🎊 🔥 | 100-beats-c-by-varuntyagig-ib28 | Complexity
Time complexity:
O(k∗n)
Space complexity:
O(1)
Code | varuntyagig | NORMAL | 2025-02-07T18:32:35.804360+00:00 | 2025-02-07T18:32:35.804360+00:00 | 35 | false | # Complexity
- Time complexity:
$$O(k*n)$$
- Space complexity:
$$O(1)$$
# Code
```cpp []
class Solution {
public:
vector<int> getFinalState(vector<int>& nums, int k, int multiplier) {
int indices = -1, mini = INT_MAX;
while (k) {
for (int i = 0; i < nums.size(); i++) {
if (mini > nums[i]) {
mini = nums[i];
indices = i;
}
}
nums[indices] = nums[indices] * multiplier;
mini = INT_MAX;
indices = -1;
k--;
}
return nums;
}
};
``` | 1 | 0 | ['Array', 'Math', 'Simulation', 'C++'] | 0 |
final-array-state-after-k-multiplication-operations-i | Beat 100 % || Cpp STL || ONLY 4 LINES!!!!!|| UPVOTE!!!! | beat-100-cpp-stl-only-4-lines-upvote-by-lhi9g | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | cardze | NORMAL | 2024-12-30T07:56:22.295686+00:00 | 2024-12-30T07:57:24.727378+00:00 | 18 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
vector<int> getFinalState(vector<int>& nums, int k, int multiplier) {
if(k == 0) return nums;
auto e = min_element(nums.begin(), nums.end());
(*e) *= multiplier;
return getFinalState(nums, k - 1, multiplier);
}
};
```

| 1 | 0 | ['C++'] | 0 |
final-array-state-after-k-multiplication-operations-i | EASY TO UNDERSTAND | BEGINNER FRIENDLY | 3ms RUNTIME | C# | easy-to-understand-beginner-friendly-3ms-3lmh | \npublic class Solution {\n public int[] GetFinalState(int[] nums, int k, int multiplier) {\n \n for(int i=0; i< k; i++){\n int min | tyagideepti9 | NORMAL | 2024-12-16T17:24:33.093000+00:00 | 2024-12-16T17:24:33.093036+00:00 | 4 | false | ```\npublic class Solution {\n public int[] GetFinalState(int[] nums, int k, int multiplier) {\n \n for(int i=0; i< k; i++){\n int min = nums.Min();\n int index = Array.IndexOf(nums, min);\n \n nums[index] = min*multiplier;\n }\n \n return nums;\n }\n}\n``` | 1 | 0 | [] | 0 |
final-array-state-after-k-multiplication-operations-i | priority queue | priority-queue-by-mr_stark-nzeo | \nclass Solution {\npublic:\n \n static bool comp(pair<int,int> x, pair<int,int> y)\n {\n return x.second<y.second;\n }\n vector<int> getF | mr_stark | NORMAL | 2024-12-16T07:32:12.229453+00:00 | 2024-12-16T07:32:12.229491+00:00 | 20 | false | ```\nclass Solution {\npublic:\n \n static bool comp(pair<int,int> x, pair<int,int> y)\n {\n return x.second<y.second;\n }\n vector<int> getFinalState(vector<int>& a, int k, int m) {\n \n priority_queue<pair<int,int> , vector<pair<int,int>> , greater<pair<int,int>>> pq;\n int j=0;\n for(auto i:a)\n {\n pq.push({i,j++});\n }\n \n while(k--)\n {\n auto t = pq.top();\n int x = t.first;\n x*=m;\n pq.pop();\n pq.push({x,t.second});\n }\n \n vector<pair<int,int>> res;\n \n while(!pq.empty())\n {\n res.push_back(pq.top());\n pq.pop();\n }\n \n sort(res.begin(),res.end(),comp);\n \n vector<int> ans;\n for(auto &i:res)\n {\n ans.push_back(i.first);\n }\n \n return ans;\n }\n};\n``` | 1 | 0 | ['C'] | 0 |
final-array-state-after-k-multiplication-operations-i | Shortest Python solutions (4 and 6 lines) | shortest-python-solutions-4-and-6-lines-qtol4 | Code | sjamr10 | NORMAL | 2024-12-28T15:32:00.089863+00:00 | 2024-12-28T15:32:00.089863+00:00 | 29 | false | # Code
```python3 []
class Solution:
# Time Complexity: O(n * k)
# Space Complexity: O(1)
def getFinalState0(self, nums: List[int], k: int, multiplier: int) -> List[int]:
for _ in range(k):
idx = min(range(len(nums)), key=lambda x: nums[x])
nums[idx] *= multiplier
return nums
# Time Complexity: O(n + k * log(n))
# Space Complexity: O(n)
def getFinalState(self, nums: list[int], k: int, multiplier: int) -> list[int]:
pq = [(x, i) for i, x in enumerate(nums)]
heapify(pq)
for _ in range(k):
nums[pq[0][1]] = pq[0][0] * multiplier
heapreplace(pq, (pq[0][0] * multiplier, pq[0][1]))
return nums
``` | 1 | 0 | ['Python3'] | 0 |
final-array-state-after-k-multiplication-operations-i | Beats 100% || Easy Sol || used iterator || without priority_queue solution | beats-100-easy-sol-used-iterator-with-pr-2trw | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | oso_valid | NORMAL | 2024-12-25T20:17:38.834200+00:00 | 2024-12-26T18:33:07.910164+00:00 | 13 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
vector<int> getFinalState(vector<int>& nums, int k, int m) {
for (int i = 0; i < k; i++) {
auto it = min_element(begin(nums), end(nums));
*it*= m;
}
return nums;
}
};
``` | 1 | 0 | ['C++'] | 0 |
final-array-state-after-k-multiplication-operations-i | beats 100% using recursion(backtracking) c++💥💣🔥 | beats-100-using-recursionbacktracking-c-f73c4 | IntuitionThe problem requires repeatedly modifying the smallest element of the array by multiplying it by a given factor m for k iterations.
The main observatio | nourine-rgb | NORMAL | 2024-12-17T10:10:44.728861+00:00 | 2024-12-17T10:10:44.728861+00:00 | 4 | false | # Intuition\n\nThe problem requires repeatedly modifying the smallest element of the array by multiplying it by a given factor m for k iterations.\nThe main observation is that finding the smallest element at each step is critical. Backtracking can recursively explore the array to find the minimum element\'s index.\n\n# Approach\n1) - Define a helper function backtracking:\n . It recursively traverses the array to find the smallest element.\n . Once the traversal is complete, the smallest value (at index imin) is multiplied by m.\n2) - Use a loop to call this function k times to perform the 3) - 3)operation k times.\n3) - Return the modified array as the final result.\n\n# Complexity\n- Time complexity:O(k * N)\n- Space complexity:O(1)\n\n# Code\nc++ solution: \nclass Solution {\npublic:\n void backtracking(vector<int>& nums, int imin, int index, int m) {\n\tif (index == nums.size()) {\n\t\tnums[imin] *= m;\n\t\treturn;\n\t}\n\tif (nums[imin] > nums[index]) {\n\t\timin = index;\n\t}\n\tbacktracking(nums, imin, index + 1, m);\n}\n\n\n\nvector<int> getFinalState(vector<int>& nums, int k, int m) {\n\tfor (int i = 0; i < k; i++) {\n\t\tbacktracking(nums,0, 1,m);\n\t}\n\treturn nums;\n}\n};\n``` | 1 | 0 | ['C++'] | 0 |
final-array-state-after-k-multiplication-operations-i | Beats 100% using 1 nested loop | simple-answer-that-beats-100-by-saksham_-tc5p | IntuitionApproachComplexity
Time complexity: O(n)
Space complexity: O(1)
Code | Saksham_Gupta_ | NORMAL | 2024-12-17T06:51:40.253115+00:00 | 2024-12-17T06:57:07.506584+00:00 | 9 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int[] getFinalState(int[] nums, int k, int multiplier) {\n\n for(int itr=0; itr<k; itr++){\n // Find min in every iteration\n int minIndex = 0;\n for(int i=1; i<nums.length; i++){\n if(nums[i] < nums[minIndex]){\n minIndex = i;\n }\n }\n nums[minIndex] *= multiplier;\n }\n return nums;\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
final-array-state-after-k-multiplication-operations-i | Mutable & Immutable scala solutions | mutable-scala-solution-by-poiug07-5xhi | IntuitionI just code.ApproachSame approach as countless others.Complexity
Time complexity: O(max(n,klogn)) Assuming priority queue construction is O(n).
Spac | poiug07 | NORMAL | 2024-12-17T01:01:26.241566+00:00 | 2024-12-17T01:16:31.020179+00:00 | 9 | false | # Intuition\nI just code.\n\n# Approach\nSame approach as countless others.\n\n# Complexity\n- Time complexity: $O(\\text{max}(n, k \\log n))$ _Assuming priority queue construction is $O(n)$_.\n\n- Space complexity: $O(n)$\n\n# Code\n```scala []\nimport scala.collection.mutable.PriorityQueue\nobject Solution {\n def getFinalState(nums: Array[Int], k: Int, multiplier: Int): Array[Int] = {\n val pq = PriorityQueue(nums.zipWithIndex: _*)(Ordering[(Int, Int)].reverse)\n\n (1 to k).foreach { _ =>\n val (e, i) = pq.dequeue()\n pq.enqueue((e*multiplier, i))\n }\n\n pq.toArray.sortBy(_._2).map(_._1)\n }\n}\n```\n\n# Immutable solution\nTime complexity $O(n^2)$ but input size is small so it beats 100%. It is possible to do more efficient, but this is clean and nice.\n```\nobject Solution {\n def getFinalState(nums: Array[Int], k: Int, multiplier: Int): Array[Int] = {\n (1 to k).foldLeft(nums.zipWithIndex){(numsWithIdx, _) => \n val (e, idx) = numsWithIdx.minBy(_._1)\n numsWithIdx.updated(idx, (e*multiplier, idx))\n }.map(_._1)\n }\n}\n``` | 1 | 0 | ['Scala'] | 1 |
final-array-state-after-k-multiplication-operations-i | Basic approach | Python | basic-approach-python-by-deviraju999-xojt | IntuitionApproachLoop through the 'k' and replace the smallest with the new multiplied numberComplexity
Time complexity:
Space complexity:
Code | deviraju999 | NORMAL | 2024-12-16T23:51:58.078976+00:00 | 2024-12-16T23:51:58.078976+00:00 | 12 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nLoop through the \'k\' and replace the smallest with the new multiplied number\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python []\nclass Solution(object):\n def getFinalState(self, nums, k, multiplier):\n for n in range(k):\n nums[nums.index(min(nums))] = min(nums) * multiplier\n return nums\n``` | 1 | 0 | ['Python'] | 0 |
final-array-state-after-k-multiplication-operations-i | Brute force C++ solution | brute-force-c-solution-by-mohamed-elsogh-auxh | Code | Mohamed-Elsogher | NORMAL | 2024-12-16T22:15:27.267419+00:00 | 2024-12-16T22:15:27.267419+00:00 | 6 | false | # Code\n```cpp []\nclass Solution {\npublic:\n vector<int> getFinalState(vector<int>& nums, int k, int multiplier) {\n \n\n while(k--){\n int min = INT_MAX;\n int mini = -1;\n for(int i = 0 ; i < nums.size() ; i++){\n if(nums[i] < min){\n min = nums[i];\n mini = i ;\n }\n }\n nums[mini] = nums[mini] * multiplier ;\n }\n return nums; \n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
final-array-state-after-k-multiplication-operations-i | Python min heap, beats 100% | python-min-heap-beats-100-by-martensova-zy4k | IntuitionUse a priority queue / heap to keep track of the current minumum value in the array.ApproachBuild a heap using Python's heapq module. Populate it with | martensova | NORMAL | 2024-12-16T21:57:50.308246+00:00 | 2024-12-16T21:57:50.308246+00:00 | 7 | false | # Intuition\nUse a priority queue / heap to keep track of the current minumum value in the array.\n\n# Approach\nBuild a heap using Python\'s `heapq` module. Populate it with (`value`, `index`) pairs based on the original list.\nNow we do the following steps `k` times.\n1. Pop the smallest value from the heap.\n2. Update the pair by multiplying the value by `multiplier`\n3. Push the updated pair back onto the heap.\n4. Also update the original `nums` list with the updated value.\n\nNote that `heappop(my_heap)` and `heappush(my_heap, item)` maintain a valid heap by automatically reheaping.\n\n# Complexity\n- Time complexity:\n$$O(n*log(n))$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```python3 []\nimport heapq\nclass Solution:\n def getFinalState(self, nums: List[int], k: int, multiplier: int) -> List[int]:\n heap = [(nums[i], i) for i in range(len(nums))]\n heapq.heapify(heap)\n for _ in range(k):\n min_pair = heapq.heappop(heap)\n min_pair = (min_pair[0]*multiplier, min_pair[1])\n heapq.heappush(heap, min_pair)\n nums[min_pair[1]] = min_pair[0]\n return nums\n``` | 1 | 0 | ['Python3'] | 0 |
final-array-state-after-k-multiplication-operations-i | ✅ Python - Quick and Easy - 100% ✅ | python-quick-and-easy-100-by-danielol-0lsk | Code | DanielOL | NORMAL | 2024-12-16T20:57:29.620023+00:00 | 2024-12-16T20:57:29.620023+00:00 | 12 | false | # Code\n```python3 []\nclass Solution:\n def getFinalState(self, nums: List[int], k: int, multiplier: int) -> List[int]:\n \n pq = []\n\n for i, n in enumerate(nums):\n heapq.heappush(pq, (n, i))\n\n while k > 0:\n\n n, i = heapq.heappop(pq)\n\n heapq.heappush(pq, (n * multiplier, i))\n\n nums[i] = n * multiplier\n\n k -= 1\n\n return nums\n``` | 1 | 0 | ['Python3'] | 1 |
final-array-state-after-k-multiplication-operations-i | 🚀Beats 99%, Python3, Heap, easy to understand🚀 | beats-99-python3-heap-easy-to-understand-1nfy | Complexity
Time complexity: O(nlogn)
Space complexity: O(n)
Code | mak2rae | NORMAL | 2024-12-16T20:27:11.719007+00:00 | 2024-12-16T20:27:11.719007+00:00 | 9 | false | # Complexity\n- Time complexity: O(nlogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nclass Solution:\n def getFinalState(self, nums: List[int], k: int, multiplier: int) -> List[int]:\n min_heap = []\n\n # Build a min_heap\n for i, num in enumerate(nums):\n heapq.heappush(min_heap, (num, i))\n \n # Multiply k times\n for _ in range(k):\n num, i = heapq.heappop(min_heap)\n nums[i] *= multiplier\n heapq.heappush(min_heap, (nums[i], i))\n \n return nums\n``` | 1 | 0 | ['Heap (Priority Queue)', 'Python3'] | 0 |
final-array-state-after-k-multiplication-operations-i | ✅😮only 4 lines| beats 100%🔥🔥🔥 | beats-100-4-lines-solution-for-beginners-mmdj | IntuitionApproachComplexity
Time complexity:O(k*n)
Space complexity:O(1)
Code | robusttt | NORMAL | 2024-12-16T19:40:41.050329+00:00 | 2024-12-16T20:53:55.517121+00:00 | 11 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(k*n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<int> getFinalState(vector<int>& nums, int k, int multiplier) \n {\n while(k--)\n {\n auto it=min_element(nums.begin(),nums.end());\n *it=*(it)*multiplier;\n }\n return nums;\n \n }\n};\n``` | 1 | 0 | ['Array', 'Math', 'Heap (Priority Queue)', 'Simulation', 'C++'] | 0 |
final-array-state-after-k-multiplication-operations-i | 🎉BEATS 100%🏆| Most Efficient O(k * n) time🕒 Easiest Greedy Approach Explained🌟 | PHP | beats-100-most-efficient-ok-n-time-easie-gl3x | Intuition:The problem asks you to modify an array nums by performing k operations. In each operation:
Find the smallest number in the array (min(nums)).
Multipl | webdevanjali | NORMAL | 2024-12-16T18:55:09.051976+00:00 | 2024-12-16T19:01:39.260445+00:00 | 8 | false | # Intuition:\nThe problem asks you to modify an array `nums` by performing `k` operations. In each operation:\n- Find the smallest number in the array (`min(nums)`).\n- Multiply that smallest number by a given `multiplier`.\n- Update the array by replacing the smallest number with its multiplied value.\n\nThe idea is to Repeatedly find the smallest element, multiply it by the multiplier, and update the array.\n\n\n\n\n# Approach:\n1. **Loop through `k` operations**: We will perform the operation `k` times as specified.\n2. **Find the minimum value**: For each operation, identify the smallest value in the array.\n3. **Multiply and update**: Multiply the minimum value by the multiplier and replace it in the array.\n4. **Repeat** this process `k` times.\n5. **Return the final array** after performing all the operations.\n\n# Complexity:\n1. **Time Complexity**:$$ O(k * n)$$\n - For each of the `k` operations, we need to:\n - Find the minimum element in the array `min(nums)`, which takes O(n) where `n` is the length of the array.\n - Find the index of that minimum element using `array_search`, which also takes O(n).\n - Update the array element, which is an O(1) operation.\n - Thus, each operation takes O(n) time, and we perform `k` operations, so the overall time complexity is O(k * n).\n\n2. **Space Complexity**: $$O(1)$$\n - The space complexity is O(1), because we are not using any additional space that scales with the input size. We only modify the `nums` array in place.\n\n\n\n# Code\n```php []\nclass Solution {\n\n /**\n * @param Integer[] $nums\n * @param Integer $k\n * @param Integer $multiplier\n * @return Integer[]\n */\n function getFinalState($nums, $k, $multiplier) {\n for($i=0; $i<$k; $i++){\n $nums[array_search(min($nums),$nums)] *= $multiplier;\n }\n return $nums;\n }\n}\n```\n\n\n\n### Steps in the Code:\n1. **`for` loop (Line 5)**: We loop `k` times to perform the operations.\n2. **`min($nums)` (Line 6)**: Find the minimum value in the array `nums`.\n3. **`array_search(min($nums), $nums)` (Line 6)**: Find the index of the first occurrence of the minimum value.\n4. **Multiply and update the element**: Once we find the minimum value\'s index, we multiply that value by the `multiplier` and update the value in the array.\n5. **Return the modified array** after `k` operations.\n | 1 | 0 | ['Array', 'Math', 'PHP', 'Simulation'] | 0 |
final-array-state-after-k-multiplication-operations-i | Easy solution simple implementation of min heap | easy-solution-simple-implementation-of-m-jg36 | Intuitionmin heap and arrayApproachmake a min heap , store elements and its idx , at top of min heap min element and its idx will be present , take that out and | Shivesh977 | NORMAL | 2024-12-16T18:44:57.101308+00:00 | 2024-12-16T18:44:57.101308+00:00 | 10 | false | # Intuition\nmin heap and array \n\n# Approach\nmake a min heap , store elements and its idx , at top of min heap min element and its idx will be present , take that out and multiply with multiplier and again push in heap , again repeat this k times , at end pop out elements of heap and store in vector and return that \n# Complexity\n- Time complexity:\n0(klog(n)+n);\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<int> getFinalState(vector<int>& nums, int k, int multiplier) {\n priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>>pq;\n for(int i=0;i<nums.size();i++) pq.push({nums[i],i});\n while(k--){\n auto cell=pq.top();\n pq.pop();\n int num=cell.first;\n int idx=cell.second;\n cout<<num<<" "<<idx<<endl;\n pq.push({num*multiplier,idx});\n\n }\n vector<int>ans(nums.size());\n while(pq.size()){\n auto cell=pq.top();\n pq.pop();\n ans[cell.second]=cell.first;\n }\n return ans;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
final-array-state-after-k-multiplication-operations-i | BYOH approach (Bring Your Own Heap :) ) | byoh-approach-bring-your-own-heap-by-kus-nazq | IntuitionJust a Greedy Approach with custom made min heapComplexity
Time complexity:
klog(n)
Space complexity:
o(n)
Code | kushalbanik | NORMAL | 2024-12-16T17:46:49.311869+00:00 | 2024-12-16T17:57:08.531879+00:00 | 18 | false | # Intuition\nJust a Greedy Approach with custom made min heap\n\n# Complexity\n- Time complexity:\n klog(n)\n\n- Space complexity:\n o(n)\n\n# Code\n```java []\nclass Solution {\n class heap{\n private void heapify(int idx,int n,Pair<Integer,Integer>[] nums){\n int lidx = 2*idx + 1;\n int ridx = 2*idx + 2;\n int min = idx;\n\n if(lidx < n && nums[lidx].getKey() <= nums[min].getKey()){\n if(nums[lidx].getKey() < nums[min].getKey()){min = lidx;}\n else{min = (Math.min(nums[lidx].getValue() , nums[min].getValue())) == nums[min].getValue() ? min : lidx;}\n }\n\n if(ridx < n && nums[ridx].getKey() <= nums[min].getKey()){\n if(nums[ridx].getKey() < nums[min].getKey()){min = ridx;}\n else{min = (Math.min(nums[ridx].getValue() , nums[min].getValue())) == nums[min].getValue() ? min : ridx;}\n }\n\n if(min != idx){\n Pair<Integer,Integer> current = nums[idx];\n nums[idx] = nums[min];\n nums[min] = current;\n heapify(min,n,nums);\n }\n }\n\n public void buildheap(Pair<Integer,Integer>[] nums){\n for(int i=nums.length/2;i>=0;i--){\n heapify(i,nums.length,nums);\n }\n }\n\n public Pair<Integer,Integer> poll(Pair<Integer,Integer>[] nums){\n Pair<Integer,Integer> top = nums[0];\n nums[0] = nums[nums.length - 1];\n return top;\n }\n\n public void offer(Pair<Integer,Integer>[] nums,Pair<Integer,Integer> current){\n nums[nums.length - 1] = current;\n buildheap(nums);\n }\n }\n\n\n public int[] getFinalState(int[] nums, int k, int multiplier) {\n Pair<Integer,Integer>[] parr = new Pair[nums.length];\n heap hp = new heap();\n\n for(int i=0;i<nums.length;i++){parr[i] = new Pair<Integer,Integer>(nums[i],i);}\n hp.buildheap(parr);\n\n while(k-- > 0){\n Pair<Integer,Integer> top = hp.poll(parr);\n hp.offer(parr,new Pair<Integer,Integer>(top.getKey() * multiplier , top.getValue()));\n }\n\n\n int[] ans = new int[nums.length];\n\n for(Pair<Integer,Integer> p:parr){\n ans[p.getValue()] = p.getKey();\n }\n\n return ans;\n }\n}\n``` | 1 | 0 | ['Heap (Priority Queue)', 'Java'] | 1 |
final-array-state-after-k-multiplication-operations-i | Simple C code | simple-c-code-by-mukesh1855-4tsb | Code | mukesh1855 | NORMAL | 2024-12-16T17:35:43.797899+00:00 | 2024-12-16T17:35:43.797899+00:00 | 16 | false | \n# Code\n```c []\n\nint* getFinalState(int* nums, int size, int k, int multiplier, int* returnSize) {\n int *arr = malloc(4*size);\n *returnSize = size;\n for(int i=0;i<size;i++) arr[i] = nums[i];\n for(int i=0;i<k;i++)\n {\n int min = arr[0],ind=0;\n for(int j=0;j<size;j++)\n {\n if(arr[j]<min)\n {\n min = arr[j];\n ind = j;\n }\n }\n arr[ind] *= multiplier;\n }\n return arr;\n}\n``` | 1 | 0 | ['C'] | 0 |
final-array-state-after-k-multiplication-operations-i | Easiest Java Solution | easiest-java-solution-by-nikita_singhal-3of7 | IntuitionApproachComplexity
Time complexity: O(k*n)
Code | Nikita_singhal | NORMAL | 2024-12-16T17:12:08.106526+00:00 | 2024-12-16T17:12:08.106526+00:00 | 5 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(k*n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int[] getFinalState(int[] nums, int k, int multiplier) {\n \n for(int i=0; i<k; i++) {\n int index = 0;\n\n for(int j=1; j<nums.length; j++) {\n if(nums[j] < nums[index]) {\n index = j;\n }\n }\n\n nums[index] = nums[index] * multiplier;\n }\n\n return nums;\n\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
final-array-state-after-k-multiplication-operations-i | Beats 100% in Python, TC: O(k) SC: O(1) | beats-100-in-python-by-amreshgiri-q941 | IntuitionIn every step of the loop, get the min value and multiple it by the multiplier.Complexity
Time complexity:
O(k)
Space complexity:
O(1)
Code | amreshgiri | NORMAL | 2024-12-16T16:56:51.303788+00:00 | 2024-12-16T16:59:54.287168+00:00 | 6 | false | # Intuition\nIn every step of the loop, get the min value and multiple it by the multiplier.\n\n\n\n# Complexity\n- Time complexity:\nO(k)\n\n- Space complexity:\nO(1)\n\n# Code\n```python3 []\nclass Solution:\n def getFinalState(self, nums: List[int], k: int, multiplier: int) -> List[int]:\n for i in range(k):\n min_num = min(nums)\n nums[nums.index(min_num)] = min_num * multiplier\n return nums\n``` | 1 | 0 | ['Array', 'Python3'] | 0 |
final-array-state-after-k-multiplication-operations-i | Golang beats 100% | golang-beats-100-by-nname6617-z51l | #IntuitionSimple golang solution beats 100% runtime cause of fast stack operationsApproach
GetSmallestIndex
Reiterets over every element in nums to return its i | nname6617 | NORMAL | 2024-12-16T16:54:34.131945+00:00 | 2024-12-16T16:54:34.131945+00:00 | 52 | false | #Intuition \n<!-- Describe your first thoughts on how to solve this problem. -->\nSimple golang solution beats 100% runtime cause of fast stack operations \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- GetSmallestIndex\nReiterets over every element in nums to return its index\n- Main solution \nfor every number in nums getSmallestIndex and multiply it by the multiplier\n# Complexity\n- Time complexity:\n$$O(n*n)$$\n\n# Code\n```golang []\nfunc getFinalState(nums []int, k int, multiplier int) []int {\n for range k {\n idx := getSmallestIndex(nums)\n nums[idx] *= multiplier\n }\n return nums\n}\nfunc getSmallestIndex(nums []int) int {\n smallest := math.MaxInt\n index := 0\n for i := range len(nums) {\n if nums[i]< smallest {\n smallest = nums[i]\n index = i\n }\n }\n return index\n}\n``` | 1 | 0 | ['Go'] | 1 |
final-array-state-after-k-multiplication-operations-i | Brute-Force Approach || 0 ms Beats 100.00% 🚀|| Explanation✔|| Please Upvote ⬆ | brute-force-approach-0-ms-beats-10000-ex-c3h7 | IntuitionThe problem requires performing a specific operation k times on the array. Each operation involves finding the smallest element in the array and updati | Abhijithsr13 | NORMAL | 2024-12-16T16:52:17.512928+00:00 | 2024-12-16T16:52:17.512928+00:00 | 3 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem requires performing a specific operation k times on the array. Each operation involves finding the smallest element in the array and updating it. The brute-force approach is straightforward: iterate through the array to find the minimum and apply the operation directly.\n\n---\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. **Iterate k times:** \n- For each operation, traverse the array to find the minimum value.\n- Maintain the index of the smallest value during traversal.\n\n2. **Update the Minimum Value:** \n- Multiply the located minimum value by the given multiplier.\n- Store the updated value back in the array.\n\n3. **Repeat for k Operations::** \n- After k operations, the array will reflect all transformations.\n\n4. **Return the Array:** \n- Once all operations are complete, return the final state of the ***nums*** array.\n\n\n---\n\n\n# Complexity\n- Time complexity: **O(k\u22C5n)**\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:**O(1)**\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<int> getFinalState(vector<int>& nums, int k, int multiplier) {\n for (int i = 0; i < k; ++i) {\n int minIndex = 0;\n for (int j = 1; j < nums.size(); ++j) {\n if (nums[j] < nums[minIndex]) {\n minIndex = j;\n }\n }\n nums[minIndex] *= multiplier;\n }\n return nums;\n }\n};\n``` | 1 | 0 | ['Array', 'Math', 'C++'] | 0 |
final-array-state-after-k-multiplication-operations-i | Intuitive solution Java code beats 100% B) | intuitive-solution-java-code-beats-100-b-xkue | Complexity
Time complexity:
O(n∗k)
Space complexity:
O(n)
Code | jahnvi_777 | NORMAL | 2024-12-16T16:44:36.399277+00:00 | 2024-12-16T16:44:36.399277+00:00 | 12 | false | # Complexity\n- Time complexity:\n$$O(n*k)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```java []\nclass Solution {\n public int[] getFinalState(int[] nums, int k, int multiplier) {\n int n = nums.length;\n for(int i = 0 ; i < k ; i++){\n int m = nums[0];\n for(int x: nums) m = Math.min(m, x); //finding min element\n for(int j = 0 ; j < n ; j++){\n if(nums[j] == m){\n nums[j] *= multiplier; // updating the minimum value to minimum * multiplier\n break;\n }\n }\n }\n return nums;\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
final-array-state-after-k-multiplication-operations-i | most easy Solution | most-easy-solution-by-yashtripathi6969-8h6y | IntuitionUsing STLApproachJust find the min element in vector and multiply it and replace it .
Do this k timesComplexity
Time complexity:
O(k.n)
Space complexit | yashtripathi6969 | NORMAL | 2024-12-16T16:43:40.014642+00:00 | 2024-12-16T16:43:40.014642+00:00 | 7 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUsing STL\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nJust find the min element in vector and multiply it and replace it .\nDo this k times\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(k.n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<int> getFinalState(vector<int>& nums, int k, int multiplier) {\n\n while(k>0){\n k--;\n\n auto minN=min_element(nums.begin(),nums.end());\n\n int minI=distance(nums.begin(),minN);\n // sort\n // (nums.begin(),nums.end());\n nums[minI]=(*minN)*multiplier;\n\n\n\n \n\n }\n return nums;\n\n\n \n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
unique-binary-search-trees-ii | Divide-and-conquer. F(i) = G(i-1) * G(n-i) | divide-and-conquer-fi-gi-1-gn-i-by-liais-3x9o | This problem is a variant of the problem of [Unique Binary Search Trees][1]. \n\nI provided a solution along with explanation for the above problem, in the ques | liaison | NORMAL | 2015-02-04T15:31:14+00:00 | 2018-10-25T18:23:40.042019+00:00 | 46,521 | false | This problem is a variant of the problem of [Unique Binary Search Trees][1]. \n\nI provided a solution along with explanation for the above problem, in the question ["DP solution in 6 lines with explanation"](https://leetcode.com/problems/unique-binary-search-trees/discuss/31666/DP-Solution-in-6-lines-with-explanation.-F(i-n)-G(i-1)-*-G(n-i))\n\nIt is intuitive to solve this problem by following the same algorithm. Here is the code in a divide-and-conquer style. \n\n public List<TreeNode> generateTrees(int n) {\n \treturn generateSubtrees(1, n);\n }\n \n\tprivate List<TreeNode> generateSubtrees(int s, int e) {\n\t\tList<TreeNode> res = new LinkedList<TreeNode>();\n\t\tif (s > e) {\n\t\t\tres.add(null); // empty tree\n\t\t\treturn res;\n\t\t}\n\n\t\tfor (int i = s; i <= e; ++i) {\n\t\t\tList<TreeNode> leftSubtrees = generateSubtrees(s, i - 1);\n\t\t\tList<TreeNode> rightSubtrees = generateSubtrees(i + 1, e);\n\n\t\t\tfor (TreeNode left : leftSubtrees) {\n\t\t\t\tfor (TreeNode right : rightSubtrees) {\n\t\t\t\t\tTreeNode root = new TreeNode(i);\n\t\t\t\t\troot.left = left;\n\t\t\t\t\troot.right = right;\n\t\t\t\t\tres.add(root);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn res;\n\t}\n\n [1]: https://oj.leetcode.com/problems/unique-binary-search-trees/\n [2]: https://oj.leetcode.com/discuss/24282/dp-solution-in-6-lines-with-explanation-f-i-g-i-1-g-n-i | 350 | 0 | ['Divide and Conquer', 'Java'] | 39 |
unique-binary-search-trees-ii | Java Solution with DP | java-solution-with-dp-by-jianwu-zb8e | Here is my java solution with DP:\n\n\n public static List generateTrees(int n) {\n List[] result = new List[n + 1];\n result[0] = new ArrayLis | jianwu | NORMAL | 2014-08-24T18:26:18+00:00 | 2018-10-25T15:59:18.853413+00:00 | 81,940 | false | Here is my java solution with DP:\n\n\n public static List<TreeNode> generateTrees(int n) {\n List<TreeNode>[] result = new List[n + 1];\n result[0] = new ArrayList<TreeNode>();\n if (n == 0) {\n return result[0];\n }\n\n result[0].add(null);\n for (int len = 1; len <= n; len++) {\n result[len] = new ArrayList<TreeNode>();\n for (int j = 0; j < len; j++) {\n for (TreeNode nodeL : result[j]) {\n for (TreeNode nodeR : result[len - j - 1]) {\n TreeNode node = new TreeNode(j + 1);\n node.left = nodeL;\n node.right = clone(nodeR, j + 1);\n result[len].add(node);\n }\n }\n }\n }\n return result[n];\n }\n\n private static TreeNode clone(TreeNode n, int offset) {\n if (n == null) {\n return null;\n }\n TreeNode node = new TreeNode(n.val + offset);\n node.left = clone(n.left, offset);\n node.right = clone(n.right, offset);\n return node;\n }\n\n\n\n**result[i]** stores the result until length **i**. For the result for length i+1, select the root node j from 0 to i, combine the result from left side and right side. Note for the right side we have to clone the nodes as the value will be offsetted by **j**. | 287 | 3 | ['Java'] | 52 |
unique-binary-search-trees-ii | 🚀 C++ || Detailed Explanation || Recursive Tree || With Comments | c-detailed-explanation-recursive-tree-wi-lqht | Problem\n> Given n, find all structurally unique BST\'s (binary search trees) that has n nodes with unique values from 1 to n\n\nStrategy:\nWe will use a recurs | sdkaur | NORMAL | 2022-03-14T16:01:59.465468+00:00 | 2022-03-14T16:08:52.327131+00:00 | 15,863 | false | **Problem**\n> Given n, find all structurally unique BST\'s (binary search trees) that has n nodes with unique values from 1 to n\n\n**Strategy:**\nWe will use a **recursive helper function** `bst(start, end)` that receives a range (*start to end*, within n) and returns all BST\'s rooted in that range.\n\nNow let\'s look how our helper function will work!\n* As there will be trees with root as 1, 2, 3...n. Iterate through all values from start to end to construct tree rooted at i and construct its left and right subtree recursively.\n* We know that in Binary Search Tree all nodes in left subtree are smaller than root and in right subtree are larger than root. So for start = 1 and end = n, if we have ith number as root, all numbers from 1 to i-1 will be in left subtree and i+1 to n will be in right subtree. \n**Therefore, we will build the tree recursively for left and right subtrees rooted at i as `leftSubTree = bst(start, i-1)` and `rightSubtree = bst(i + 1, end)`**\n* So, till what moment we will recursively find the left and right subtrees?? Answer is until **start < end**!! \n`So when start > end, add NULL to the list and return`\nThis will be our base case!\n* Now, we have leftSubtree and rightSubtree for node with root i. The last thing we need to do is connect leftSubTree and rightSubTree with root and add this tree(rooted at i) to the ans list!\n\uD83D\uDCCC Here, we can have multiple left and right subtrees. So we need to loop through all left and right subtrees and connect every left subTree to right subTree and to current root(i) one by one.\n\n**Recursive Tree**\nSee below recursive tree for more details, expanded for n = 5 and 3 as root!\n\n\n\t\n\t\t\n**Code**\n```cpp\nvector<TreeNode*> buildTree(int start, int end) {\n\tvector<TreeNode*> ans;\n \n // If start > end, then subtree will be empty so add NULL in the ans and return it.\n if(start > end) {\n\t\tans.push_back(NULL);\n return ans;\n }\n\n // Iterate through all values from start to end to construct left and right subtree recursively\n\tfor(int i = start; i <= end; ++i) {\n\t\tvector<TreeNode*> leftSubTree = buildTree(start, i - 1); // Construct left subtree\n vector<TreeNode*> rightSubTree = buildTree(i + 1, end); // Construct right subtree\n \n\t\t// loop through all left and right subtrees and connect them to ith root \n\t\tfor(int j = 0; j < leftSubTree.size(); j++) {\n\t\t\tfor(int k = 0; k < rightSubTree.size(); k++) {\n\t\t\t\tTreeNode* root = new TreeNode(i); // Create root with value i\n\t\t\t\troot->left = leftSubTree[j]; // Connect left subtree rooted at leftSubTree[j]\n root->right = rightSubTree[k]; // Connect right subtree rooted at rightSubTree[k]\n\t\t\t\tans.push_back(root); // Add this tree(rooted at i) to ans data-structure\n\t\t\t}\n\t\t}\n }\n \n\treturn ans;\n}\n \nvector<TreeNode*> generateTrees(int n) {\n\treturn buildTree(1, n);\n}\n```\n | 278 | 1 | ['Recursion', 'C'] | 20 |
unique-binary-search-trees-ii | Should-be-6-Liner | should-be-6-liner-by-stefanpochmann-8dg5 | If only LeetCode had a TreeNode(val, left, right) constructor... sigh. Then I wouldn't need to provide my own and my solution would be six lines instead of elev | stefanpochmann | NORMAL | 2015-06-11T00:38:37+00:00 | 2018-10-16T09:39:57.259290+00:00 | 34,830 | false | If only LeetCode had a `TreeNode(val, left, right)` constructor... sigh. Then I wouldn't need to provide my own and my solution would be six lines instead of eleven.\n\n def generateTrees(self, n):\n def node(val, left, right):\n node = TreeNode(val)\n node.left = left\n node.right = right\n return node\n def trees(first, last):\n return [node(root, left, right)\n for root in range(first, last+1)\n for left in trees(first, root-1)\n for right in trees(root+1, last)] or [None]\n return trees(1, n)\n\nOr even just **four** lines, if it's not forbidden to add an optional argument:\n\n def node(val, left, right):\n node = TreeNode(val)\n node.left = left\n node.right = right\n return node\n \n class Solution:\n def generateTrees(self, last, first=1):\n return [node(root, left, right)\n for root in range(first, last+1)\n for left in self.generateTrees(root-1, first)\n for right in self.generateTrees(last, root+1)] or [None]\n\nJust another version, using loops instead of list comprehension:\n\n def generateTrees(self, n):\n def generate(first, last):\n trees = []\n for root in range(first, last+1):\n for left in generate(first, root-1):\n for right in generate(root+1, last):\n node = TreeNode(root)\n node.left = left\n node.right = right\n trees += node,\n return trees or [None]\n return generate(1, n) | 205 | 12 | ['Python'] | 35 |
unique-binary-search-trees-ii | [Python] DFS with Memoization - Clean & Concise | python-dfs-with-memoization-clean-concis-wcyd | Idea\n- Let dfs(left, right) return all valid BSTs where values in the BST in range [left..right].\n- Then dfs(1, n) is our result.\n- To solve dfs(left, right) | hiepit | NORMAL | 2021-09-02T07:16:09.874480+00:00 | 2021-09-02T09:34:13.610682+00:00 | 11,847 | false | **Idea**\n- Let `dfs(left, right)` return all valid BSTs where values in the BST in range `[left..right]`.\n- Then `dfs(1, n)` is our result.\n- To solve `dfs(left, right)`, we just\n\t- Generate `root` value in range `[left...right]`\n\t- Get left subtrees by `leftNodes = dfs(left, root-1)`\n\t- Get right subtrees by `rightNodes = dfs(root+1, right)`.\n\t- Add all combination between `leftNodes` and `rightNodes` to form `root` trees.\n- Can we cache the result of `dfs(left, right)` to prevent it to re-compute multiple time.\n- There is a simillar problem, which is **[894. All Possible Full Binary Trees](https://leetcode.com/problems/all-possible-full-binary-trees/)**, try to solve it yourself.\n```python\nclass Solution:\n def generateTrees(self, n: int) -> List[Optional[TreeNode]]:\n @lru_cache(None)\n def dfs(left, right):\n if left > right: return [None]\n if left == right: return [TreeNode(left)]\n ans = []\n for root in range(left, right+1):\n leftNodes = dfs(left, root - 1)\n rightNodes = dfs(root+1, right)\n for leftNode in leftNodes:\n for rightNode in rightNodes:\n rootNode = TreeNode(root, leftNode, rightNode)\n ans.append(rootNode)\n return ans\n \n return dfs(1, n)\n```\n**Complexity**\n- Time: `O(C0+C1+...Cn)`, where `Cn` is the [Catalan number](https://en.wikipedia.org/wiki/Catalan_number), `n <= 8`. Can check this problem [96. Unique Binary Search Trees](https://leetcode.com/problems/unique-binary-search-trees/) to know why the number of nodes in the BST with `n` nodes is a Catalan number.\n\t- The Catalan numbers for `n = 0, 1, 2, 3, 4, 5, 6, 7, 8` are `1, 1, 2, 5, 14, 42, 132, 429, 1430`.\n- Space: `O(n * Cn)`, there is total `Cn` BSTs, each BST has `n` nodes.\n\nIf you think this **post is useful**, I\'m happy if you **give a vote**. Any **questions or discussions are welcome!** Thank a lot. | 167 | 1 | [] | 10 |
unique-binary-search-trees-ii | ✅ Recursion & DP [VIDEO] Catalan Number - Unique BST | recursion-dp-video-catalan-number-unique-nfdh | Given an integer \( n \), the task is to return all the structurally unique BST\'s (binary search trees) that have exactly \( n \) nodes of unique values from \ | vanAmsen | NORMAL | 2023-08-05T00:22:20.783064+00:00 | 2023-08-05T03:50:06.259959+00:00 | 17,180 | false | Given an integer \\( n \\), the task is to return all the structurally unique BST\'s (binary search trees) that have exactly \\( n \\) nodes of unique values from \\( 1 \\) to \\( n \\).\n\n# Intuition Recursion & Dynamic Programming\nThe problem can be solved by utilizing the properties of a BST, where the left subtree has all values less than the root and the right subtree has values greater than the root. We can explore both recursive and dynamic programming (DP) approaches to generate all possible combinations of unique BSTs.\n\n# Live Coding & Explenation Recursion\nhttps://youtu.be/HeB6Oufsg_o\n\n# n-th Catalan number\n\nIn the context of this task, the \\(n\\)-th Catalan number gives the number of distinct binary search trees that can be formed with \\(n\\) unique values. The \\(n\\)-th Catalan number is given by the formula:\n\n$$\nC_n = \\frac{1}{n+1} \\binom{2n}{n} = \\frac{(2n)!}{(n+1)!n!}\n$$\n\nThe time and space complexity of generating these trees are both $$O(C_n)$$, which is equivalent to $$O\\left(\\frac{4^n}{n\\sqrt{n}}\\right)$$.\n\nHere\'s how it relates to the task:\n\n1. **Choosing the Root**: For each root value, we\'re essentially dividing the problem into two subproblems (left and right subtrees), and the number of combinations for each division aligns with the recursive definition of the Catalan numbers.\n \n2. **Recursive and Dynamic Programming Solutions**: Both approaches inherently follow the recursive nature of the Catalan numbers. The recursive approach directly corresponds to the recursive formula for the Catalan numbers, while the dynamic programming approach leverages the computed results for smaller subproblems to build up to the solution.\n\n3. **Number of Unique BSTs**: The fact that there are \\(C_n\\) unique BSTs with \\(n\\) nodes is a direct application of the Catalan numbers. The complexity of generating all these trees is thus closely tied to the value of the \\(n\\)-th Catalan number.\n\nIn conclusion, the complexity of the problem is inherently linked to the Catalan numbers, as they precisely describe the number of unique structures that can be formed, which in turn dictates the computational resources required to enumerate them.\n\n# Approach Short\n\n1. **Recursion**: Recursively construct left and right subtrees and combine them with each root.\n2. **Dynamic Programming**: Use dynamic programming to store the result of subproblems (subtrees) and utilize them for constructing unique BSTs.\n\n## Approach Differences\nThe recursive approach constructs the trees from scratch every time, while the DP approach reuses previously computed subtrees to avoid redundant work.\n\n# Approach Recursion\n\nThe recursive approach involves the following steps:\n\n1. **Base Case**: If the start index is greater than the end index, return a list containing `None`. This represents an empty tree and serves as the base case for the recursion.\n\n2. **Choose Root**: For every number \\( i \\) in the range from `start` to `end`, consider \\( i \\) as the root of the tree.\n\n3. **Generate Left Subtrees**: Recursively call the function to generate all possible left subtrees using numbers from `start` to \\( i-1 \\). This forms the left child of the root.\n\n4. **Generate Right Subtrees**: Recursively call the function to generate all possible right subtrees using numbers from \\( i+1 \\) to `end`. This forms the right child of the root.\n\n5. **Combine Subtrees**: For each combination of left and right subtrees, create a new tree with \\( i \\) as the root and the corresponding left and right subtrees. Append this tree to the list of all possible trees.\n\n6. **Return Trees**: Finally, return the list of all trees generated.\n\n# Complexity Recursion\n- Time complexity: $$O(\\frac{4^n}{n\\sqrt{n}})$$\n- Space complexity: $$ O(\\frac{4^n}{n\\sqrt{n}}) $$\n\n# Performance Recursion\n\n| Language | Runtime (ms) | Beats (%) | Memory (MB) | Beats (%) |\n|------------|--------------|-----------|-------------|-----------|\n| Rust | 0 | 100 | 2.5 | 80 |\n| Java | 1 | 99.88 | 43.7 | 66.87 |\n| Go | 3 | 56.88 | 4.4 | 63.30 |\n| C++ | 16 | 75.53 | 16.2 | 20.99 |\n| Python3 | 53 | 97.4 | 18.1 | 27.83 |\n| JavaScript | 74 | 89.61 | 48.4 | 55.19 |\n| C# | 91 | 88.76 | 39.8 | 19.10 |\n\n\n\n\n# Code Recursion\n``` Python []\nclass Solution:\n def generateTrees(self, n: int):\n def generate_trees(start, end):\n if start > end:\n return [None,]\n \n all_trees = []\n for i in range(start, end + 1):\n left_trees = generate_trees(start, i - 1)\n right_trees = generate_trees(i + 1, end)\n \n for l in left_trees:\n for r in right_trees:\n current_tree = TreeNode(i)\n current_tree.left = l\n current_tree.right = r\n all_trees.append(current_tree)\n \n return all_trees\n \n return generate_trees(1, n) if n else []\n```\n``` C++ []\nclass Solution {\npublic:\n vector<TreeNode*> generateTrees(int n) {\n return n ? generate_trees(1, n) : vector<TreeNode*>();\n }\n\nprivate:\n vector<TreeNode*> generate_trees(int start, int end) {\n if (start > end) return {nullptr};\n\n vector<TreeNode*> all_trees;\n for (int i = start; i <= end; i++) {\n vector<TreeNode*> left_trees = generate_trees(start, i - 1);\n vector<TreeNode*> right_trees = generate_trees(i + 1, end);\n\n for (TreeNode* l : left_trees) {\n for (TreeNode* r : right_trees) {\n TreeNode* current_tree = new TreeNode(i);\n current_tree->left = l;\n current_tree->right = r;\n all_trees.push_back(current_tree);\n }\n }\n }\n return all_trees;\n }\n};\n```\n``` Java []\nclass Solution {\n public List<TreeNode> generateTrees(int n) {\n return n > 0 ? generate_trees(1, n) : new ArrayList<>();\n }\n\n private List<TreeNode> generate_trees(int start, int end) {\n List<TreeNode> all_trees = new ArrayList<>();\n if (start > end) {\n all_trees.add(null);\n return all_trees;\n }\n\n for (int i = start; i <= end; i++) {\n List<TreeNode> left_trees = generate_trees(start, i - 1);\n List<TreeNode> right_trees = generate_trees(i + 1, end);\n\n for (TreeNode l : left_trees) {\n for (TreeNode r : right_trees) {\n TreeNode current_tree = new TreeNode(i);\n current_tree.left = l;\n current_tree.right = r;\n all_trees.add(current_tree);\n }\n }\n }\n return all_trees;\n }\n}\n```\n``` JavaScript []\nvar generateTrees = function(n) {\n if (n === 0) return [];\n\n function generate_trees(start, end) {\n if (start > end) return [null];\n\n const all_trees = [];\n for (let i = start; i <= end; i++) {\n const left_trees = generate_trees(start, i - 1);\n const right_trees = generate_trees(i + 1, end);\n\n for (const l of left_trees) {\n for (const r of right_trees) {\n const current_tree = new TreeNode(i);\n current_tree.left = l;\n current_tree.right = r;\n all_trees.push(current_tree);\n }\n }\n }\n return all_trees;\n }\n\n return generate_trees(1, n);\n};\n```\n``` C# []\npublic class Solution {\n public IList<TreeNode> GenerateTrees(int n) {\n return n > 0 ? GenerateTrees(1, n) : new List<TreeNode>();\n }\n\n private IList<TreeNode> GenerateTrees(int start, int end) {\n if (start > end) return new List<TreeNode> {null};\n\n var all_trees = new List<TreeNode>();\n for (int i = start; i <= end; i++) {\n var left_trees = GenerateTrees(start, i - 1);\n var right_trees = GenerateTrees(i + 1, end);\n\n foreach (var l in left_trees) {\n foreach (var r in right_trees) {\n var current_tree = new TreeNode(i, l, r);\n all_trees.Add(current_tree);\n }\n }\n }\n return all_trees;\n }\n}\n```\n``` Rust []\nuse std::rc::Rc;\nuse std::cell::RefCell;\n\nimpl Solution {\n pub fn generate_trees(n: i32) -> Vec<Option<Rc<RefCell<TreeNode>>>> {\n if n == 0 {\n return Vec::new();\n }\n Self::generate(1, n)\n }\n\n fn generate(start: i32, end: i32) -> Vec<Option<Rc<RefCell<TreeNode>>>> {\n if start > end {\n return vec![None];\n }\n\n let mut all_trees = Vec::new();\n for i in start..=end {\n let left_trees = Self::generate(start, i - 1);\n let right_trees = Self::generate(i + 1, end);\n\n for l in &left_trees {\n for r in &right_trees {\n let current_tree = Some(Rc::new(RefCell::new(TreeNode::new(i))));\n current_tree.as_ref().unwrap().borrow_mut().left = l.clone();\n current_tree.as_ref().unwrap().borrow_mut().right = r.clone();\n all_trees.push(current_tree);\n }\n }\n }\n all_trees\n }\n}\n```\n``` Go []\nfunc generateTrees(n int) []*TreeNode {\n\tif n == 0 {\n\t\treturn []*TreeNode{}\n\t}\n\treturn generate(1, n)\n}\n\nfunc generate(start, end int) []*TreeNode {\n\tif start > end {\n\t\treturn []*TreeNode{nil}\n\t}\n\n\tvar allTrees []*TreeNode\n\tfor i := start; i <= end; i++ {\n\t\tleftTrees := generate(start, i-1)\n\t\trightTrees := generate(i+1, end)\n\n\t\tfor _, l := range leftTrees {\n\t\t\tfor _, r := range rightTrees {\n\t\t\t\tcurrentTree := &TreeNode{Val: i, Left: l, Right: r}\n\t\t\t\tallTrees = append(allTrees, currentTree)\n\t\t\t}\n\t\t}\n\t}\n\treturn allTrees\n}\n```\n\n# Approach Dynamic Programming\n\n1. **Initialization**: Create a DP table `dp` where `dp[i]` will store all the unique BSTs with `i` nodes. Initialize `dp[0]` with a single `None` value representing an empty tree.\n\n2. **Iterate Over Number of Nodes**: For every number `nodes` from 1 to `n`, iterate and construct all possible trees with `nodes` number of nodes.\n\n3. **Choose Root**: For every possible root value within the current `nodes`, iterate and use the root to build trees.\n\n4. **Use Previously Computed Subtrees**: For the chosen root, use the previously computed `dp[root - 1]` for left subtrees and `dp[nodes - root]` for right subtrees.\n\n5. **Clone Right Subtree**: Since the right subtree\'s values will be affected by the choice of the root, clone the right subtree with an offset equal to the root value. The `clone` function handles this.\n\n6. **Combine Subtrees**: Create a new tree by combining the current root with the left and right subtrees. Append this tree to `dp[nodes]`.\n\n7. **Return Result**: Finally, return the trees stored in `dp[n]`.\n\n# Complexity Dynamic Programming\n- Time complexity: $$O(\\frac{4^n}{n\\sqrt{n}})$$\n- Space complexity: $$ O(\\frac{4^n}{n\\sqrt{n}}) $$\n\n# Performance Dynamic Programming\n\n| Language | Runtime (ms) | Beats (%) | Memory (MB) | Beats (%) |\n|------------|--------------|-----------|-------------|-----------|\n| Rust | 0 | 100 | 2.7 | 20 |\n| Java | 1 | 99.88 | 44.1 | 8.87 |\n| Go | 3 | 56.88 | 4.2 | 90.83 |\n| C++ | 10 | 96.72 | 12.5 | 86.56 |\n| JavaScript | 67 | 96.75 | 48.5 | 55.19 |\n| Python3 | 49 | 98.84 | 18.1 | 21.91 |\n| C# | 91 | 88.76 | 38.5 | 80.90 |\n\n\n\n\n# Code Dynamic Programming\n``` Python []\nclass Solution:\n def generateTrees(self, n: int):\n if n == 0:\n return []\n\n dp = [[] for _ in range(n + 1)]\n dp[0].append(None)\n for nodes in range(1, n + 1):\n for root in range(1, nodes + 1):\n for left_tree in dp[root - 1]:\n for right_tree in dp[nodes - root]:\n root_node = TreeNode(root)\n root_node.left = left_tree\n root_node.right = self.clone(right_tree, root)\n dp[nodes].append(root_node)\n return dp[n]\n \n def clone(self, n: TreeNode, offset: int) -> TreeNode:\n if n:\n node = TreeNode(n.val + offset)\n node.left = self.clone(n.left, offset)\n node.right = self.clone(n.right, offset)\n return node\n return None\n```\n``` C++ []\nclass Solution {\npublic:\n vector<TreeNode*> generateTrees(int n) {\n if (n == 0) return {};\n\n vector<vector<TreeNode*>> dp(n + 1);\n dp[0].push_back(nullptr);\n for (int nodes = 1; nodes <= n; nodes++) {\n for (int root = 1; root <= nodes; root++) {\n for (TreeNode* left_tree : dp[root - 1]) {\n for (TreeNode* right_tree : dp[nodes - root]) {\n TreeNode* root_node = new TreeNode(root);\n root_node->left = left_tree;\n root_node->right = clone(right_tree, root);\n dp[nodes].push_back(root_node);\n }\n }\n }\n }\n return dp[n];\n }\n\nprivate:\n TreeNode* clone(TreeNode* n, int offset) {\n if (n == nullptr) return nullptr;\n TreeNode* node = new TreeNode(n->val + offset);\n node->left = clone(n->left, offset);\n node->right = clone(n->right, offset);\n return node;\n }\n};\n```\n``` Java []\nclass Solution {\n public List<TreeNode> generateTrees(int n) {\n if (n == 0) return new ArrayList<>();\n\n List<TreeNode>[] dp = new ArrayList[n + 1];\n dp[0] = new ArrayList<>();\n dp[0].add(null);\n for (int nodes = 1; nodes <= n; nodes++) {\n dp[nodes] = new ArrayList<>();\n for (int root = 1; root <= nodes; root++) {\n for (TreeNode left_tree : dp[root - 1]) {\n for (TreeNode right_tree : dp[nodes - root]) {\n TreeNode root_node = new TreeNode(root);\n root_node.left = left_tree;\n root_node.right = clone(right_tree, root);\n dp[nodes].add(root_node);\n }\n }\n }\n }\n return dp[n];\n }\n\n private TreeNode clone(TreeNode n, int offset) {\n if (n == null) return null;\n TreeNode node = new TreeNode(n.val + offset);\n node.left = clone(n.left, offset);\n node.right = clone(n.right, offset);\n return node;\n }\n}\n```\n``` JavaScript []\nvar generateTrees = function(n) {\n if (n === 0) return [];\n\n const dp = Array.from({ length: n + 1 }, () => []);\n dp[0].push(null);\n for (let nodes = 1; nodes <= n; nodes++) {\n for (let root = 1; root <= nodes; root++) {\n for (const left_tree of dp[root - 1]) {\n for (const right_tree of dp[nodes - root]) {\n const root_node = new TreeNode(root);\n root_node.left = left_tree;\n root_node.right = clone(right_tree, root);\n dp[nodes].push(root_node);\n }\n }\n }\n }\n return dp[n];\n};\n\nfunction clone(n, offset) {\n if (n === null) return null;\n const node = new TreeNode(n.val + offset);\n node.left = clone(n.left, offset);\n node.right = clone(n.right, offset);\n return node;\n}\n```\n``` C# []\npublic class Solution {\n public IList<TreeNode> GenerateTrees(int n) {\n if (n == 0) return new List<TreeNode>();\n\n var dp = new List<TreeNode>[n + 1];\n dp[0] = new List<TreeNode> { null };\n for (int nodes = 1; nodes <= n; nodes++) {\n dp[nodes] = new List<TreeNode>();\n for (int root = 1; root <= nodes; root++) {\n foreach (var left_tree in dp[root - 1]) {\n foreach (var right_tree in dp[nodes - root]) {\n TreeNode root_node = new TreeNode(root);\n root_node.left = left_tree;\n root_node.right = Clone(right_tree, root);\n dp[nodes].Add(root_node);\n }\n }\n }\n }\n return dp[n];\n }\n\n private TreeNode Clone(TreeNode n, int offset) {\n if (n == null) return null;\n TreeNode node = new TreeNode(n.val + offset);\n node.left = Clone(n.left, offset);\n node.right = Clone(n.right, offset);\n return node;\n }\n}\n```\n``` Rust []\nuse std::rc::Rc;\nuse std::cell::RefCell;\n\nimpl Solution {\n pub fn generate_trees(n: i32) -> Vec<Option<Rc<RefCell<TreeNode>>>> {\n if n == 0 {\n return Vec::new();\n }\n\n let mut dp = vec![Vec::new(); (n + 1) as usize];\n dp[0].push(None);\n for nodes in 1..=n {\n let mut trees_per_node = Vec::new();\n for root in 1..=nodes {\n let left_trees = &dp[(root - 1) as usize];\n let right_trees = &dp[(nodes - root) as usize];\n for left_tree in left_trees {\n for right_tree in right_trees {\n let root_node = Some(Rc::new(RefCell::new(TreeNode::new(root))));\n root_node.as_ref().unwrap().borrow_mut().left = left_tree.clone();\n root_node.as_ref().unwrap().borrow_mut().right = Solution::clone(right_tree.clone(), root);\n trees_per_node.push(root_node);\n }\n }\n }\n dp[nodes as usize] = trees_per_node;\n }\n dp[n as usize].clone()\n }\n\n fn clone(tree: Option<Rc<RefCell<TreeNode>>>, offset: i32) -> Option<Rc<RefCell<TreeNode>>> {\n tree.map(|node| {\n Rc::new(RefCell::new(TreeNode {\n val: node.borrow().val + offset,\n left: Solution::clone(node.borrow().left.clone(), offset),\n right: Solution::clone(node.borrow().right.clone(), offset),\n }))\n })\n }\n}\n```\n``` Go []\nvar generateTrees = function(n) {\n if (n === 0) return [];\n\n const dp = Array.from({ length: n + 1 }, () => []);\n dp[0].push(null);\n for (let nodes = 1; nodes <= n; nodes++) {\n for (let root = 1; root <= nodes; root++) {\n for (const left_tree of dp[root - 1]) {\n for (const right_tree of dp[nodes - root]) {\n const root_node = new TreeNode(root);\n root_node.left = left_tree;\n root_node.right = clone(right_tree, root);\n dp[nodes].push(root_node);\n }\n }\n }\n }\n return dp[n];\n};\n\nfunction clone(n, offset) {\n if (n === null) return null;\n const node = new TreeNode(n.val + offset);\n node.left = clone(n.left, offset);\n node.right = clone(n.right, offset);\n return node;\n}\n```\n\nThe time and space complexity for both approaches are the same. The $$ O(\\frac{4^n}{n\\sqrt{n}}) $$ complexity arises from the Catalan number, which gives the number of BSTs for a given \\( n \\).\n\nI hope you find this solution helpful in understanding how to generate all structurally unique Binary Search Trees (BSTs) for a given number n. If you have any further questions or need additional clarifications, please don\'t hesitate to ask. If you understood the solution and found it beneficial, please consider giving it an upvote. Happy coding, and may your coding journey be filled with success and satisfaction! \uD83D\uDE80\uD83D\uDC68\u200D\uD83D\uDCBB\uD83D\uDC69\u200D\uD83D\uDCBB | 113 | 3 | ['Dynamic Programming', 'Recursion', 'C++', 'Java', 'Go', 'Python3', 'Rust', 'JavaScript', 'C#'] | 9 |
unique-binary-search-trees-ii | Share a C++ DP solution with O(1) space | share-a-c-dp-solution-with-o1-space-by-w-sj9p | The basic idea is that we can construct the result of n node tree just from the result of n-1 node tree.\nHere's how we do it: only 2 conditions: 1) The nth no | wangxinlei | NORMAL | 2015-01-04T06:37:57+00:00 | 2018-10-24T23:11:03.922843+00:00 | 36,048 | false | The basic idea is that we can construct the result of n node tree just from the result of n-1 node tree.\nHere's how we do it: only 2 conditions: 1) The nth node is the new root, so `newroot->left = oldroot;`\n2) the nth node is not root, we traverse the old tree, every time the node in the old tree has a right child, we can perform: `old node->right = nth node, nth node ->left = right child;` and when we reach the end of the tree, don't forget we can also add the nth node here.\nOne thing to notice is that every time we push a TreeNode in our result, I push the clone version of the root, and I recover what I do to the old node immediately. This is because you may use the old tree for several times.\n \n\n class Solution {\n public:\n TreeNode* clone(TreeNode* root){\n if(root == nullptr)\n return nullptr;\n TreeNode* newroot = new TreeNode(root->val);\n newroot->left = clone(root->left);\n newroot->right = clone(root->right);\n return newroot;\n }\n vector<TreeNode *> generateTrees(int n) {\n vector<TreeNode *> res(1,nullptr);\n for(int i = 1; i <= n; i++){\n vector<TreeNode *> tmp;\n for(int j = 0; j<res.size();j++){\n TreeNode* oldroot = res[j];\n TreeNode* root = new TreeNode(i);\n TreeNode* target = clone(oldroot);\n root->left = target;\n tmp.push_back(root);\n \n if(oldroot!=nullptr){\n TreeNode* tmpold = oldroot;\n while(tmpold->right!=nullptr){\n TreeNode* nonroot = new TreeNode(i);\n TreeNode *tright = tmpold->right;\n tmpold->right = nonroot;\n nonroot->left = tright;\n TreeNode *target = clone(oldroot);\n tmp.push_back(target);\n tmpold->right = tright;\n tmpold = tmpold->right;\n }\n tmpold->right = new TreeNode(i);\n TreeNode *target = clone(oldroot);\n tmp.push_back(target);\n tmpold->right = nullptr;\n }\n }\n res=tmp;\n }\n return res;\n }\n }; | 108 | 2 | [] | 23 |
unique-binary-search-trees-ii | My Accepted C++ solution (recursive, less than 30 lines) | my-accepted-c-solution-recursive-less-th-mrel | explaination:\nGiven a tree which n nodes, it has the follwing form: \n(0)root(n-1)\n(1)root(n-2)\n(2)root(n-3)\nwhere (x) denotes the trees with x nodes.\n\nN | chn | NORMAL | 2014-11-05T12:28:04+00:00 | 2018-10-05T15:44:48.631068+00:00 | 17,373 | false | **explaination:**\nGiven a tree which n nodes, it has the follwing form: \n(0)root(n-1)\n(1)root(n-2)\n(2)root(n-3)\nwhere (x) denotes the trees with x nodes.\n\nNow take n=3 for example. Given n=3, we have [1 2 3] in which each of them can be used as the tree root.\n\nwhen root=1: [1 # 2 # 3]; [1 # 3 2];\nwhen root=2: [2 1 3]; \nwhen root=3: (similar with the situations when root=1.)\n\nThus, if we write a recursive function who generates a group of trees in which the numbers range from *f* to *t*, we have to generate the left trees and right trees of each tree in the vector. \n\nI give the following recursive code and expect to see non-recursive ones. please! \n\n**code:**\n\n vector<TreeNode *> generateTree(int from, int to)\n {\n vector<TreeNode *> ret;\n if(to - from < 0) ret.push_back(0);\n if(to - from == 0) ret.push_back(new TreeNode(from));\n if(to - from > 0)\n {\n for(int i=from; i<=to; i++)\n {\n vector<TreeNode *> l = generateTree(from, i-1);\n vector<TreeNode *> r = generateTree(i+1, to);\n\n for(int j=0; j<l.size(); j++)\n {\n for(int k=0; k<r.size(); k++)\n {\n TreeNode * h = new TreeNode (i);\n h->left = l[j];\n h->right = r[k];\n ret.push_back(h);\n }\n }\n }\n }\n return ret;\n }\n \n vector<TreeNode *> generateTrees(int n) {\n return generateTree(1, n);\n } | 85 | 3 | [] | 26 |
unique-binary-search-trees-ii | 【Video】3 important points | video-3-important-points-by-niits-auvc | Intuition\nThere 3 important things. \n\nOne is we try to create subtrees with some range between start(minimum) and end(maximum) value.\n\nSecond is calculatio | niits | NORMAL | 2024-12-05T12:03:18.956080+00:00 | 2024-12-05T12:03:18.956098+00:00 | 3,237 | false | # Intuition\nThere 3 important things. \n\nOne is we try to create subtrees with some range between start(minimum) and end(maximum) value.\n\nSecond is calculation of the range. left range should be between start and current root - 1 as end value because all values of left side must be smaller than current root. right range should be between current root + 1 and end becuase all values on the right side should be greater than current root value.\n\nThrid is we call the same funtion recursively, so it\'s good idea to keep results of current start and end, so that we can use the results later. It\'s time saving.\n\n---\n\n# Solution Video\n\nhttps://youtu.be/5G-Kwx8Lm5Q\n\n**\u25A0 Subscribe URL**\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\nSubscribers: 11,570\nThank you for your support!\n\n---\n\n# Approach\nThis is based on Python. Other might be different a bit.\n\n1. Define a class `Solution` containing a method `generateTrees` which takes an integer `n` as input and returns a list of optional `TreeNode` objects.\n\n2. Check if `n` is 0. If it is, return an empty list since there are no possible trees with 0 nodes.\n\n3. Initialize an empty dictionary called `memo`. This dictionary will be used to store previously computed results for specific ranges of values to avoid redundant calculations.\n\n4. Define an inner function called `generate_trees` that takes two parameters: `start` and `end`, which represent the range of values for which binary search trees need to be generated.\n\n5. Inside the `generate_trees` function:\n - Check if the tuple `(start, end)` exists as a key in the `memo` dictionary. If it does, return the corresponding value from the `memo` dictionary.\n - Initialize an empty list called `trees`. This list will store the generated trees for the current range.\n - If `start` is greater than `end`, append `None` to the `trees` list, indicating an empty subtree, and return the `trees` list.\n - Loop through each value `root_val` in the range `[start, end]` (inclusive):\n - Recursively call the `generate_trees` function for the left subtree with the range `[start, root_val - 1]` and store the result in `left_trees`.\n - Recursively call the `generate_trees` function for the right subtree with the range `[root_val + 1, end]` and store the result in `right_trees`.\n - Nested loop through each combination of `left_tree` in `left_trees` and `right_tree` in `right_trees`:\n - Create a new `TreeNode` instance with `root_val` as the value, `left_tree` as the left child, and `right_tree` as the right child.\n - Append the new `TreeNode` to the `trees` list.\n - Store the `trees` list in the `memo` dictionary with the key `(start, end)`.\n - Return the `trees` list.\n\n6. Outside the `generate_trees` function, call `generate_trees` initially with arguments `1` and `n` to generate all unique binary search trees with `n` nodes.\n\n7. Return the list of generated trees.\n\nThis algorithm generates all possible unique binary search trees with `n` nodes by considering different ranges of root values and recursively generating left and right subtrees for each possible root value. The `memo` dictionary is used to store previously computed results, reducing redundant calculations and improving the efficiency of the algorithm.\n\n# Complexity\n- Time complexity: O(C(n))\nC is Catalan number.\n\n- Space complexity: O(C(n))\nC is Catalan number.\n\nCatalan number\nhttps://en.wikipedia.org/wiki/Catalan_number\n\n```python []\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def generateTrees(self, n: int) -> List[Optional[TreeNode]]:\n if n == 0:\n return []\n \n memo = {}\n\n def generate_trees(start, end):\n if (start, end) in memo:\n return memo[(start, end)]\n \n trees = []\n if start > end:\n trees.append(None)\n return trees\n \n for root_val in range(start, end + 1):\n left_trees = generate_trees(start, root_val - 1)\n right_trees = generate_trees(root_val + 1, end)\n \n for left_tree in left_trees:\n for right_tree in right_trees:\n root = TreeNode(root_val, left_tree, right_tree)\n trees.append(root)\n \n memo[(start, end)] = trees\n return trees\n\n return generate_trees(1, n)\n```\n```javascript []\n/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = (val===undefined ? 0 : val)\n * this.left = (left===undefined ? null : left)\n * this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {number} n\n * @return {TreeNode[]}\n */\nvar generateTrees = function(n) {\n if (n === 0) {\n return [];\n }\n \n const memo = new Map();\n\n function generateTreesHelper(start, end) {\n if (memo.has(`${start}-${end}`)) {\n return memo.get(`${start}-${end}`);\n }\n \n const trees = [];\n if (start > end) {\n trees.push(null);\n return trees;\n }\n \n for (let rootVal = start; rootVal <= end; rootVal++) {\n const leftTrees = generateTreesHelper(start, rootVal - 1);\n const rightTrees = generateTreesHelper(rootVal + 1, end);\n \n for (const leftTree of leftTrees) {\n for (const rightTree of rightTrees) {\n const root = new TreeNode(rootVal, leftTree, rightTree);\n trees.push(root);\n }\n }\n }\n \n memo.set(`${start}-${end}`, trees);\n return trees;\n }\n\n return generateTreesHelper(1, n); \n};\n```\n```java []\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public List<TreeNode> generateTrees(int n) {\n if (n == 0) {\n return new ArrayList<>();\n }\n \n Map<String, List<TreeNode>> memo = new HashMap<>();\n\n return generateTreesHelper(1, n, memo); \n }\n\n private List<TreeNode> generateTreesHelper(int start, int end, Map<String, List<TreeNode>> memo) {\n String key = start + "-" + end;\n if (memo.containsKey(key)) {\n return memo.get(key);\n }\n \n List<TreeNode> trees = new ArrayList<>();\n if (start > end) {\n trees.add(null);\n return trees;\n }\n \n for (int rootVal = start; rootVal <= end; rootVal++) {\n List<TreeNode> leftTrees = generateTreesHelper(start, rootVal - 1, memo);\n List<TreeNode> rightTrees = generateTreesHelper(rootVal + 1, end, memo);\n \n for (TreeNode leftTree : leftTrees) {\n for (TreeNode rightTree : rightTrees) {\n TreeNode root = new TreeNode(rootVal);\n root.left = leftTree;\n root.right = rightTree;\n trees.add(root);\n }\n }\n }\n \n memo.put(key, trees);\n return trees;\n }\n}\n```\n```C++ []\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n vector<TreeNode*> generateTrees(int n) {\n if (n == 0) {\n return vector<TreeNode*>();\n }\n \n unordered_map<string, vector<TreeNode*>> memo;\n\n return generateTreesHelper(1, n, memo); \n }\n\nprivate:\n vector<TreeNode*> generateTreesHelper(int start, int end, unordered_map<string, vector<TreeNode*>>& memo) {\n string key = to_string(start) + "-" + to_string(end);\n if (memo.find(key) != memo.end()) {\n return memo[key];\n }\n \n vector<TreeNode*> trees;\n if (start > end) {\n trees.push_back(nullptr);\n return trees;\n }\n \n for (int rootVal = start; rootVal <= end; rootVal++) {\n vector<TreeNode*> leftTrees = generateTreesHelper(start, rootVal - 1, memo);\n vector<TreeNode*> rightTrees = generateTreesHelper(rootVal + 1, end, memo);\n \n for (TreeNode* leftTree : leftTrees) {\n for (TreeNode* rightTree : rightTrees) {\n TreeNode* root = new TreeNode(rootVal);\n root->left = leftTree;\n root->right = rightTree;\n trees.push_back(root);\n }\n }\n }\n \n memo[key] = trees;\n return trees;\n } \n};\n```\n | 79 | 0 | ['Dynamic Programming', 'Backtracking', 'Tree', 'Binary Search Tree', 'Binary Tree', 'C++', 'Java', 'Python3', 'JavaScript'] | 1 |
unique-binary-search-trees-ii | Small C++ solution | small-c-solution-by-tushargupta1999-6l21 | \nclass Solution {\npublic:\n vector<TreeNode*> generateTrees(int n, int s = 1) {\n vector<TreeNode*> ans;\n if(n < s)\n return {nul | tushargupta1999 | NORMAL | 2021-09-02T16:16:29.339907+00:00 | 2021-09-02T16:19:19.114622+00:00 | 4,234 | false | ```\nclass Solution {\npublic:\n vector<TreeNode*> generateTrees(int n, int s = 1) {\n vector<TreeNode*> ans;\n if(n < s)\n return {nullptr};\n\t\t\t\n\t\t// Consider every number in range [s,n] as root \n for(int i=s; i<=n; i++) {\n\t\t\n\t\t\t// generate all possible trees in range [s,i)\n for(auto left: generateTrees(i-1, s)) {\n\t\t\t\n\t\t\t\t// generate all possible trees in range (i,e]\n for(auto right: generateTrees(n, i+1))\n\t\t\t\t\n\t\t\t\t\t// make new trees with i as the root\n ans.push_back(new TreeNode(i, left, right));\n }\n }\n return ans;\n }\n};\n``` | 69 | 0 | ['Recursion', 'C'] | 7 |
unique-binary-search-trees-ii | Recursive python solution | recursive-python-solution-by-shenggu-uvk6 | class Solution(object):\n def generateTrees(self, n):\n """\n :type n: int\n :rtype: List[TreeNode]\n """\n | shenggu | NORMAL | 2015-09-29T22:12:10+00:00 | 2018-10-25T19:29:44.145556+00:00 | 14,851 | false | class Solution(object):\n def generateTrees(self, n):\n """\n :type n: int\n :rtype: List[TreeNode]\n """\n if n == 0:\n return [[]]\n return self.dfs(1, n+1)\n \n def dfs(self, start, end):\n if start == end:\n return None\n result = []\n for i in xrange(start, end):\n for l in self.dfs(start, i) or [None]:\n for r in self.dfs(i+1, end) or [None]:\n node = TreeNode(i)\n node.left, node.right = l, r\n result.append(node)\n return result\n\nUse start/end instead of actual nodes to bosst the program. | 67 | 0 | ['Python'] | 13 |
unique-binary-search-trees-ii | JAVA DP Solution and Brute Force Recursive Solution. | java-dp-solution-and-brute-force-recursi-n4oa | The first method that came to mind was the brute force solution as below. \n\n public List generateTrees(int n) {\n return generateTrees(1,n);\n | coderoath | NORMAL | 2015-04-22T20:15:35+00:00 | 2018-10-06T19:15:20.298440+00:00 | 16,819 | false | The first method that came to mind was the brute force solution as below. \n\n public List<TreeNode> generateTrees(int n) {\n return generateTrees(1,n);\n }\n \n public List<TreeNode> generateTrees(int start,int end){ \n List<TreeNode> trees = new ArrayList<TreeNode>();\n if(start>end){ trees.add(null); return trees;}\n \n for(int rootValue=start;rootValue<=end;rootValue++){\n List<TreeNode> leftSubTrees=generateTrees(start,rootValue-1);\n List<TreeNode> rightSubTrees=generateTrees(rootValue+1,end);\n \n for(TreeNode leftSubTree:leftSubTrees){\n for(TreeNode rightSubTree:rightSubTrees){\n TreeNode root=new TreeNode(rootValue);\n root.left=leftSubTree;\n root.right=rightSubTree;\n trees.add(root);\n }\n }\n }\n return trees;\n }\n\n\n\nThen @6219221 reminded me it is unnecessary to create the BSTs with all brand new nodes. \nAssume you have a list of all BSTs with values from 1 to n-1, every possible way to insert value n only involves changing the right tree (root inclusive) because n is always greater than root.val and the left subtree structure is fixed. So all we gotta do is to create a new copy of the right part of the tree and point the new root.left to the original left subtree. This way we reuse the left tree, which saves time and space.\n\nHow to insert Node n into the right subtree?\nGiven any BST on the n - 1 level, it will be only valid to put n on the root.right, root.right.right or root.right.....right locations and then move the right subtree of n.right...right to become the left child of n, in order to keep n on the right-most position as the greatest value in the tree.\n\nHere is my implementation. Note that I do the dp from [n] back to [n to 1]. Therefore all the right subtree structures are fixed and new values are inserted into the left side, opposite to making BSTs from 1 to [1 to n].\n\n public List<TreeNode> generateTrees(int n) {\n List<TreeNode> res = new ArrayList<>();\n res.add(null);\n for(; n > 0; n--) {\n List<TreeNode> next = new ArrayList<>();\n for(TreeNode node: res) {\n //the special case when Node(n) is root of new tree\n TreeNode root = new TreeNode(n); \n root.right = node;\n next.add(root);\n //while loop inserts new value to every possible position into the left tree side\n while(node != null) {\n TreeNode cRoot = new TreeNode(root.right.val);\n //clone left subtree\n cRoot.left = copyTree(root.right.left);\n //reusing - point new root.right to the original right subtree\n cRoot.right = root.right.right;\n //curr is the cutoff node whose right child will be replaced by the new n \n TreeNode curr = getValNode(cRoot, node.val); \n //place n as curr's right child, make curr's original right child as the left child of n.\n TreeNode tmp = curr.left;\n curr.left = new TreeNode(n);\n curr.left.right = tmp;\n\n next.add(cRoot);\n node = node.left;\n }\n }\n res = next;\n }\n return res;\n }\n private TreeNode getValNode(TreeNode n, int val) { //find the cutoff node in the new tree\n while(n != null) {\n if(n.val == val) break;\n n = n.left;\n }\n return n;\n }\n\n private TreeNode copyTree(TreeNode root) { //clone the right subtree\n if(root == null) return null;\n TreeNode cRoot = new TreeNode(root.val);\n cRoot.left = copyTree(root.left);\n cRoot.right = copyTree(root.right);\n return cRoot;\n } | 66 | 1 | ['Dynamic Programming', 'Recursion', 'Java'] | 14 |
unique-binary-search-trees-ii | Java Recursion Along with Recursion Tree Figure Explanation | java-recursion-along-with-recursion-tree-v6a0 | \nclass Solution {\n public List<TreeNode> generateTrees(int n) {\n if (n == 0) {\n return new ArrayList<>();\n }\n return he | Leonxi | NORMAL | 2021-01-19T00:17:42.126770+00:00 | 2021-01-20T16:21:02.908532+00:00 | 4,106 | false | ```\nclass Solution {\n public List<TreeNode> generateTrees(int n) {\n if (n == 0) {\n return new ArrayList<>();\n }\n return helper(1, n);\n }\n \n private List<TreeNode> helper(int lo, int hi) {\n List<TreeNode> result = new ArrayList<>();\n //base case\n if (lo > hi) {\n result.add(null);\n return result;\n }\n \n //subproblem to reach boootm\n for (int i = lo; i <= hi; i++) {\n List<TreeNode> left = helper(lo, i - 1);\n List<TreeNode> right = helper(i + 1, hi);\n //reconstruct tree from bottom to up\n for (TreeNode l : left) {\n for (TreeNode r : right) {\n TreeNode root = new TreeNode(i);\n root.left = l;\n root.right = r;\n result.add(root);\n }\n }\n }\n //return list of root to last layer\n return result;\n }\n}\n```\n\n | 57 | 0 | ['Recursion', 'Java'] | 4 |
unique-binary-search-trees-ii | [C++] Simple and short | c-simple-and-short-by-acce_l-99o2 | Plz upvote if you like it\n\nclass Solution {\npublic:\n vector<TreeNode*> helper(int start,int end) {\n vector<TreeNode*> v;\n if(start > end) | Acce_l | NORMAL | 2020-06-24T09:51:09.661145+00:00 | 2020-06-24T09:59:57.345394+00:00 | 3,508 | false | ***Plz upvote if you like it***\n```\nclass Solution {\npublic:\n vector<TreeNode*> helper(int start,int end) {\n vector<TreeNode*> v;\n if(start > end) {\n v.push_back(NULL);\n return v;\n }\n for(int i = start; i <= end; i++){\n auto left = helper(start,i-1);\n auto right = helper(i+1,end);\n for(auto l : left) {\n for(auto r : right){\n TreeNode* newNode = new TreeNode(i, l, r);\n v.push_back(newNode);\n }\n }\n }\n return v;\n }\n \n vector<TreeNode*> generateTrees(int n) {\n if(n == 0) \n return vector<TreeNode*>();\n auto ans = helper(1,n);\n return ans;\n }\n};\n``` | 56 | 0 | [] | 5 |
unique-binary-search-trees-ii | 24ms c++ easy understanding solution | 24ms-c-easy-understanding-solution-by-sx-3asn | class Solution {\n private:\n vector<TreeNode*> helper(int start, int end){\n vector<TreeNode*> res;\n if(start > end) {\n | sxycwzwzq | NORMAL | 2016-04-21T22:57:32+00:00 | 2018-10-17T07:10:08.545868+00:00 | 8,358 | false | class Solution {\n private:\n vector<TreeNode*> helper(int start, int end){\n vector<TreeNode*> res;\n if(start > end) {\n res.push_back(NULL);\n return res;\n }\n for(int i = start; i <= end; i++){\n vector<TreeNode*> lefts = helper(start, i - 1);\n vector<TreeNode*> rights = helper(i + 1, end);\n for(int j = 0; j < (int)lefts.size(); j++){\n for(int k = 0; k < (int)rights.size(); k++){\n TreeNode* root = new TreeNode(i);\n root->left = lefts[j];\n root->right = rights[k];\n res.push_back(root);\n }\n }\n }\n return res;\n }\n public:\n vector<TreeNode*> generateTrees(int n) {\n if(n == 0) return vector<TreeNode*>(0);\n return helper(1,n);\n }\n }; | 48 | 0 | ['C++'] | 5 |
unique-binary-search-trees-ii | C++ / Python Simple and Short Recursive Solutions, With Explanation | c-python-simple-and-short-recursive-solu-ru00 | Idea:\nWe will use a recursive helper function that recieves a range (within n) and returns all subtrees in that range.\nWe have a few cases:\n1. if start > end | yehudisk | NORMAL | 2021-09-02T07:49:23.496245+00:00 | 2021-09-02T07:49:23.496287+00:00 | 4,852 | false | **Idea:**\nWe will use a recursive helper function that recieves a range (within n) and returns all subtrees in that range.\nWe have a few cases:\n1. if `start > end`, which is not supposed to happen, we return a list that contains only a null.\n2. if `start == end` it means we reached a leaf and we will return a list containing a tree that has only that node.\n3. Otherwise:\nfor each option of root, we get all possible subtrees with that root for `left` and `right` children.\nThen for each possible pair of `left` and `right` we add to the result a new tree.\n\n**C++:**\n```\nclass Solution {\npublic:\n vector<TreeNode*> rec(int start, int end) {\n vector<TreeNode*> res;\n if (start > end) return {NULL};\n \n if (start == end) return {new TreeNode(start)};\n \n for (int i = start; i <= end; i++) {\n vector<TreeNode*> left = rec(start, i-1), right = rec(i+1, end);\n \n for (auto l : left)\n for (auto r : right)\n res.push_back(new TreeNode(i, l, r));\n }\n return res;\n }\n \n vector<TreeNode*> generateTrees(int n) {\n vector<TreeNode*> res = rec(1, n);\n return res;\n }\n};\n```\n**Python:**\n```\nclass Solution:\n def generateTrees(self, n: int) -> List[TreeNode]:\n def rec(start, end):\n\t\t\n if start > end:\n return [None]\n\t\t\t\t\n if start == end:\n return [TreeNode(start)]\n ret_list = []\n\t\t\t\n for i in range(start, end+1):\n left = rec(start, i-1)\n right = rec(i+1, end)\n for pair in product(left, right):\n ret_list.append(TreeNode(i, pair[0], pair[1]))\n \n return ret_list\n \n res = rec(1,n)\n return res\n```\n**Like it? please upvote!** | 46 | 2 | ['C', 'Python'] | 3 |
unique-binary-search-trees-ii | Simple python solution | simple-python-solution-by-fangkunjnsy-pkjw | class Solution(object):\n def generateTrees(self, n):\n return self.cal([i for i in xrange(1, n+1)])\n \n def cal(self, lst):\n if no | fangkunjnsy | NORMAL | 2015-09-24T07:52:59+00:00 | 2018-10-10T05:34:47.067671+00:00 | 5,236 | false | class Solution(object):\n def generateTrees(self, n):\n return self.cal([i for i in xrange(1, n+1)])\n \n def cal(self, lst):\n if not lst: return [None]\n res=[]\n for i in xrange(len(lst)):\n for left in self.cal(lst[:i]):\n for right in self.cal(lst[i+1:]):\n node, node.left, node.right=TreeNode(lst[i]), left, right\n res+=[node]\n return res | 32 | 2 | [] | 5 |
unique-binary-search-trees-ii | c++ recursive and iterative solutions. Beats 100% and doesn't create Frankenstein trees | c-recursive-and-iterative-solutions-beat-mlu5 | TL;DR\n### Recursive solution\ncpp\n /// Returns all insert orderings of [first, last) that will produce a unique tree when inserted into a tree\n std::vector | christrompf | NORMAL | 2018-09-05T10:31:47.733270+00:00 | 2019-10-14T19:32:20.496371+00:00 | 4,413 | false | # TL;DR\n### Recursive solution\n```cpp\n /// Returns all insert orderings of [first, last) that will produce a unique tree when inserted into a tree\n std::vector<std::vector<int>> unique_orderings(int first, int last)\n {\n std::vector<std::vector<int>> ret;\n if (first == last) {\n ret.emplace_back();\n } else {\n // For each possible root digit\n for (int digit = first; digit != last; ++digit) {\n \n // Get all the orderings to build unique left branches\n auto left_orders = unique_orderings(first, digit);\n \n // Get all the orderings to build unique right branches\n auto right_orders = unique_orderings(digit + 1, last);\n \n // Combine all the possibilities together\n for (auto& left : left_orders) {\n for (auto& right : right_orders) {\n ret.emplace_back(1, digit);\n ret.reserve(left.size() + 1 + right.size());\n std::copy(left.begin(), left.end(), std::back_inserter(ret.back()));\n std::copy(right.begin(), right.end(), std::back_inserter(ret.back()));\n }\n }\n }\n }\n return ret;\n }\n\n vector<TreeNode*> generateTrees(int n) {\n std::vector<TreeNode*> ret;\n \n // Get the orderings that will produce unique unique tress using the numbers from [1, n]\n // For example, when n is 3, will return [[1, 2, 3], [1, 3, 2], [2, 1, 3], [3, 1, 2], [3, 2, 1]].\n // Each ordering will produce a unique tree when inserted from left to right.\n auto orderings = unique_orderings(1, n + 1);\n if (!orderings.front().empty()) {\n std::fill_n(std::back_inserter(ret), orderings.size(), nullptr);\n \n // Make each unique tree by inserting the digits of each orderings into a tree.\n for (int i = 0; i < orderings.size(); ++i) {\n for (auto digit : orderings[i]) {\n TreeNode** curr = &ret[i];\n while (*curr) {\n curr = (digit <= (**curr).val) ? &((**curr).left): &((**curr).right);\n }\n *curr = new TreeNode(digit);\n }\n }\n }\n \n return ret;\n }\n```\n### Iterative solution. Using cache for maximum speed\n```cpp\n vector<TreeNode*> generateTrees(int n) {\n std::vector<TreeNode*> ret;\n \n std::vector<std::vector<std::vector<int>>> patterns(1, std::vector<std::vector<int>>(1));\n \n // Create a template for each level from 0 to n - 1. This lists all the unique patterns for that level. If you take a pattern \n // and create a tree by inserting the digits in order, you will produce a unique tree that no other pattern creates\n for (int lvl = 1; lvl < n; ++lvl) {\n patterns.emplace_back();\n // For each possible root digit\n for (int digit = 1; digit <= lvl; ++digit) {\n // For each possible unique pattern that can be made using digits less than the root\n for (auto& left : patterns[digit - 1]) {\n // For each possible unique pattern that can be made using digits greater than the root\n for (auto& right : patterns[lvl - digit]) {\n patterns[lvl].emplace_back();\n patterns[lvl].reserve(left.size() + 1 + right.size());\n auto it = std::back_inserter(patterns.back().back());\n // Add root\n *it++ = digit;\n \n // Add left branch pattern\n it = std::copy(left.begin(), left.end(), it);\n \n // Add right branch pattern, but offsetting the numbers by the root value\n it = std::generate_n(it, right.size(), [digit, r_it = right.begin()] () mutable { return digit + *r_it++; });\n }\n }\n }\n }\n\n // We now have a template for each level 0 to n - 1. Time to build level n, but this time we must create it as\n // actual trees\n \n // For each possible root digit\n for (int digit = 1; digit <= n; ++digit) {\n // For each possible unique pattern that can be made using digits less than the root\n for (auto& left : patterns[digit - 1]) {\n // For each possible unique pattern that can be made using digits greater than the root\n for (auto& right : patterns[n - digit]) {\n ret.emplace_back(new TreeNode(digit));\n \n // Create left branch\n for (int left_digit : left) {\n TreeNode** curr = &ret.back()->left;\n while (*curr) {\n curr = (left_digit <= (**curr).val) ? &((**curr).left): &((**curr).right);\n }\n *curr = new TreeNode(left_digit);\n }\n \n // Create right branch, remembering to add the offset\n for (int right_digit : right) {\n TreeNode** curr = &ret.back()->right;\n while (*curr) {\n curr = (right_digit + digit <= (**curr).val) ? &((**curr).left): &((**curr).right);\n }\n *curr = new TreeNode(right_digit + digit);\n }\n }\n }\n } \n \n return ret;\n }\n```\n# Details\n### Background\nMy solutions are an expansion of [unique binary search tree](https://leetcode.com/problems/unique-binary-search-trees/discuss/166725/c++-extremely-short-stl-solution.-4-lines.-With-detailed-explaination). The idea being that if you choose a root node _r_, then there are [1, _r_) numbers to use to build the left branch and [_r_ + 1, _n_) numbers to use to build the right branch. Focusing on the left branch for the moment, it is obviously just the same problem except instead of needing to use the numbers [1, _n_], we now use [1, _r_), where _r_ <= _n_. So we have a decreasing, recursive problem. The right branch is actually exactly the same, just with a different offset, starting position.\n\nSo lets get down to how to use this.\n### Recursive solution\nA convient way to represent a unique tree is by indicating the order of numbers to be inserted. For example [1, 2, 3] would be;\n```\n1\n \\\n 2\n \\\n 3\n```\n[3, 1, 2, 4]\n```\n 3\n / \\\n1 4\n \\\n 2\n```\nThis is convient because from above, we will be dividing the numbers around a root. What we\'re aiming for is a list of numbers like `[root, <left branch>, <right branch>]`. This is what the recursive function `unique_orderings` is producing. Given a range [first, last), return all the unique insert orderings for that range. All that is left to do after that is actually build all the trees to return.\n\n**Note: After I implemented my solution, I checked out other peoples solutions. I found a large number of them were returning trees directly from their recursive function. These would then be directly linked to. This results in trees _sharing_ branches. Not something I expect the question is looking for.**\n```cpp\nstd::vector<TreeNode*> branches(...)\n{\n ...\n auto left = branches(...);\n auto right = branches(...);\n for (auto l : left) {\n for (auto r : right) {\n TreeNode* root = new TreeNode(root_val);\n root->left = l; // Every tree points to the _same_ left branch\n root->right = r; // Every tree points to the _same_ right branch\n ...\n }\n }\n}\n```\nIt\'s hard to visualise, in ascii, but the trees [3, 2, 1, 5, 4] and [3, 2, 1, 4, 5] will be linked very stranglely. Using the same node for node _2_.\n```\n -------\\\n /\t \\\n / 3 \\ 3\n \\ / \\ ---/ \\\n 2 5 4\n / / \\\n1 4 5\n```\t \nThis is why I choose to build the trees outside of the recursive function. To avoid such an a quirk.\n### Iterative\nYou will notice that the recursive solution actually generates the same branches over and over again. To make it faster, we could instead cache our branches, so every time the branch options for [1, 4) was requested, the same values would be returned. We can go further than this though. Consider the case of a _n_ = 7 and using a root node of 4. The left branch with use the range [1, 4), while the right branch will need to use [5, 8). The number of options will be the same for both branches as they have the same, just the starting number will be different. My solution uses this to build all branches from a _pattern_, where each node value is offset to adjust for different start values.\n\nThe solution is very fast while still being relatively memory efficent. Once again it doesn\'t create Frankenstein trees that are share branches.\n\n**Please give me a thumbs up if this helped explain this problem for you** | 31 | 5 | ['Recursion', 'C', 'Iterator'] | 3 |
unique-binary-search-trees-ii | Ex-Amazon explains a solution with a video, Python, JavaScript, Java and C++ | ex-amazon-explains-a-solution-with-a-vid-xyht | Intuition\nThere 3 important things. \n\nOne is we try to create subtrees with some range between start(minimum) and end(maximum) value.\n\nSecond is calculatio | niits | NORMAL | 2023-08-05T05:45:16.084187+00:00 | 2023-08-05T14:50:48.368617+00:00 | 4,236 | false | # Intuition\nThere 3 important things. \n\nOne is we try to create subtrees with some range between start(minimum) and end(maximum) value.\n\nSecond is calculation of the range. left range should be between start and current root - 1 as end value because all values of left side must be smaller than current root. right range should be between current root + 1 and end becuase all values on the right side should be greater than current root value.\n\nThrid is we call the same funtion recursively, so it\'s good idea to keep results of current start and end, so that we can use the results later. It\'s time saving.\n\n---\n\n# Solution Video\n## *** Please upvote for this article. *** \n\nhttps://youtu.be/5G-Kwx8Lm5Q\n\n# Subscribe to my channel from here. I have 240 videos as of August 5th\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\n---\n\n# Approach\nThis is based on Python. Other might be different a bit.\n\n1. Define a class `Solution` containing a method `generateTrees` which takes an integer `n` as input and returns a list of optional `TreeNode` objects.\n\n2. Check if `n` is 0. If it is, return an empty list since there are no possible trees with 0 nodes.\n\n3. Initialize an empty dictionary called `memo`. This dictionary will be used to store previously computed results for specific ranges of values to avoid redundant calculations.\n\n4. Define an inner function called `generate_trees` that takes two parameters: `start` and `end`, which represent the range of values for which binary search trees need to be generated.\n\n5. Inside the `generate_trees` function:\n - Check if the tuple `(start, end)` exists as a key in the `memo` dictionary. If it does, return the corresponding value from the `memo` dictionary.\n - Initialize an empty list called `trees`. This list will store the generated trees for the current range.\n - If `start` is greater than `end`, append `None` to the `trees` list, indicating an empty subtree, and return the `trees` list.\n - Loop through each value `root_val` in the range `[start, end]` (inclusive):\n - Recursively call the `generate_trees` function for the left subtree with the range `[start, root_val - 1]` and store the result in `left_trees`.\n - Recursively call the `generate_trees` function for the right subtree with the range `[root_val + 1, end]` and store the result in `right_trees`.\n - Nested loop through each combination of `left_tree` in `left_trees` and `right_tree` in `right_trees`:\n - Create a new `TreeNode` instance with `root_val` as the value, `left_tree` as the left child, and `right_tree` as the right child.\n - Append the new `TreeNode` to the `trees` list.\n - Store the `trees` list in the `memo` dictionary with the key `(start, end)`.\n - Return the `trees` list.\n\n6. Outside the `generate_trees` function, call `generate_trees` initially with arguments `1` and `n` to generate all unique binary search trees with `n` nodes.\n\n7. Return the list of generated trees.\n\nThis algorithm generates all possible unique binary search trees with `n` nodes by considering different ranges of root values and recursively generating left and right subtrees for each possible root value. The `memo` dictionary is used to store previously computed results, reducing redundant calculations and improving the efficiency of the algorithm.\n\n# Complexity\n- Time complexity: O(C(n))\nC is Catalan number.\n\n- Space complexity: O(C(n))\nC is Catalan number.\n\nCatalan number\nhttps://en.wikipedia.org/wiki/Catalan_number\n\n```python []\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def generateTrees(self, n: int) -> List[Optional[TreeNode]]:\n if n == 0:\n return []\n \n memo = {}\n\n def generate_trees(start, end):\n if (start, end) in memo:\n return memo[(start, end)]\n \n trees = []\n if start > end:\n trees.append(None)\n return trees\n \n for root_val in range(start, end + 1):\n left_trees = generate_trees(start, root_val - 1)\n right_trees = generate_trees(root_val + 1, end)\n \n for left_tree in left_trees:\n for right_tree in right_trees:\n root = TreeNode(root_val, left_tree, right_tree)\n trees.append(root)\n \n memo[(start, end)] = trees\n return trees\n\n return generate_trees(1, n)\n```\n```javascript []\n/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = (val===undefined ? 0 : val)\n * this.left = (left===undefined ? null : left)\n * this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {number} n\n * @return {TreeNode[]}\n */\nvar generateTrees = function(n) {\n if (n === 0) {\n return [];\n }\n \n const memo = new Map();\n\n function generateTreesHelper(start, end) {\n if (memo.has(`${start}-${end}`)) {\n return memo.get(`${start}-${end}`);\n }\n \n const trees = [];\n if (start > end) {\n trees.push(null);\n return trees;\n }\n \n for (let rootVal = start; rootVal <= end; rootVal++) {\n const leftTrees = generateTreesHelper(start, rootVal - 1);\n const rightTrees = generateTreesHelper(rootVal + 1, end);\n \n for (const leftTree of leftTrees) {\n for (const rightTree of rightTrees) {\n const root = new TreeNode(rootVal, leftTree, rightTree);\n trees.push(root);\n }\n }\n }\n \n memo.set(`${start}-${end}`, trees);\n return trees;\n }\n\n return generateTreesHelper(1, n); \n};\n```\n```java []\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public List<TreeNode> generateTrees(int n) {\n if (n == 0) {\n return new ArrayList<>();\n }\n \n Map<String, List<TreeNode>> memo = new HashMap<>();\n\n return generateTreesHelper(1, n, memo); \n }\n\n private List<TreeNode> generateTreesHelper(int start, int end, Map<String, List<TreeNode>> memo) {\n String key = start + "-" + end;\n if (memo.containsKey(key)) {\n return memo.get(key);\n }\n \n List<TreeNode> trees = new ArrayList<>();\n if (start > end) {\n trees.add(null);\n return trees;\n }\n \n for (int rootVal = start; rootVal <= end; rootVal++) {\n List<TreeNode> leftTrees = generateTreesHelper(start, rootVal - 1, memo);\n List<TreeNode> rightTrees = generateTreesHelper(rootVal + 1, end, memo);\n \n for (TreeNode leftTree : leftTrees) {\n for (TreeNode rightTree : rightTrees) {\n TreeNode root = new TreeNode(rootVal);\n root.left = leftTree;\n root.right = rightTree;\n trees.add(root);\n }\n }\n }\n \n memo.put(key, trees);\n return trees;\n }\n}\n```\n```C++ []\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n vector<TreeNode*> generateTrees(int n) {\n if (n == 0) {\n return vector<TreeNode*>();\n }\n \n unordered_map<string, vector<TreeNode*>> memo;\n\n return generateTreesHelper(1, n, memo); \n }\n\nprivate:\n vector<TreeNode*> generateTreesHelper(int start, int end, unordered_map<string, vector<TreeNode*>>& memo) {\n string key = to_string(start) + "-" + to_string(end);\n if (memo.find(key) != memo.end()) {\n return memo[key];\n }\n \n vector<TreeNode*> trees;\n if (start > end) {\n trees.push_back(nullptr);\n return trees;\n }\n \n for (int rootVal = start; rootVal <= end; rootVal++) {\n vector<TreeNode*> leftTrees = generateTreesHelper(start, rootVal - 1, memo);\n vector<TreeNode*> rightTrees = generateTreesHelper(rootVal + 1, end, memo);\n \n for (TreeNode* leftTree : leftTrees) {\n for (TreeNode* rightTree : rightTrees) {\n TreeNode* root = new TreeNode(rootVal);\n root->left = leftTree;\n root->right = rightTree;\n trees.push_back(root);\n }\n }\n }\n \n memo[key] = trees;\n return trees;\n } \n};\n```\n | 26 | 0 | ['C++', 'Java', 'Python3', 'JavaScript'] | 1 |
unique-binary-search-trees-ii | 【Video】3 important points | video-3-important-points-by-niits-29nc | Intuition\nThere 3 important things. \n\nOne is we try to create subtrees with some range between start(minimum) and end(maximum) value.\n\nSecond is calculatio | niits | NORMAL | 2024-05-23T17:11:54.362202+00:00 | 2024-05-23T17:11:54.362235+00:00 | 3,738 | false | # Intuition\nThere 3 important things. \n\nOne is we try to create subtrees with some range between start(minimum) and end(maximum) value.\n\nSecond is calculation of the range. left range should be between start and current root - 1 as end value because all values of left side must be smaller than current root. right range should be between current root + 1 and end becuase all values on the right side should be greater than current root value.\n\nThrid is we call the same funtion recursively, so it\'s good idea to keep results of current start and end, so that we can use the results later. It\'s time saving.\n\n---\n\n# Solution Video\n## *** Please upvote for this article. *** \n\nhttps://youtu.be/5G-Kwx8Lm5Q\n\n# Subscribe to my channel from here. I have 240 videos as of August 5th\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\n---\n\n# Approach\nThis is based on Python. Other might be different a bit.\n\n1. Define a class `Solution` containing a method `generateTrees` which takes an integer `n` as input and returns a list of optional `TreeNode` objects.\n\n2. Check if `n` is 0. If it is, return an empty list since there are no possible trees with 0 nodes.\n\n3. Initialize an empty dictionary called `memo`. This dictionary will be used to store previously computed results for specific ranges of values to avoid redundant calculations.\n\n4. Define an inner function called `generate_trees` that takes two parameters: `start` and `end`, which represent the range of values for which binary search trees need to be generated.\n\n5. Inside the `generate_trees` function:\n - Check if the tuple `(start, end)` exists as a key in the `memo` dictionary. If it does, return the corresponding value from the `memo` dictionary.\n - Initialize an empty list called `trees`. This list will store the generated trees for the current range.\n - If `start` is greater than `end`, append `None` to the `trees` list, indicating an empty subtree, and return the `trees` list.\n - Loop through each value `root_val` in the range `[start, end]` (inclusive):\n - Recursively call the `generate_trees` function for the left subtree with the range `[start, root_val - 1]` and store the result in `left_trees`.\n - Recursively call the `generate_trees` function for the right subtree with the range `[root_val + 1, end]` and store the result in `right_trees`.\n - Nested loop through each combination of `left_tree` in `left_trees` and `right_tree` in `right_trees`:\n - Create a new `TreeNode` instance with `root_val` as the value, `left_tree` as the left child, and `right_tree` as the right child.\n - Append the new `TreeNode` to the `trees` list.\n - Store the `trees` list in the `memo` dictionary with the key `(start, end)`.\n - Return the `trees` list.\n\n6. Outside the `generate_trees` function, call `generate_trees` initially with arguments `1` and `n` to generate all unique binary search trees with `n` nodes.\n\n7. Return the list of generated trees.\n\nThis algorithm generates all possible unique binary search trees with `n` nodes by considering different ranges of root values and recursively generating left and right subtrees for each possible root value. The `memo` dictionary is used to store previously computed results, reducing redundant calculations and improving the efficiency of the algorithm.\n\n# Complexity\n- Time complexity: O(C(n))\nC is Catalan number.\n\n- Space complexity: O(C(n))\nC is Catalan number.\n\nCatalan number\nhttps://en.wikipedia.org/wiki/Catalan_number\n\n```python []\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def generateTrees(self, n: int) -> List[Optional[TreeNode]]:\n if n == 0:\n return []\n \n memo = {}\n\n def generate_trees(start, end):\n if (start, end) in memo:\n return memo[(start, end)]\n \n trees = []\n if start > end:\n trees.append(None)\n return trees\n \n for root_val in range(start, end + 1):\n left_trees = generate_trees(start, root_val - 1)\n right_trees = generate_trees(root_val + 1, end)\n \n for left_tree in left_trees:\n for right_tree in right_trees:\n root = TreeNode(root_val, left_tree, right_tree)\n trees.append(root)\n \n memo[(start, end)] = trees\n return trees\n\n return generate_trees(1, n)\n```\n```javascript []\n/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = (val===undefined ? 0 : val)\n * this.left = (left===undefined ? null : left)\n * this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {number} n\n * @return {TreeNode[]}\n */\nvar generateTrees = function(n) {\n if (n === 0) {\n return [];\n }\n \n const memo = new Map();\n\n function generateTreesHelper(start, end) {\n if (memo.has(`${start}-${end}`)) {\n return memo.get(`${start}-${end}`);\n }\n \n const trees = [];\n if (start > end) {\n trees.push(null);\n return trees;\n }\n \n for (let rootVal = start; rootVal <= end; rootVal++) {\n const leftTrees = generateTreesHelper(start, rootVal - 1);\n const rightTrees = generateTreesHelper(rootVal + 1, end);\n \n for (const leftTree of leftTrees) {\n for (const rightTree of rightTrees) {\n const root = new TreeNode(rootVal, leftTree, rightTree);\n trees.push(root);\n }\n }\n }\n \n memo.set(`${start}-${end}`, trees);\n return trees;\n }\n\n return generateTreesHelper(1, n); \n};\n```\n```java []\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public List<TreeNode> generateTrees(int n) {\n if (n == 0) {\n return new ArrayList<>();\n }\n \n Map<String, List<TreeNode>> memo = new HashMap<>();\n\n return generateTreesHelper(1, n, memo); \n }\n\n private List<TreeNode> generateTreesHelper(int start, int end, Map<String, List<TreeNode>> memo) {\n String key = start + "-" + end;\n if (memo.containsKey(key)) {\n return memo.get(key);\n }\n \n List<TreeNode> trees = new ArrayList<>();\n if (start > end) {\n trees.add(null);\n return trees;\n }\n \n for (int rootVal = start; rootVal <= end; rootVal++) {\n List<TreeNode> leftTrees = generateTreesHelper(start, rootVal - 1, memo);\n List<TreeNode> rightTrees = generateTreesHelper(rootVal + 1, end, memo);\n \n for (TreeNode leftTree : leftTrees) {\n for (TreeNode rightTree : rightTrees) {\n TreeNode root = new TreeNode(rootVal);\n root.left = leftTree;\n root.right = rightTree;\n trees.add(root);\n }\n }\n }\n \n memo.put(key, trees);\n return trees;\n }\n}\n```\n```C++ []\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n vector<TreeNode*> generateTrees(int n) {\n if (n == 0) {\n return vector<TreeNode*>();\n }\n \n unordered_map<string, vector<TreeNode*>> memo;\n\n return generateTreesHelper(1, n, memo); \n }\n\nprivate:\n vector<TreeNode*> generateTreesHelper(int start, int end, unordered_map<string, vector<TreeNode*>>& memo) {\n string key = to_string(start) + "-" + to_string(end);\n if (memo.find(key) != memo.end()) {\n return memo[key];\n }\n \n vector<TreeNode*> trees;\n if (start > end) {\n trees.push_back(nullptr);\n return trees;\n }\n \n for (int rootVal = start; rootVal <= end; rootVal++) {\n vector<TreeNode*> leftTrees = generateTreesHelper(start, rootVal - 1, memo);\n vector<TreeNode*> rightTrees = generateTreesHelper(rootVal + 1, end, memo);\n \n for (TreeNode* leftTree : leftTrees) {\n for (TreeNode* rightTree : rightTrees) {\n TreeNode* root = new TreeNode(rootVal);\n root->left = leftTree;\n root->right = rightTree;\n trees.push_back(root);\n }\n }\n }\n \n memo[key] = trees;\n return trees;\n } \n};\n```\n | 25 | 0 | ['C++', 'Java', 'Python3', 'JavaScript'] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.