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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
reveal-cards-in-increasing-order | [Java] Easy 100% solution using a queue + explanation | java-easy-100-solution-using-a-queue-exp-qrcj | \nclass Solution {\n public int[] deckRevealedIncreasing(int[] deck) {\n Arrays.sort(deck);\n\n Queue<Integer> queue = new LinkedList<>();\n\n | YTchouar | NORMAL | 2024-02-08T06:56:14.585280+00:00 | 2024-02-08T06:56:14.585299+00:00 | 338 | false | ```\nclass Solution {\n public int[] deckRevealedIncreasing(int[] deck) {\n Arrays.sort(deck);\n\n Queue<Integer> queue = new LinkedList<>();\n\n for(int i = deck.length - 1; i >= 0; --i) {\n if(queue.size() > 0)\n queue.add(queue.poll());\n queue.add(deck[i]);\n }\n\n for(int i = deck.length - 1; i >= 0; --i)\n deck[i] = queue.poll();\n\n return deck;\n }\n}\n\n// Example 1\n// [1, 2, 3, 4, 5] <- Order we want to pick cards\n// [1, 5, 2, 4, 3] <- Order we need\n// [2, 4, 3, 5] <- Remove 1, move 5 to the end\n// [3, 5, 4] <- Remove 2, move 4 to the end\n// [4, 5] <- Remove 3, move 5 to the end\n// [5] <- remove 4, move 5 to the end\n// [] <- remove 5\n\n// Example 2\n// [1, 2, 3, 4, 5, 6] <- Order we want to pick cards\n// [1, 4, 2, 6, 3, 5] <- Order we need\n// [2, 6, 3, 5, 4] <- Remove 1, move 4 to the end\n// [3, 5, 4, 6] <- Remove 2, move 6 to the end\n// [4, 6, 5] <- Remove 3, move 5 to the end\n// [5, 6] <- remove 4, move 6 to the end\n// [6] <- remove 5, move 6 to the end\n// [] <- remove 6\n\n// What we learn from the examples above is that even indexes are increasing\n// The odd ones depend on the number of moves we can do\n// To get the order we need to do a simulation, best way to do that\n// Is to use a queue to simulate the game (inverse order, so decreasing order)\n// The queue will allow us to remove a card and place it at the end\n// Using queue.add(queue.poll())\n// Basically what we\'re doing is the opposite of what we were doing in the examples\n``` | 4 | 0 | ['Java'] | 0 |
reveal-cards-in-increasing-order | Ruby Solution | ruby-solution-by-purandhar999-6ufz | \n# Code\n\ndef deck_revealed_increasing(deck)\n res = [deck.sort!.pop]\n deck.reverse_each { |x| res = [x, res.pop] + res }\n res\nend\n | Purandhar999 | NORMAL | 2023-11-24T06:47:23.695253+00:00 | 2023-11-24T06:47:23.695276+00:00 | 48 | false | \n# Code\n```\ndef deck_revealed_increasing(deck)\n res = [deck.sort!.pop]\n deck.reverse_each { |x| res = [x, res.pop] + res }\n res\nend\n``` | 4 | 0 | ['Ruby'] | 0 |
reveal-cards-in-increasing-order | ----- Beginner friendly approach 4 lines of logic code with 0ms + Notes ----- | beginner-friendly-approach-4-lines-of-lo-5lvo | Have a look at the pattern before moving to the code - \n\ninput array - [17,13,11,2,3,5,7]\nsorted array - [2,3,5,7,11,13,17]\noutput array -[2,13,3,11,5,17,7] | HarryBad | NORMAL | 2022-09-01T11:27:48.010941+00:00 | 2022-09-01T12:18:20.031285+00:00 | 586 | false | Have a look at the pattern before moving to the code - \n\ninput array - [17,13,11,2,3,5,7]\nsorted array - [2,3,5,7,11,13,17]\noutput array -[2,13,3,11,5,17,7]\n\nHave a look at this pattern (taken from explanation) - \n\n[17] -pick the (n-1)th element from sorted array and add to front.\n[13,17]. - again pick the (n-2)th element and add to front\n[11,17,13] - move the last element(13) to the front , pop it from back and pick (n-3)rd elemnt from array and add to front .\n[7,13,11,17] - move the last element(17) to the front , pop it from back and pick (n-4)th elemnt from array and add to front \n[5,17,7,13,11]\n[3,11,5,17,7,13]\n[2,13,3,11,5,17,7]\n\n\n\n----------------------------UPVOTE --------------------------------\n\n\n```\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) \n {\n int n = deck.size();\n sort(deck.begin(),deck.end()); //sort the array \n deque<int>dq;\n vector<int>ans;\n for(int i=n-1;i>=0;i--)\n {\n\t\t//if condition applies after the addition of two elements to the deque\n if(dq.size()>=2)\n {\n dq.push_front(dq.back());\n dq.pop_back();\n }\n dq.push_front(deck[i]);\n }\n\t\t\n\t\t//just add the deque to the vector\n\t\t\n while(!(dq.empty()))\n {\n ans.push_back(dq.front());\n dq.pop_front();\n }\n return ans;\n }\n};\n```\n\n | 4 | 0 | ['Queue', 'C++'] | 0 |
reveal-cards-in-increasing-order | C++ || reverse engineering || Deque | c-reverse-engineering-deque-by-mr_optimi-hwaa | We will appreach this question in reverse order.\nAs we want to reveal in sorted orde (smaller to larger), we sort the vector in (larger to smaller).\nNow in pl | mr_optimizer | NORMAL | 2021-10-14T15:40:12.253653+00:00 | 2021-10-14T15:40:12.253689+00:00 | 275 | false | We will appreach this question in reverse order.\nAs we want to reveal in sorted orde (smaller to larger), we sort the vector in (larger to smaller).\nNow in place of revealing from front, we push new the card in front, and in place of pushing our card from top to bottom, we take card from back and put in onto top.\n\n```\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n sort(deck.begin(),deck.end(),greater<int>());\n deque<int>dq;\n dq.push_back(deck[0]); //taking card of largest value at bottom, so it will revealed at last. \n for(int i=1;i<deck.size();i++){\n dq.push_front(dq.back()); //moving back card to top;\n dq.pop_back();\n dq.push_front(deck[i]); //taking new card on top.\n }\n vector<int>answer(dq.begin(),dq.end());\n return answer;\n }\n\t\n | 4 | 0 | ['Queue', 'C'] | 0 |
reveal-cards-in-increasing-order | c++ 8ms simple solution | c-8ms-simple-solution-by-kkchengaf-7kju | Basically after placing a number in answer array, just leave one empty space to represent an unrevealed card, repeat the process and fill up all empty space lat | kkchengaf | NORMAL | 2020-02-10T03:00:15.787330+00:00 | 2020-02-10T03:00:30.831944+00:00 | 699 | false | Basically after placing a number in answer array, just leave one empty space to represent an unrevealed card, repeat the process and fill up all empty space later in the same manner. Below is a direct implementation of the idea. \n\n```\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n sort(deck.begin(), deck.end());\n vector<int> res(deck.size(), 0);\n int i=0;\n bool skipped = true;\n\t\t\n //every time fill up half of empty space\n //O(nlogn) here\n while(i<deck.size()) {\n for(int j=0;j<res.size();j++)\n if(res[j]==0){\n if(skipped){\n res[j] = deck[i++];\n skipped = false;\n }\n else\n skipped = true;\n }\n }\n return res;\n }\n};\n``` | 4 | 0 | ['C', 'C++'] | 1 |
reveal-cards-in-increasing-order | 100%%%% beatsssss Easy Solution very very very veryyyyyyyyyyyyy | 100-beatsssss-easy-solution-very-very-ve-oxjw | Intuition\nDesi approch\nSee the explannation of the testcase.\nLook.(From below of the testcase)\nYou see the pattern that new number from the vector in increa | ShivanshGoel1611 | NORMAL | 2024-06-24T08:34:16.312146+00:00 | 2024-06-24T08:34:16.312182+00:00 | 6 | false | # Intuition\n*Desi approch*\nSee the explannation of the testcase.\nLook.(From below of the testcase)\nYou see the pattern that new number from the vector in increasing order come in the new array and the back element of previous array is next one of new array and rest from starting of previous array come as\nitis...\nYesss YOU ARE CORRECT WE USE DEQUE \nWHY???\nIT GIVE US THE FLEXIBILITY OF FOUR OPERATIONS \npush_front\npush_back\npop_back\npop_front\nNow dry run my solution you can easily understand!!!!1\n#Goel approach\nThank you \n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\n(O(n))\nfor deque space.....\n# Code\n```\n***class Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n deque<int> dq;\n int n = deck.size();\n sort(deck.begin(), deck.end(), [](int a, int b) { return a > b; });\n if(deck.size()==1)\n {\n return {deck[0]};\n }\n dq.push_front(deck[0]);\n dq.push_front(deck[1]);\n \n for (int i = 2; i < deck.size(); i++) {\n int back = dq.back();\n dq.pop_back();\n dq.push_front(back);\n dq.push_front(deck[i]);\n }\n vector<int> ans(dq.begin(), dq.end());\n\n return ans;\n }\n};***\n``` | 3 | 0 | ['Queue', 'C++'] | 0 |
reveal-cards-in-increasing-order | ✅✅FULL DETAILED EXPLANATION ||BEATS 98 PERCENT✅✅ | full-detailed-explanation-beats-98-perce-7pbe | Intuition\n Describe your first thoughts on how to solve this problem. \n# guys you need to fry run pls upvote man , I write so much and you guys are so weirs y | Abhishekkant135 | NORMAL | 2024-04-10T17:58:25.018870+00:00 | 2024-04-10T17:58:25.018926+00:00 | 26 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n# guys you need to fry run pls upvote man , I write so much and you guys are so weirs you dont even upvote me.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n\n**Steps:**\n\n1. **Initialization:**\n - `int n = deck.length`: Stores the number of cards (`n`) in the deck.\n - `int[] result = new int[n]`: Creates a new integer array `result` of size `n` to store the revealed card order. Initially, all elements in `result` are set to 0.\n - `boolean skip = false`: Initializes a boolean variable `skip` to `false`, which is used to control the reveal pattern.\n\n2. **Sorting the Deck:**\n - `Arrays.sort(deck)`: Sorts the `deck` array in ascending order. This ensures that the cards with lower values are revealed earlier in the process.\n\n3. **Revealing Cards:**\n - The `while` loop iterates until all cards (`i < n`) have been processed from the `deck` array.\n - **Checking Empty Slot in Result:**\n - `if (result[j] == 0)`: This condition checks if the current position (`j`) in the `result` array is empty (not filled with a revealed card value yet).\n - **Revealing a Card (if not skipped):**\n - `if (!skip)`: This condition checks if the `skip` flag is not set (`false`). If it\'s not skipped, a card will be revealed.\n - `result[j] = deck[i]`: Sets the value at the current position (`j`) in the `result` array to the card value from the `deck` at index `i`. This effectively reveals the card.\n - `i++`: Increments `i` to move to the next card in the `deck` for revealing.\n - **Toggling Skip Flag:**\n - `skip = !skip`: Sets the `skip` flag to the opposite of its current value. This controls the alternating reveal pattern (reveal, skip, reveal, skip, ...).\n\n4. **Updating Result Index:**\n - `j = (j + 1) % n`: Updates the index `j` for the `result` array. The modulo operation `% n` ensures it wraps around to the beginning (0) after reaching the end (`n-1`). This creates a circular pattern for filling the `result` array.\n\n5. **Returning the Result:**\n - After the loop completes, the `result` array will contain the revealed card order following the alternating reveal rule. The function returns the `result` array.\n\n**Key Points:**\n\n- Sorting the deck ensures cards with lower values are revealed first.\n- The `skip` flag controls the alternating reveal pattern.\n- The modulo operation in updating `j` creates a circular filling pattern for the `result` array.\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n- Sorting the deck dominates the time complexity, which is O(n log n) in most sorting algorithms used in Java\'s `Arrays.sort`.\n- The loop iterates through the deck (`n` elements) and has constant time operations within it.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n- The space complexity is O(n) due to the creation of the `result` array to store the revealed card order.\n# Code\n```\nclass Solution {\n public int[] deckRevealedIncreasing(int[] deck) {\n int n = deck.length;\n int[] result = new int[n];\n \n boolean skip = false;\n \n int i = 0; // deck\n int j = 0; // result\n \n Arrays.sort(deck);\n \n while (i < n) {\n if (result[j] == 0) { // khali hai\n if (!skip) {\n result[j] = deck[i];\n i++;\n }\n \n skip = !skip; // alternate\n }\n \n j = (j + 1) % n;\n }\n \n return result;\n }\n}\n``` | 3 | 0 | ['Simulation', 'Java'] | 0 |
reveal-cards-in-increasing-order | E☠💀💯 Faster✅💯Lesser🧠🎯C++✅Python3✅Java✅C✅Python✅💥🔥💫Explained☠💥🔥 Beats 💯 | e-fasterlessercpython3javacpythonexplain-svaa | Intuition\n\n\n\n\nC++ []\n#define ll long long\n#define vi vector<int>\n#define vvi vector<vi>\n#define vl vector<long>\n#define vvl vector<vl>\n#define all(n) | Edwards310 | NORMAL | 2024-04-10T15:22:44.965107+00:00 | 2024-05-03T16:13:36.741514+00:00 | 47 | false | # Intuition\n\n\n\n\n```C++ []\n#define ll long long\n#define vi vector<int>\n#define vvi vector<vi>\n#define vl vector<long>\n#define vvl vector<vl>\n#define all(n) n.begin(), n.end()\n#define mii mp<int, int>\n#define mivi map<int, vi>\n#define umii unordered_map<int, int>\n#define qi deque<int>\n#define loop(i, n) for (int i = 0; i < n; i++)\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n vi sorted_copy = deck;\n sort(all(sorted_copy));\n\n int n = deck.size();\n vi ans(n);\n vector<bool> already_inserted(n, false);\n bool should_insert = true;\n int j = 0;\n for (int i = 0; j < n; i++) {\n i %= n;\n if (should_insert & !already_inserted[i]) {\n already_inserted[i] = true;\n ans[i] = sorted_copy[j++];\n should_insert ^= 1;\n } else if (!already_inserted[i])\n should_insert ^= 1;\n }\n return ans;\n }\n};\n```\n```python3 []\nclass Solution:\n def deckRevealedIncreasing(self, deck: List[int]) -> List[int]:\n sz = len(deck)\n res = [0] * sz\n q = deque()\n for i in range(sz):\n q.append(i)\n deck.sort()\n for card in deck:\n res[q.popleft()] = card\n if q:\n q.append(q.popleft())\n return res\n```\n```Java []\nclass Solution {\n public int[] deckRevealedIncreasing(int[] deck) {\n Arrays.sort(deck);\n Queue<Integer> q = new LinkedList<>();\n for (int i = 0; i < deck.length; i++) {\n q.add(i);\n }\n int[] res = new int[deck.length];\n int index = 0;\n while (!q.isEmpty()) {\n res[q.poll()] = deck[index++];\n if (!q.isEmpty())\n q.offer(q.poll());\n }\n return res;\n }\n}\n```\n```C []\n/**\n * Note: The returned array must be malloced, assume caller calls free().\n */\nint* deckRevealedIncreasing(int* deck, int deckSize, int* returnSize) {\n *returnSize = deckSize;\n int* array = calloc(deckSize, sizeof(int));\n int i, j, key, up = 1, front;\n for (i = 1; i < deckSize; i++) { // Insertion sort\n key = deck[i];\n j = i - 1;\n for (; j >= 0 && deck[j] > key; j--)\n deck[j + 1] = deck[j];\n deck[j + 1] = key;\n }\n for (i = front = 0, up = 1; i < deckSize; front = ++front % deckSize)\n if (!up && !array[front])\n up = !up; // 0 to 1\n else if (up && !array[front]) {\n array[front] = deck[i++];\n up = !up; // 1 to 0;\n }\n return array;\n}\n```\n```python []\nclass Solution(object):\n def deckRevealedIncreasing(self, deck):\n """\n :type deck: List[int]\n :rtype: List[int]\n """\n deck.sort(reverse=True)\n q = deque()\n for i in deck:\n if q:\n q.appendleft(q.pop()) \n q.appendleft(i)\n \n return q\n```\n\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 O(n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(n)\n# Code\n```\nclass Solution:\n def deckRevealedIncreasing(self, deck: List[int]) -> List[int]:\n sz = len(deck)\n res = [0] * sz\n q = deque()\n for i in range(sz):\n q.append(i)\n deck.sort()\n for card in deck:\n res[q.popleft()] = card\n if q:\n q.append(q.popleft())\n return res\n\n```\n# Please upvote if it\'s useful\n\n | 3 | 0 | ['Array', 'Queue', 'C', 'Simulation', 'Python', 'C++', 'Java', 'Python3'] | 1 |
reveal-cards-in-increasing-order | C# Solution for Reveal Cards In Increasing Order Problem | c-solution-for-reveal-cards-in-increasin-eu1e | Intuition\n Describe your first thoughts on how to solve this problem. \nThe intuition behind this solution is to use a queue to keep track of the indices of th | Aman_Raj_Sinha | NORMAL | 2024-04-10T11:12:43.254320+00:00 | 2024-04-10T11:12:43.254347+00:00 | 202 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition behind this solution is to use a queue to keep track of the indices of the result array. By simulating the card revealing process, we assign cards to the corresponding indices in the result array while ensuring that the order is maintained.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1.\tSort the input deck array to ensure the cards are in increasing order.\n2.\tCreate a queue containing the indices of the result array.\n3.\tIterate through the sorted deck array, dequeue an index from the queue, and assign the current card to that index in the result array.\n4.\tIf there are still cards remaining in the deck, enqueue the next index to simulate moving cards to the bottom of the deck.\n5.\tFinally, return the resulting array.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity is O(NlogN) due to the sorting step, where N is the number of cards in the deck. The iteration through the deck array and the operations on the queue take linear time, so they don\u2019t contribute significantly to the overall complexity.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is O(N), where N is the number of cards in the deck. This is due to the extra space used by the queue and the resulting array.\n\n# Code\n```\npublic class Solution {\n public int[] DeckRevealedIncreasing(int[] deck) {\n Array.Sort(deck);\n Queue<int> indexQueue = new Queue<int>(Enumerable.Range(0, deck.Length));\n int[] result = new int[deck.Length];\n \n foreach (int card in deck) {\n result[indexQueue.Dequeue()] = card;\n if (indexQueue.Count > 0) {\n indexQueue.Enqueue(indexQueue.Dequeue());\n }\n }\n \n return result;\n }\n}\n``` | 3 | 0 | ['C#'] | 1 |
reveal-cards-in-increasing-order | Beats 100% users || Easy & beginner friendly approach || O(nlogn) complexity | beats-100-users-easy-beginner-friendly-a-98w8 | \n\n# Intuition\n Describe your first thoughts on how to solve this problem. \nJust observe the pattern backward how cards the drawn from the deck.We have to us | SoumyaAdhikary | NORMAL | 2024-04-10T06:56:58.172387+00:00 | 2024-04-10T07:08:33.217410+00:00 | 94 | false | \n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nJust observe the pattern backward how cards the drawn from the deck.We have to use a dequq to do operations from both front and end.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- By seeing the backward pattern of withdrawn cards that only every last number of the queue comes to front of the queue and the rest are in the same order , then a new card is pushed in front of the queue.\n- This pattern continues till all cards are completed.\n- Thus first sort the cards numbers. Then using a for loop push the last element in front of the queue.When elemnts are already present int he queue,then push the last elemt of the queue in the front and then pop it from back and insert the new card number.\n- Do this step until all cards are traversed from the deck. \n\n# Complexity\n- Time complexity:O(nlogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n\n- Space complexity:O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n int n=deck.size();\n deque<int>ans;\n sort(deck.begin(),deck.end());\n ans.push_back(deck[n-1]);\n for(int i=n-2;i>=0;i--){\n ans.push_front(ans.back());\n ans.pop_back();\n ans.push_front(deck[i]);\n }\n vector<int>ans1;\n for(int i=0;i<ans.size();i++){\n ans1.push_back(ans[i]);\n }\n return ans1;\n }\n};\n```\n\n | 3 | 0 | ['C++'] | 1 |
reveal-cards-in-increasing-order | Simple Bottom-up approach || Simulation || C++ | simple-bottom-up-approach-simulation-c-b-bocd | Intuition\n Describe your first thoughts on how to solve this problem. \nAfter some dry-run, my intuition started out like this. (Bottom-up-approach)\n- conside | Aryan_Marwaha | NORMAL | 2024-04-10T06:28:47.741808+00:00 | 2024-04-10T06:28:47.741841+00:00 | 54 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAfter some dry-run, my intuition started out like this. **(Bottom-up-approach)**\n- consider the rectangular portion to be a sliding window (deque).\n- start from bottom and work up your way to top.\n<div align="center">\n <img src="https://assets.leetcode.com/users/images/c693f36c-e94b-4d6e-a5a1-704b332d2e48_1712730124.656206.jpeg" width=80%>\n</div>\n<hr>\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Sort the input deck vector in increasing order.\n- Initialize a deque to store the cards.\n- Iterate through the sorted deck from the end, pushing elements into the front of the deque in a specific pattern to reveal the cards.\n- Return the elements of the deque as a vector.\n# Complexity\n- **Time complexity:** $$O(n(logn + 1))$$ due to the sorting operation + traversal taken to run simulation.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- **Space complexity:** $$O(n)$$ for the deque, if we exclude space taken by result vector.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n- where **n** is the size of the input deck vector.\n# Code\n```\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n sort(deck.begin(),deck.end());\n deque<int> dq;\n\n int i = deck.size()-1;\n while(i>=0) {\n if(!dq.empty()) {\n dq.push_front(dq.back());\n dq.pop_back();\n }\n dq.push_front(deck[i]);\n i--;\n }\n return vector<int> (dq.begin(),dq.end());\n }\n};\n``` | 3 | 0 | ['Sliding Window', 'Simulation', 'C++'] | 0 |
reveal-cards-in-increasing-order | ✅ Java || Simulation || Time O(nlog(n)) || Space O(n) || Easy Explained ✅ | java-simulation-time-onlogn-space-on-eas-c13k | Intuition\nThe problem asks us to reveal cards in a specific order to make them appear in increasing order when read from left to right. Initially, all cards ar | 0xsonu | NORMAL | 2024-04-10T05:26:25.101599+00:00 | 2024-04-10T05:26:25.101631+00:00 | 26 | false | # Intuition\nThe problem asks us to reveal cards in a specific order to make them appear in increasing order when read from left to right. Initially, all cards are facing down. We need to simulate the process of revealing cards according to the given rules.\n\n# Approach\n1. **Sorting:** First, we sort the given deck of cards in increasing order. This allows us to know the correct order in which the cards should be revealed.\n2. **Simulation:** We simulate the process of revealing cards. We start by creating an array `res` of the same length as the deck to store the revealed cards. We initialize all elements of `res` to 0, indicating that they are facing down.\n3. We use two pointers, `i` and `j`, to iterate through the sorted deck and the result array, respectively. Initially, both pointers are set to 0.\n4. We reveal the cards one by one. At each step:\n - If `res[j]` is 0 (indicating that the card at position `j` is facing down) and we are not skipping the current position, we reveal the card from the sorted deck at index `i`, and increment `i`.\n - If `res[j]` is already revealed (not 0), or we are skipping the current position, we move to the next position in the result array.\n5. We continue this process until all cards are revealed and placed in the correct order in the result array.\n6. Finally, we return the result array containing the revealed cards.\n\n# Complexity\n- Time complexity: \\(O(n \\log n)\\), where \\(n\\) is the number of cards in the deck. This complexity arises due to sorting the deck.\n- Space complexity: \\(O(n)\\) for the result array `res` and other constant space requirements. \n\n# Code\n```java\nclass Solution {\n public int[] deckRevealedIncreasing(int[] deck) {\n int len = deck.length;\n boolean skip = false;\n int[] res = new int[len];\n int i = 0, j = 0;\n Arrays.sort(deck);\n\n while (i < len) {\n if (res[j] == 0 && !skip) {\n res[j] = deck[i++];\n skip = true;\n } else {\n if (res[j] == 0) \n skip = false;\n j = (j + 1) % len;\n }\n }\n return res;\n }\n}\n``` | 3 | 0 | ['Array', 'Queue', 'Sorting', 'Simulation', 'Java'] | 0 |
reveal-cards-in-increasing-order | Python | Easy | python-easy-by-khosiyat-6zku | see the Successfully Accepted Submission\n\n# Code\n\nclass Solution:\n def deckRevealedIncreasing(self, deck: List[int]) -> List[int]:\n # Sort the d | Khosiyat | NORMAL | 2024-04-10T05:18:58.677133+00:00 | 2024-04-10T05:18:58.677151+00:00 | 351 | false | [see the Successfully Accepted Submission](https://leetcode.com/problems/reveal-cards-in-increasing-order/submissions/1228249497/?envType=daily-question&envId=2024-04-10)\n\n# Code\n```\nclass Solution:\n def deckRevealedIncreasing(self, deck: List[int]) -> List[int]:\n # Sort the deck\n deck.sort()\n \n # Initialize a deque to store the indices\n indices = deque(range(len(deck)))\n \n # Initialize the result array\n result = [0] * len(deck)\n \n # Iterate over sorted deck and populate result array\n for card in deck:\n # Take the index of the next unrevealed card\n idx = indices.popleft()\n # Assign the revealed card to the correct position\n result[idx] = card\n \n # If there are still unrevealed cards, move the next unrevealed card to the end\n if indices:\n indices.append(indices.popleft())\n \n return result\n\n```\n\n | 3 | 0 | ['Python3'] | 1 |
reveal-cards-in-increasing-order | ✅ 🔥Interview solution | No Duque/queue | With basic looping | 100% faster ✅ 🔥 | interview-solution-no-duquequeue-with-ba-x89t | Hi,\n\nMy approach is to adhere to the fundamentals and implement our logic, rather than relying on a queue/deque, which may not satisfy the interviewer.\n\nUnd | Surendaar | NORMAL | 2024-04-10T05:17:35.038550+00:00 | 2024-04-10T06:39:04.041760+00:00 | 363 | false | Hi,\n\nMy approach is to adhere to the fundamentals and implement our logic, rather than relying on a queue/deque, which may not satisfy the interviewer.\n\n**Understand:**\nWe need the result array to be in sorted order, so we should place the values such that if we place an element in an empty index, the next element should be placed by skipping another empty index.\n\n**Intution:** \nSo my intuition was to reverse the process, as they mentioned that the resulting array should be in sorted order but with a different picking method: we pick an element and then skip the following element until all elements are added to the resulting array.\n\n**Steps:**\n1. We will go in reverse, first sorting the given array.\n2. Next, we need to place elements in the order specified in the question:\n\t* Place the element in the resulting array if its index is zero.\n\t* Otherwise, find the next index that is zero.\n\t* Skip that index.\n\t* Find the next index that is zero.\n3. Store the value in that index.\n4. Repeat the above two steps until i is equal to the length of the array.\n\n**Kindly do upvote if you find it helpful.. :)**\n\nTime complexity - O(n logn)\nSpace complexity - O(n)\n\n\n```\n public int[] deckRevealedIncreasing(int[] deck) {\n int len=deck.length, i=0, curr=0;\n Arrays.sort(deck);\n boolean skip = false;\n int[] res = new int[len];\n while(i<len){\n while(res[curr]>0 && skip==false){\n curr = getNextIndex(res, curr, len);\n skip = true;\n curr++;\n if(curr==len){\n curr=0;\n }\n curr = getNextIndex(res, curr, len);\n }\n res[curr] = deck[i++];\n skip=false;\n }\n return res;\n }\n\n private int getNextIndex(int[] res, int curr, int len) {\n while(res[curr]>0){\n curr++;\n if(curr==len){\n curr=0;\n }\n }\n return curr;\n } | 3 | 0 | ['Sorting', 'Java'] | 1 |
reveal-cards-in-increasing-order | No Queue Needed, O(1) space, 0ms C++ beats 100% | no-queue-needed-o1-space-0ms-c-beats-100-dhc7 | \n//https://hyper-meta.blogspot.com/\n#pragma GCC target("avx,mmx,sse2,sse3,sse4")\nauto _=[]()noexcept{ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);return 0; | yjian012 | NORMAL | 2024-04-10T03:08:35.710584+00:00 | 2024-04-11T10:02:05.539842+00:00 | 82 | false | ```\n//https://hyper-meta.blogspot.com/\n#pragma GCC target("avx,mmx,sse2,sse3,sse4")\nauto _=[]()noexcept{ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);return 0;}();\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n const int sz=deck.size();\n sort(deck.begin(),deck.end());\n vector<int> r(sz);\n for(int i=(sz+1)/2;i<sz;++i){\n int d=2*(sz-i)-1;\n r[2*sz-1-(d<<(32-__builtin_clz((sz-1)/d)))]=deck[i];\n }\n for(int i=0;i<(sz+1)/2;++i) r[2*i]=deck[i];\n return r; \n }\n};\n```\nExplanation:\n\nMy first idea was the same as many others, i.e. to reverse the process and simulate, which is discussed in many other solutions. Then I tried a different idea.\n\nSo, the question is, given the index of a number in the sorted input, is there a way to tell its final index efficiently?\nLet\'s take a look at how the index of the number changes.\nUsing the example input,\n17 13 11 7 5 3 2,\nthe arrays from the final state to the initial state are:\n```\n17\n13,17\n11,17,13\n7,13,11,17\n5,17,7,13,11\n3,11,5,17,7,13\n2,13,3,11,5,17,7\n```\nLet\'s look at 17\'s index,\n```\n17:\nsiz : 0 1 2 3 4 5 6\nind : 0 1 1 3 1 3 5\n2*siz:0 2 4 6 8 10 12\nchange:-1 -2 -4\n```\nAnd 13\'s,\n```\n13:\nsiz : 1 2 3 4 5 6\nind : 0 2 1 3 5 1\n2*siz:0 2 4 6 8 10\nchange: -3 -6\n```\nHere, `siz` is the size of the array, `ind` is its index in the current array. It\'s easy to tell that:\n- If `ind` is less than `siz`, `ind` increases by 2 in the next step.\n- Otherwise, `ind` becomes 1 in the next step.\n\nThen, how can we find out its final index? Do we just keep computing its next index?\nNo, that would be $O(n)$ for each number, not good.\nBut noticing that it increases by 2 mostly, we can just find out where it resets to 1, and we subtract those changes from what it would be if it increases by 2 all the time!\n\nLet\'s try with an array of 100 elements:\n```\n#include <bits/stdc++.h>\nusing namespace std;\nint main(){\n int sz=100;\n vector<int> szi(sz),ind(sz);\n for(int i=0;i<sz;++i) szi[i]=i;\n for(int st=0;st<sz;++st){\n vector<int> change(sz-st,0);\n ind[st]=0;\n for(int j=st;j<sz-1;){\n if(ind[j]==szi[j]) {change[j-st]=ind[j]+1;ind[++j]=1;}\n else ind[++j]=ind[j]+2;\n }\n cout<<"ind : "; for(int j=st;j<sz;++j) cout<<ind[j]<<",";cout<<endl;\n cout<<"chid: "; for(int j=0;j<sz-st;++j) if(change[j]) cout<<j<<",";cout<<endl;\n cout<<"chan: "; for(int j=0;j<sz-st;++j) cout<<change[j]<<",";cout<<endl<<endl;\n }\n return 0;\n}\n```\nThe sequences created by the largest 3 numbers are,\n```\nind : 0,1,1,3,1,3,5,7,1,3,5,7,9,11,13,15,1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59,61,63,1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59,61,63,65,67,69,71,\nchid: 0,1,3,7,15,31,63,\nchan: 1,2,0,4,0,0,0,8,0,0,0,0,0,0,0,16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,\n\nind : 0,2,1,3,5,1,3,5,7,9,11,1,3,5,7,9,11,13,15,17,19,21,23,1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59,61,63,65,67,69,71,73,75,77,79,81,83,85,87,89,91,93,95,1,3,5,7,\nchid: 1,4,10,22,46,94,\nchan: 0,3,0,0,6,0,0,0,0,0,12,0,0,0,0,0,0,0,0,0,0,0,24,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,48,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,96,0,0,0,0,\n\nind : 0,2,4,1,3,5,7,9,1,3,5,7,9,11,13,15,17,19,1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59,61,63,65,67,69,71,73,75,77,79,1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,\nchid: 2,7,17,37,77,\nchan: 0,0,5,0,0,0,0,10,0,0,0,0,0,0,0,0,0,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,40,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,80,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,\n```\nwhere `ind` is its index in the array, `chan` is the change in the index when it resets to 1, and `chid` is the index where reset happens.\n\nIt\'s easy to tell that the `chid`s are\n0, then *2+1 every time\n1, then *2+2 every time\n2, then *2+3 every time\n...\nAnd the `chan`s are\n1,2,4... and *2 every time\n3,6,12... and *2 every time\n5,10,20... and *2 every time\n\nWe stop when `chid` is out of range.\n```\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n const int sz=deck.size();\n sort(deck.begin(),deck.end());\n vector<int> r(sz);\n for(int i=sz/2;i<sz;++i){\n int st=sz-i,chid=st-1,chan=2*st-1,sum=0;\n while(chid<i){\n sum+=chan;\n chan*=2;\n chid=chid*2+st;\n }\n r[2*i-sum]=deck[i];\n }\n for(int i=0;i<sz/2;++i) r[2*i]=deck[i];\n return r; \n }\n};\n```\nSince the index grows exponentially, it\'s $O(\\log n)$ for each number. And it\'s easy to see that the first half of the numbers just move to `2*i`, so only half of the numbers need to be calculated.\n\nThe part after the sorting is $O(n\\log n)$, but it doesn\'t require allocation or deallocation of extra storages, in contrast to the `queue` solution.\nAnother advantage of this algorithm is, it can be easily parallelized, where the part after sorting becomes $O(\\log n)$.\n\n# Update\nActually, the sum can be found in $O(1)$.\nGiven\n$a_n=2a_{n-1}+k$,\nit\'s not hard to find that \n$a_n=-k+(a_0+k)2^{n}$\nAnd the sum is just $(a_0+k)(2^{n}-1)$\nWe just need to find the maximum $n$ such that $a_n$ lies within range, $a_n< i$.\nAnd this condition converts to finding the highest set bit of $(i+k)/(a_0+k)$.\nThus, the result becomes\n```\n int k=32-__builtin_clz((i+st-1)/(2*st-1));\n int sum=(2*st-1)*((1<<k)-1);\n r[2*i-sum]=deck[i];\n```\nWith some simplification, I got the code in the beginning.\nThis is probably the most efficient algorithm? If run in parallel, it becomes $O(1)$ after sorting.\n\nWhat\'s more, since this is one-one index mapping, it can be done in place, and return the modified input. The following is an implementation of this:\n```\n//https://hyper-meta.blogspot.com/\n#pragma GCC target("avx,mmx,sse2,sse3,sse4")\nauto _=[]()noexcept{ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);return 0;}();\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n const int sz=deck.size();\n sort(deck.begin(),deck.end());\n for(int st=1;st<sz;++st){\n if(deck[st]<0) continue;\n int i=st,d=2*(sz-i)-1,nxti=sz-1<d? 2*i : 2*sz-1-(d<<(32-__builtin_clz((sz-1)/d)));\n int cur=deck[i],nxt=deck[nxti];\n while(nxti!=st){\n deck[nxti]=-cur;\n i=nxti;\n d=2*(sz-i)-1;\n nxti=sz-1<d? 2*i : 2*sz-1-(d<<(32-__builtin_clz((sz-1)/d)));\n cur=nxt;\n nxt=deck[nxti];\n }\n deck[st]=-cur;\n }\n for(int i=1;i<sz;++i) deck[i]=-deck[i];\n return deck; \n }\n};\n``` | 3 | 0 | ['C++'] | 0 |
reveal-cards-in-increasing-order | Strictly O(N) Math Solution W/O any queue | strictly-on-math-solution-wo-any-queue-b-rkr5 | Intuition\n Describe your first thoughts on how to solve this problem. \nEvery time we are removing half of the cards we just have to figure out which those car | arnavbssaini | NORMAL | 2023-09-04T19:35:15.933672+00:00 | 2023-09-04T19:56:22.159671+00:00 | 239 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nEvery time we are removing half of the cards we just have to figure out which those cards are.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nTake the very first cycle, we will reveal all the even numbered index card 0,2,4,6,8,.....\n\nWe are initially assigning cards from the deck to indices start from 0 in steps of 2.\n\nIn the very next cycle of reveals we will assign cards from the deck in steps of 4 (steps of 8 in the next cycle), starting from -->>> This we still need to figure out.\n\nBy solving few even powered test cases (n= 4,8,16...) on pen and paper we can figure out that the starts for each cycle will be 0,1,3,7.. and so on. \n\nMathamatically speaking:\n\nSay all indices available initailly 0,1,2,3,4,...,n. We have 2 groups of indices A\' --->>> 2n\' (where n\' = 0,1,2,3,4,5..) and B\' --->>> 2n\' + 1 (where n\' = 0,1,2,3,4,5..). We assign cards from the deck to the first group (A\') in the first cycle.\n\nNow we are left with \n\n2n\' + 1 (where n\' = 0,1,2,3,4,5..) \n\n OR\n\nA" --->>>> 4n" + 1 (where n" = 0,1,2,3,4,5..) and B" --->>> 4n" + 3 (where n" = 0,1,2,3,4,5..)\n\nWe will assign cards to indices to the group A".\n\nNow again we are left with group B" --->>> 4n" + 3 indices (where n" = 0,1,2,3,4,5..)\n\nNext we will assign cards on indeces in group A"\' --->>> 8n"\' + 3 (where n"\' = 0,1,2,3,4,5..) AND be left with B"\' ---->>> 8n"\' + 7 and so on.\n\nIts a breeze when we have to assign cards to even number of indecies in a cycle, the real tricky part is to figure out the starts and the END when we have to assign odd number of indices in a cycle.\n\nSay we have a deck of cards and we reveal even number of cards from the deck, the relative order of the remaining cards remains unchanged. BUT when we reveal odd number of cards from the deck the relative order of the remaining cards is slightly changed.\n\nInitial deck:\nA,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z\n\nFirst cycle:\nEven number of cards revealed:\nA,C,E,G,I,K,M,O,Q,S,U,W,Y\nCards remaining in deck in order:\nB,D,F,H,J,L,N,P,R,T,V,X,Z\n\nSecond cycle:\nOdd number of cards revealed:\nB,F,J,N,R,V,Z\nCards remaining in deck in order:\nH,L,P,T,X,D\n\nSee how the D ends up in the end. This is taken care by the variable \'kata\'. \n\'kata\' is only created and used (if it was created in any of the previous cycle) when we have to reveal odd number of cards. Cycles which reveal even number of cards leave \'kata\' alone.\n\nDon\'t ask why this variable name, we all have our own way of coping from heartbreaks :P\n\nI will edit this post to a more well formated solution and more detailed explaination, feel free to fire away in the comments section for questions and suggestions. And if you find this interesting please upvote :D !!\n\n\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n) (without the sorting time obviously. Figuring out that we need a sorted array for this question is not the key point of this question/solution. We might as well get n as input, with cards being numbered from 1 to n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n# Code\n```\nclass Solution {\n public int[] deckRevealedIncreasing(int[] deck) {\n int n = deck.length, p = 0, rem = n;\n int start1 = 0, start2 = 1, kata = -1;\n Arrays.sort(deck);\n boolean flag1 = false, flag2 = false;\n int[] ret = new int[n];\n for(int step=2;p<n;step<<=1) {\n flag2 = (rem & 1) != 0;\n if(flag1) {\n // pre odd\n for(int fill=start1;fill<n;fill+=step) {\n ret[fill] = deck[p++];\n }\n if(flag2) {\n // cur odd\n ret[kata] = deck[p++];\n }\n } else {\n // pre even\n for(int fill=start1;fill<n;fill+=step) {\n ret[fill] = deck[p++];\n }\n if(flag2) {\n // cur odd\n if(kata !=- 1) {\n ret[kata] = deck[p++];\n }\n }\n }\n if(flag2) {\n start1 = start2 + step;\n start2 = start1 + step;\n kata = start1 - step;\n\n } else {\n start1 = start2;\n start2 = start1 + step;\n }\n rem >>= 1;\n flag1 = flag2;\n }\n return ret;\n }\n}\n``` | 3 | 0 | ['Java'] | 0 |
reveal-cards-in-increasing-order | JavaScript 91.84% faster | Simplest solution with explanation O(n) | Queue| Beg to Adv | javascript-9184-faster-simplest-solution-ly2q | \n\n\n# Complexity\n- Time complexity:O(n)\n\n- Space complexity:O(n)\n\n# Code\n\n/**\n * @param {number[]} deck\n * @return {number[]}\n */\nvar deckRevealedI | rlakshay14 | NORMAL | 2023-07-20T19:57:19.823805+00:00 | 2023-07-20T19:57:19.823834+00:00 | 188 | false | \n\n\n# Complexity\n- Time complexity:O(n)\n\n- Space complexity:O(n)\n\n# Code\n```\n/**\n * @param {number[]} deck\n * @return {number[]}\n */\nvar deckRevealedIncreasing = function(deck) {\n let stack = deck.sort((a, b) => b - a); // Sorting the deck in decending order.\n // Deck will look like : [17, 13, 11, 7, 5, 3, 2]\n let queue = [stack.shift()]; // Adding first element of stack in queue.\n // At this level :\n // Stack : [ 13, 11, 7, 5, 3, 2 ] \n // Queue : [ 17 ]\n \n while (stack.length > 0) { // Loop to travering stack and queue.\n queue.unshift(queue.pop()); // Taking last element of the queue and adding it to the front of the queue. Revealing the last card.\n queue.unshift(stack.shift()); // Taking out first element of the stack and adding it the front of the queue.\n // In this way top card will added to the queue.\n }\n return queue; // Returning the resulting queue.\n};\n```\n**Queue output :**\n```\nQueue at each iteration:\n[17]\n[13, 17]\n[11, 17, 13]\n[7, 13, 11, 17]\n[5, 17, 7, 13, 11]\n[3, 11, 5, 17, 7, 13]\n[2, 13, 3, 11, 5, 17, 7]\n```\n\n## Found helpful, Do upvote !! | 3 | 0 | ['Queue', 'JavaScript'] | 2 |
reveal-cards-in-increasing-order | c++ Solution using Queue | 100% faster | 0ms | c-solution-using-queue-100-faster-0ms-by-yv75 | This solution takes an input vector deck and sorts it in increasing order. It then uses a queue to store the indices of the elements in the deck. The algorithm | teja_swaroop | NORMAL | 2023-07-09T06:46:56.766942+00:00 | 2023-07-09T08:31:43.529632+00:00 | 336 | false | This solution takes an input vector deck and sorts it in increasing order. It then uses a queue to store the indices of the elements in the deck. The algorithm iterates through the deck and assigns the sorted values to the corresponding indices in a result vector.\n\nThe queue is processed until it becomes empty. At each iteration, the algorithm retrieves the front index from the queue, assigns the next sorted value to that index in the result vector, and removes the index from the queue. If there are still more than one element in the queue, the front index is moved to the back of the queue to simulate the revealing process.\n\nFinally, the resulting vector is returned as the output of the function.\n\n```\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n // Create a queue to store indices\n queue<int> q;\n \n // Sort the deck in increasing order\n sort(deck.begin(), deck.end());\n \n // Create a result vector with the same size as the deck\n vector<int> res(deck.size());\n \n // Initialize the queue with indices\n for (int i = 0; i < deck.size(); i++)\n q.push(i);\n \n // Process the queue until it becomes empty\n int j = 0;\n while (!q.empty()) {\n // Retrieve the front index from the queue\n int ind = q.front();\n \n // Set the value at the front index in the result vector\n res[ind] = deck[j++];\n \n // Remove the front index from the queue\n q.pop();\n \n // If there are still more than one element in the queue,\n // move the front index to the back of the queue\n if (q.size() > 1) {\n int k = q.front();\n q.pop();\n q.push(k);\n }\n }\n \n // Return the resulting vector\n return res;\n}\n\n``` | 3 | 0 | ['Array', 'Queue', 'C', 'Sorting'] | 0 |
reveal-cards-in-increasing-order | Solution | solution-by-deleted_user-g4lb | C++ []\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n queue<int>q;\n int n=deck.size();\n sort(d | deleted_user | NORMAL | 2023-05-16T04:15:45.896721+00:00 | 2023-05-16T04:29:10.015372+00:00 | 933 | false | ```C++ []\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n queue<int>q;\n int n=deck.size();\n sort(deck.begin(),deck.end());;\n for(int i=0;i<n;i++)\n q.push(i);\n vector<int>res(n,0);\n int i=0;\n while(!q.empty() && i<n){\n int index=q.front();\n q.pop();\n res[index]=deck[i++];\n q.push(q.front());\n q.pop();\n }\n return res;\n }\n};\n```\n\n```Python3 []\nclass Solution(object):\n def deckRevealedIncreasing(self, deck):\n N = len(deck)\n index = collections.deque(range(N))\n ans = [None] * N\n\n for card in sorted(deck):\n ans[index.popleft()] = card\n if index:\n index.append(index.popleft())\n\n return ans\n```\n\n```Java []\nclass Solution {\n public int[] deckRevealedIncreasing(int[] deck) {\n if(deck.length==1)\n return deck;\n Arrays.sort(deck);\n int res[]=new int[deck.length];\n int k=1;\n int c=0;\n res[0]=deck[0];\n while(k<deck.length)\n {\n for(int i=1;i<deck.length;i++)\n {\n if(res[i]==0){\n c++;\n if(c==2){\n res[i]=deck[k++];\n c=0;\n \n }\n } \n }\n }\n return res;\n }\n}\n```\n | 3 | 0 | ['C++', 'Java', 'Python3'] | 1 |
reveal-cards-in-increasing-order | Java - Solution (add first ,skipping second approach) | java-solution-add-first-skipping-second-xbq4k | \npublic int[] deckRevealedIncreasing(int[] deck) {\n Arrays.sort(deck);\n int n = deck.length;\n Queue<Integer> q = new LinkedList<>();\n | shubhankar01 | NORMAL | 2022-08-14T12:16:51.290513+00:00 | 2022-08-14T12:16:51.290543+00:00 | 667 | false | ```\npublic int[] deckRevealedIncreasing(int[] deck) {\n Arrays.sort(deck);\n int n = deck.length;\n Queue<Integer> q = new LinkedList<>();\n for(int i = 0; i < n; i++) q.offer(i);\n int ans[] = new int[deck.length];\n for(int i = 0;i < n; i++){\n ans[q.poll()] = deck[i];\n q.offer(q.poll());\n }\n return ans;\n }\n``` | 3 | 0 | ['Java'] | 0 |
reveal-cards-in-increasing-order | [C++] With detailed explanation - Without using deque | c-with-detailed-explanation-without-usin-t453 | Logic :\nBasically, here I am taking an element from sorted vector deck one by one and putting it into res vector where 0 is present with one gap.\n\nExample : | isha_070_ | NORMAL | 2021-06-30T15:11:57.953579+00:00 | 2021-06-30T20:34:08.863421+00:00 | 110 | false | # **Logic :**\nBasically, here I am taking an element from sorted vector ```deck``` one by one and putting it into ```res``` vector where ```0``` is present with one gap.\n\n**Example :** ```17,13,11,2,3,5,7```\n\nAfter sorting: ```2,3,5,7,11,13,17```\n* Initially:\nres -> ```2,0,0,0,0,0,0```\nPutting smallest element at the index ```0``` at the beginning itself.\n* After first pass :\nres -> ```2,0,3,0,0,0,0```\nSkipping index ```1``` untouched and keeping next bigger element at index ```2```.\n* After second pass :\nres -> ```2,0,3,0,5,0,0```\nSkipping index ```3``` untouched and keeping next bigger element at index ```4```.\n* After third pass :\nres -> ```2,0,3,0,5,0,7```\nSkipping index ```5``` untouched and keeping next bigger element at index ```6```.\n* After fourth pass :\nres -> ```2,0,3,11,5,0,7```\nSkipping index ```1``` untouched and keeping next bigger element at index ```3```.\n* After fifth pass :\nres -> ```2,13,3,11,5,0,7```\nSkipping index ```5``` untouched and keeping next bigger element at index ```1```.\n* After sixth pass :\nres -> ```2,13,3,11,5,17,7```\nFinally, largest value will occupy the position with only ```0``` left after passing through that index once.\n\n**Answer :** ```2,13,3,11,5,17,7```\n\n# **Code :**\n```\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n int n=deck.size();\n vector<int> res(n);\n sort(deck.begin(), deck.end());\n int i=1; res[0]=deck[0];\n int k=0;\n while(i<n){\n int c=0;\n while(c!=2){\n k++;\n if(k>=n) k=0;\n if(res[k]==0) c++;\n }\n res[k]=deck[i];\n i++;\n }\n return res;\n }\n};\n``` | 3 | 0 | [] | 1 |
reveal-cards-in-increasing-order | C++ | 100% faster | easy | c-100-faster-easy-by-armangupta48-iyma | \nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n queue<int> q;\n for(int i = 0;i<deck.size();i++)\n | armangupta48 | NORMAL | 2021-05-09T20:43:51.330864+00:00 | 2021-05-09T20:43:51.330911+00:00 | 403 | false | ```\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n queue<int> q;\n for(int i = 0;i<deck.size();i++)\n {\n q.push(i);\n }\n vector<int> ans(deck.size());\n sort(deck.begin(),deck.end());\n for(int card:deck)\n {\n ans[q.front()] = card;\n q.pop();\n if(!q.empty())\n {\n q.push(q.front());\n q.pop();\n }\n }\n return ans;\n }\n};\n``` | 3 | 0 | ['C', 'C++'] | 1 |
reveal-cards-in-increasing-order | python explained the logic in detail with an example | python-explained-the-logic-in-detail-wit-xfuk | To solve this problem, we can first observe the example, and try to reverse this process:\n\nWe get the deck in the order [17,13,11,2,3,5,7] (this order doesn\' | shuashua2019 | NORMAL | 2021-04-07T13:36:55.580476+00:00 | 2021-04-07T13:36:55.580517+00:00 | 263 | false | To solve this problem, we can first observe the example, and try to reverse this process:\n```\nWe get the deck in the order [17,13,11,2,3,5,7] (this order doesn\'t matter), and reorder it.\nAfter reordering, the deck starts as [2,13,3,11,5,17,7], where 2 is the top of the deck.\nWe reveal 2, and move 13 to the bottom. The deck is now [3,11,5,17,7,13].\nWe reveal 3, and move 11 to the bottom. The deck is now [5,17,7,13,11].\nWe reveal 5, and move 17 to the bottom. The deck is now [7,13,11,17].\nWe reveal 7, and move 13 to the bottom. The deck is now [11,17,13].\nWe reveal 11, and move 17 to the bottom. The deck is now [13,17].\nWe reveal 13, and move 17 to the bottom. The deck is now [17].\nWe reveal 17.\n```\nFrom the above we know we can go this steps to obtain the final answer:\n1. start an empty data structure: que/list/array\n2. put the largest one in. Here it is 17\n3. put the next largest one to the left, when there is only one element. So it become 13, 17\n4. Now we before we add the third element, we rotate the que: put the 17 to the first: so it will be [17, 13], we next add 11 ( the third largest) so we have [11.17,13]\n5. From now on, we repeat the step 4 until finish. eg. rotate, and get [13,11,17] and then add 7. this give[7,13,11,17]\n...\n```\nfrom collections import deque\nclass Solution:\n def deckRevealedIncreasing(self, deck: List[int]) -> List[int]:\n deck.sort(reverse = True) # sort \n deck_result = deque() # start a deque for the result\n for card in deck: \n if len(deck_result) > 1: # if the deque have more than 1 element, we need to rotate it before add the new element\n deck_result.rotate(1)\n deck_result.appendleft(card) # add the new element\n return list(deck_result)\n \n``` | 3 | 0 | ['Python3'] | 2 |
reveal-cards-in-increasing-order | [PYTHON 3] Using Deque - Beats 97 % | python-3-using-deque-beats-97-by-mohamed-ayyp | \nclass Solution:\n def deckRevealedIncreasing(self, deck: List[int]) -> List[int]:\n deck.sort(reverse = True)\n queue = deque()\n for | mohamedimranps | NORMAL | 2020-04-25T06:43:50.303595+00:00 | 2020-04-25T06:43:50.303634+00:00 | 458 | false | ```\nclass Solution:\n def deckRevealedIncreasing(self, deck: List[int]) -> List[int]:\n deck.sort(reverse = True)\n queue = deque()\n for card in deck:\n if queue:\n queue.appendleft(queue.pop())\n queue.appendleft(card)\n return queue\n``` | 3 | 0 | ['Queue', 'Python3'] | 1 |
reveal-cards-in-increasing-order | [Python] 100% O(NlogN) | python-100-onlogn-by-mantasltu-c010 | ```\n def deckRevealedIncreasing(self, deck: List[int]) -> List[int]:\n deck.sort()\n res = collections.deque()\n res.append(deck.pop()) | mantasltu | NORMAL | 2019-08-26T22:15:31.612249+00:00 | 2019-08-26T22:22:11.156231+00:00 | 283 | false | ```\n def deckRevealedIncreasing(self, deck: List[int]) -> List[int]:\n deck.sort()\n res = collections.deque()\n res.append(deck.pop())\n while deck:\n res.appendleft(res.pop())\n res.appendleft(deck.pop())\n return list(res) | 3 | 0 | [] | 0 |
reveal-cards-in-increasing-order | Easy solution with queue by reverse engineering - beats 99.83% | easy-solution-with-queue-by-reverse-engi-zi00 | input - [2,3,5,7,11,13,17] (just sort the input that you get)\n\nThe last number that you wanna get is the last number in the array - (17)\n\nThe penultimate nu | nyubee | NORMAL | 2019-02-26T05:31:53.274043+00:00 | 2019-02-26T05:31:53.274089+00:00 | 481 | false | input - [2,3,5,7,11,13,17] (just sort the input that you get)\n\nThe last number that you wanna get is the last number in the array - (17)\n\nThe penultimate number is 13. So put 13 on top of 17 (13,17) and bring the last number to top (17,13). Now while you perform the action with (17,13), you will place 17 in the bottom and reveal 13 first - so it becomes (17), now reveal 17.\n\nThe number that you want before 13 is 11. Place 11 on top now (11,17,13) and bring the last number to the top (13,11,17). Now when you perfom the action with (13,11,17), you will place 13 in the bottom and reveal 11 - so it becomes (17,13), now you will place 17 in the bottom and reveal 13 - it becomes (17), and then you will reveal 17.\n\ncurrent is 7 -> (7,13,11,17) -> (17,7,13,11) (add 7 to the queue, remove 17 from the queue and add back 17 to the queue)\ncurrent is 5 -> (5,17,7,13,11) -> (11,5,17,7,13) (add 5 to the queue, remove 11 from the queue and add back 11 to the queue)\ncurrent is 3 -> (3,11,5,17,7,13) -> (13,3,11,5,17,7) (add current to the queue, remove from the queue, add the removed number back to the queue)\ncurrent is 2 -> (2,13,3,11,5,17,7) -> Stop here since you don\'t have anymore numbers.\n\nNow the head of queue is 7, tail is 2. Just return the reverse order.\n\n```\n public int[] deckRevealedIncreasing(int[] deck) {\n Arrays.sort(deck);\n \n if(deck.length < 3) {\n return deck;\n }\n \n Queue<Integer> queue = new LinkedList<Integer>();\n \n for(int i=deck.length-1; i>=1; i--) {\n queue.add(deck[i]);\n queue.add(queue.remove());\n }\n \n queue.add(deck[0]);\n \n for(int i=deck.length-1; i>=0; i--) {\n deck[i] = queue.remove();\n }\n return deck;\n }\n``` | 3 | 0 | ['Queue'] | 1 |
reveal-cards-in-increasing-order | C++ beats 100% using deque with explanation | c-beats-100-using-deque-with-explanation-0lrx | In this question, we can find the rules from samples that it pop the first element and move the second element to last. So if want to get the correct answer, we | robotzhao | NORMAL | 2019-02-16T16:53:34.226632+00:00 | 2019-06-11T12:43:22.995151+00:00 | 242 | false | In this question, we can find the rules from samples that it pop the first element and move the second element to last. So if want to get the correct answer, we can do the steps contrary to the rules:\nSort the deck, push elements at the front of the deque from large to small and move the last element to the second everytime.\n```\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n deque<int> deque;\n sort(deck.begin(), deck.end(), [](int& v1, int& v2) -> bool {\n return v1 > v2;\n });\n for(int i = 0; i < deck.size(); i++) {\n deque.push_front(deck[i]);\n deque.insert(deque.begin() + 1, *(deque.end() - 1));\n deque.pop_back();\n }\n return vector(deque.begin(), deque.end());\n }\n};\n```\n\n\n\n | 3 | 1 | [] | 0 |
reveal-cards-in-increasing-order | C++ 8ms 99% solution (with detail algorithm) | c-8ms-99-solution-with-detail-algorithm-b0h0l | \nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n //Algorithm:\n //The behavior of the question is compos | sjwu | NORMAL | 2018-12-22T15:06:57.926767+00:00 | 2018-12-22T15:06:57.926837+00:00 | 457 | false | ```\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n //Algorithm:\n //The behavior of the question is composed of two steps.\n //1. Take the front element out from current vector\n //2. Move the second element to the end of current vector\n //So, the best way to solve this problem is through backward trace.\n //That is, reverse the step of 2. and 1. until the deck.size().\n //2.-rev Move the last element to the front of current vector\n //1.-rev push the element to the front of current vector \n\t\t//3. And note that if we implement 1.-rev with ordered values, this is exactly the answer to this question\n const int deck_size=deck.size();\n vector<int> ans;\n sort(deck.begin(),deck.end());//sort it as I mentioned in 3.\n for(int i=0;i<deck_size;i++){\n //Implement step 2.-rev\n if(ans.size()){\n rotate(ans.begin(),ans.end()-1,ans.end());\n }\n \n //Implement step 1.-rev with sorted values\n ans.insert(ans.begin(),deck[deck_size-1-i]);\n }\n return ans;\n }\n};\n``` | 3 | 0 | [] | 1 |
reveal-cards-in-increasing-order | C++ easy and clear way using deque | c-easy-and-clear-way-using-deque-by-teck-inxk | c++\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n vector<int> res;\n \n sort(deck.rbegin(), dec | tecknight | NORMAL | 2018-12-02T10:30:35.877200+00:00 | 2018-12-02T10:30:35.877242+00:00 | 428 | false | ```c++\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n vector<int> res;\n \n sort(deck.rbegin(), deck.rend());\n deque<int> dq;\n \n dq.push_back(deck[0]);\n \n for(int i=1;i<deck.size();i++)\n {\n dq.push_front(dq.back());\n dq.pop_back();\n dq.push_front(deck[i]);\n }\n \n while(!dq.empty())\n {\n res.push_back(dq.front());\n dq.pop_front();\n }\n return res;\n }\n};\n``` | 3 | 1 | [] | 2 |
reveal-cards-in-increasing-order | C++ solution with auxiliary queue | c-solution-with-auxiliary-queue-by-kmshi-4xwn | Sort array.\nUse a queue to keep track of indices.\n\n```\nvector deckRevealedIncreasing(vector& deck) {\n\t\t//result array\n std::vector res(deck.size( | kmshihabuddin | NORMAL | 2018-12-02T04:04:51.213709+00:00 | 2018-12-02T04:04:51.213761+00:00 | 259 | false | Sort array.\nUse a queue to keep track of indices.\n\n```\nvector<int> deckRevealedIncreasing(vector<int>& deck) {\n\t\t//result array\n std::vector<int> res(deck.size(),0);\n \n std::sort(deck.begin(),deck.end());\n \n\t\t//queue of card indices\n std::queue<int> indices;\n for(int i=0;i<deck.size();++i){\n indices.push(i);\n }\n \n int index=0;\n \n while(indices.size()){\n \n //reveal card\n int temp=indices.front();\n indices.pop();\n res[temp]=deck[index++];\n \n //push to back\n temp=indices.front();\n indices.pop();\n indices.push(temp);\n }\n \n return res;\n }\n\t | 3 | 0 | [] | 1 |
reveal-cards-in-increasing-order | USING QUEUE || TC = O(N), SC = O(N) | using-queue-tc-on-sc-on-by-dkvmah7yog-q741 | IntuitionApproachComplexity
Time complexity:
O(N)
Space complexity:
O(N)
Code | DkVMAH7YOG | NORMAL | 2025-03-27T17:25:10.668392+00:00 | 2025-03-27T17:25:10.668392+00:00 | 42 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
O(N)
- Space complexity:
O(N)
# Code
```cpp []
class Solution {
public:
vector<int> deckRevealedIncreasing(vector<int>& deck) {
vector<int> ans(deck.size());
// step 01 : sort
sort(deck.begin(), deck.end());
// step 02 : put indices of ans into q
queue<int> q;
for (int i = 0; i<ans.size(); i++) {
q.push(i);
}
// ip -> op -> reveal in sort
// reverse : sort -> op
// reverse simulation + filling using sorted deck
for (int i = 0; i<deck.size(); i++) {
// reveal
ans[q.front()] = deck[i];
q.pop();
// push from to bottom
if (!q.empty()) {
q.push(q.front());
q.pop();
}
}
return ans;
}
};
``` | 2 | 0 | ['Array', 'Queue', 'Sorting', 'Simulation', 'C++'] | 0 |
reveal-cards-in-increasing-order | Beginner Level Solution And Explanation | beginner-level-solution-and-explanation-sx30f | Algorithm
Sort the Deck: Sort the deck array in ascending order.
Initialize an Index Queue: Create a queue containing indices ( 0 ) to ( n-1 ), where ( n ) is t | yadav_sanjay | NORMAL | 2025-01-04T07:44:31.453856+00:00 | 2025-01-04T07:44:31.453856+00:00 | 123 | false | ### Algorithm
1. **Sort the Deck**: Sort the `deck` array in ascending order.
2. **Initialize an Index Queue**: Create a queue containing indices \( 0 \) to \( n-1 \), where \( n \) is the length of the deck.
3. **Simulate the Process**:
- Assign the smallest card (from the sorted deck) to the position at the front of the queue.
- Remove the front index and, if the queue is not empty, move the next index to the back of the queue.
4. **Repeat** until all cards are placed in their respective positions.
5. **Return the Result**: The `result` array contains the deck order.
---
### Complexity
- **Time Complexity**:
- Sorting the deck: \( O(n log n) \).
- Queue operations: \( O(n) \).
Total: \( O(n log n) \).
- **Space Complexity**:
- Result array: \( O(n) \).
- Index queue: \( O(n) \).
Total: \( O(n) \).
---
### Code
```java []
class Solution {
public int[] deckRevealedIncreasing(int[] deck) {
Arrays.sort(deck);
int n = deck.length;
int[] result = new int[n];
Queue<Integer> indexQueue = new LinkedList<>();
for (int i = 0; i < n; i++) {
indexQueue.add(i);
}
for (int card : deck) {
result[indexQueue.poll()] = card;
if (!indexQueue.isEmpty()) {
indexQueue.add(indexQueue.poll());
}
}
return result;
}
}
```
```cpp []
class Solution {
public:
vector<int> deckRevealedIncreasing(vector<int>& deck) {
sort(deck.begin(), deck.end());
int n = deck.size();
vector<int> result(n);
queue<int> indexQueue;
for (int i = 0; i < n; i++) {
indexQueue.push(i);
}
for (int card : deck) {
result[indexQueue.front()] = card;
indexQueue.pop();
if (!indexQueue.empty()) {
indexQueue.push(indexQueue.front());
indexQueue.pop();
}
}
return result;
}
};
```
```python []
class Solution:
def deckRevealedIncreasing(self, deck: List[int]) -> List[int]:
deck.sort()
n = len(deck)
result = [0] * n
indexQueue = deque(range(n))
for card in deck:
result[indexQueue.popleft()] = card
if indexQueue:
indexQueue.append(indexQueue.popleft())
return result
```
---
# UPVOTE | 2 | 0 | ['Array', 'Queue', 'Simulation', 'Python', 'C++', 'Java'] | 0 |
reveal-cards-in-increasing-order | C++ Easy Solution with full Explanation || Time Complexity O(n) | c-easy-solution-with-full-explanation-ti-943j | Intuition\n Describe your first thoughts on how to solve this problem. \n this solution sorts the deck, arranges the cards in a way that they can be revealed in | uy_154788 | NORMAL | 2024-04-10T19:11:52.450180+00:00 | 2024-04-10T19:11:52.450216+00:00 | 11 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n this solution sorts the deck, arranges the cards in a way that they can be revealed in increasing order, and then rearranges them according to the specified pattern to achieve the final result.\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n**Sorting the Deck:** The function starts by sorting the deck in increasing order. This is necessary to ensure that the revealed cards will be in increasing order.\n\n**Creating a New Vector:** A new vector v is created with twice the size of the input deck. This is done to accommodate the process of revealing cards as described in the problem.\n\n**Placing Cards in Alternate Positions:** The sorted deck elements are placed at alternate positions (even indices) in the new vector. This ensures that when the cards are revealed, they will be in increasing order.\n\n**Removing Trailing Zeros:** After placing the sorted elements, there might be trailing zeros left in the vector. If there are any, they are removed using pop_back().\n\n**Rearranging Elements:** The last step involves rearranging the elements of the vector in a specific manner. Elements at even indices are moved to the end of the vector. This is done to simulate the process of revealing cards according to the given rules.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(n) \n\n# Code\n```\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n sort(deck.begin(),deck.end());\n int n=deck.size();\n int j=0;\n \n vector<int> v(2*n,0);\n for(int i=0;i<2*n;i=i+2){\n v[i]=deck[j];\n j++;\n }\n\n int s=v.size();\n if(v[s-1]==0){\n v.pop_back();\n }\n for(int i=v.size()-2;i>=0;i=i-2){\n int j=v.size()-1;\n v[i]=v[j];\n v.pop_back();\n }\n return v;\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
reveal-cards-in-increasing-order | Beats 86.41% of users with java || Easy solution using queue | beats-8641-of-users-with-java-easy-solut-8u95 | \n\n# Approach\n1. Sort the deck:* First, sort the given deck array in increasing order. This allows us to reveal the cards in increasing order.\n\n*2. Initiali | DEEPAK_10439 | NORMAL | 2024-04-10T16:28:04.845479+00:00 | 2024-04-10T16:28:04.845514+00:00 | 130 | false | \n\n# Approach\n**1. **Sort the deck:**** First, sort the given deck array in increasing order. This allows us to reveal the cards in increasing order.\n\n**2. Initialize a Queue:** Initialize a queue (let\'s call it indexQueue) to keep track of the indices of the cards in the revealed deck. Populate the queue with the indices of the array res, which represent the positions of the cards in the revealed deck.\n\n**3 Simulate the Card Revealing Process:**\n Iterate through the sorted deck.\n For each card in the sorted deck, reveal the card at the front of the queue by setting its value in the res array to the current value of the card.\n Move the next index in the queue to the end, simulating the process of moving cards in a circular fashion.\n Repeat until there is only one index left in the queue.\n**4. Construct the Revealed Deck:** After simulating the revealing process, the res array will contain the revealed deck in increasing order.\n\n**5. Return the Revealed Deck:** Return the res array as the final output.\n\n# Complexity\n- Time complexity: O(nlogn)\n\n- Space complexity: O(n)\n# Code\n```\nclass Solution {\n public int[] deckRevealedIncreasing(int[] deck) {\n int res[] = new int[deck.length];\n Queue<Integer> q = new LinkedList<>();\n Arrays.sort(deck);\n for (int i = 0; i < res.length; i++) {\n q.add(i);\n }\n int i=0;\n while (q.size() > 1) {\n res[q.remove()] = deck[i];\n q.add(q.remove());\n i++;\n }\n res[q.remove()] = deck[i];\n return res;\n }\n}\n``` | 2 | 0 | ['Java'] | 1 |
reveal-cards-in-increasing-order | Reverse Simulation | Java | C++ | reverse-simulation-java-c-by-lazy_potato-3u9x | Intuition, approach, and complexity dicussed in video solution in detail.\nhttps://youtu.be/tqLlQHxL0nc\n# Code\n\nJava:\n\njava\nclass Solution {\n public i | Lazy_Potato_ | NORMAL | 2024-04-10T16:10:45.856037+00:00 | 2024-04-10T16:10:45.856066+00:00 | 80 | false | # Intuition, approach, and complexity dicussed in video solution in detail.\nhttps://youtu.be/tqLlQHxL0nc\n# Code\n\nJava:\n\n```java\nclass Solution {\n public int[] deckRevealedIncreasing(int[] deck) {\n Arrays.sort(deck);\n Deque<Integer> cardQ = new ArrayDeque<>();\n int size = deck.length;\n for (int indx = size - 1; indx > -1; indx--) {\n if (!cardQ.isEmpty()) {\n cardQ.offerLast(cardQ.pollFirst());\n }\n cardQ.offerLast(deck[indx]);\n }\n for (int indx = 0; indx < size; indx++) {\n deck[indx] = cardQ.pollLast();\n }\n return deck;\n }\n}\n```\n\nC++:\n\n```cpp\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n sort(deck.begin(), deck.end());\n queue<int> cardQ;\n int size = deck.size();\n for(int indx = size - 1; indx > -1; indx--){\n if(!cardQ.empty()){\n cardQ.push(cardQ.front());\n cardQ.pop(); \n }\n cardQ.push(deck[indx]);\n }\n for(int indx = size-1; indx > -1; indx--){\n deck[indx] = cardQ.front();\n cardQ.pop();\n }\n return deck;\n }\n};\n```\n\nFeel free to copy and use these code snippets as needed! Let me know if you need further assistance! | 2 | 0 | ['Array', 'Queue', 'Sorting', 'Simulation', 'C++', 'Java'] | 1 |
reveal-cards-in-increasing-order | Easy Solution || without Queue || pattern identification || O(n * logn) | easy-solution-without-queue-pattern-iden-vv2e | Intuition\npattern identification by analyzing testcases \n Describe your first thoughts on how to solve this problem. \n\n# Approach\ntestcase :- 2 13 3 11 5 1 | Kiraa71 | NORMAL | 2024-04-10T15:48:02.054283+00:00 | 2024-04-11T02:27:44.113531+00:00 | 7 | false | # Intuition\npattern identification by analyzing testcases \n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\ntestcase :- 2 13 3 11 5 17 7 \n\nafter_all_operation :- 2 13 3 11 5 17 7 13 11 17 13 17 \napproach :- first pick last two number and store in ans array and after that alternate-wise fill by picking from decks and fill into answer and last with one pointer iterate where zero exist in the array fill the last pointerwise data from decks into answer array \n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n * 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```\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n int n = deck.size();\n sort(deck.begin(),deck.end());\n vector<int>ans(n+(n-2));\n if(deck.size() == 1)return deck;\n ans[n+(n-2) - 1] = deck[n-1];\n ans[n+(n-2) - 2] = deck[n-2];\n int j = n-3;\n for(int i = n + (n-2)-4; i >= 0; i-=2){\n ans[i] = deck[j];\n j--;\n }\n j = n + (n-2) - 1;\n for(int i = n + (n-2)-3; i >= 0; i-=2){\n if(ans[i] == 0){\n ans[i] = ans[j];\n j--;\n }\n }\n while(ans.size() != n){\n ans.pop_back();\n }\n return ans;\n }\n};\n``` | 2 | 0 | ['C++'] | 1 |
reveal-cards-in-increasing-order | Beats 100% Using C++ | Detailed solution | BOOM BRAIN | beats-100-using-c-detailed-solution-boom-06t9 | Intuition\nAfter all elements were sorted, just put them to the right index. \n\n# Approach\n- Create an array of index, just even indexes are revealed first.\n | xuankhuongw | NORMAL | 2024-04-10T15:02:53.912060+00:00 | 2024-04-10T15:03:44.271730+00:00 | 19 | false | # Intuition\nAfter all elements were sorted, just put them to the right index. \n\n# Approach\n- Create an array of index, just even indexes are revealed first.\n- It\'s kind of hard to describe my solution, let\'s see some example.\n- In index-array, if index of element in index-array is even, add deck at this index to the res array, if not, push it to back\n- Begin:\n- - Sorted array: 2 3 5 7 11 13 17\n- - Result array: 0 0 0 0 0 0 0 \n- - Index array : 0 1 2 3 4 5 6\n- Loop 1:\n- - Sorted array: 2 3 5 7 11 13 17\n- - Result array: 2 0 0 0 0 0 0 \n- - Index array : 0 1 2 3 4 5 6\n- Index of ind_array:0 1 2 3 4 5 6\n- Loop 2:\n- - Sorted array: 2 3 5 7 11 13 17\n- - Result array: 2 0 0 0 0 0 0 \n- - Index array : 0 1 2 3 4 5 6 1\n- Index of ind_array:0 1 2 3 4 5 6 7\n- Loop 3:\n- - Sorted array: 2 3 5 7 11 13 17\n- - Result array: 2 0 3 0 0 0 0 \n- - Index array : 0 1 2 3 4 5 6 1\n- Index of ind_array:0 1 2 3 4 5 6 7\n- Loop 4:\n- - Sorted array: 2 3 5 7 11 13 17\n- - Result array: 2 0 3 0 0 0 0 \n- - Index array : 0 1 2 3 4 5 6 1 3\n- Index of ind_array:0 1 2 3 4 5 6 7 8\n- ------------\nAnd continue \nAt the end:\n- The index array: is 0 1 2 3 4 5 6 1 3 5 1 5 5\n- Index of ind_array:0 1 2 3 4 5 6 7 8 9 10 11 12\n# Complexity\n- Time complexity: O(n)\n- Space complexity: O(n)\n\n\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n sort(deck.begin(), deck.end());\n int n = deck.size();\n\n vector<int> res(n, 0);\n //this index will move in the deck list\n int index = 0;\n int time = 0;\n //create index array\n vector<int> index_list;\n for(int i = 0; i < n; i++)\n index_list.push_back(i);\n //this index will move in the index_list\n int i = 0;\n while(true)\n {\n if(i % 2 == 0)\n {\n res[index_list[i]] = deck[index++];\n time ++;\n }\n else\n index_list.push_back(index_list[i]);\n //move the index of index array\n i++;\n if(time == n) break;\n }\n return res;\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
reveal-cards-in-increasing-order | C++ || Beats 100% || Queue || Priority Queue | c-beats-100-queue-priority-queue-by-kush-ufej | Approach\n\nHere we must remeber the index we left earlier therefor queue will be best to store them as if we need them we pop() them else we reinsert the unuse | kushal_019 | NORMAL | 2024-04-10T12:18:35.772437+00:00 | 2024-04-10T12:18:35.772460+00:00 | 30 | false | # Approach\n\nHere we must remeber the index we left earlier therefor queue will be best to store them as if we need them we pop() them else we reinsert the unused indexes.\nalso we use priority queue to always add smallest element first.\nwe also used a flag called "flip" to keep a track weather i flip the card or append again in the deck.\n\n**here we used same array deck to return so no extra space is used and changes are made in same at every state.**\n\nExample : deck = [17,13,11,2,3,5,7]\n here index = [0,1,2,3,4,5,6]\n values = [2,3,5,7,11,13,17]\n\n flag is true so we removed the card hence its out first card\n step 1 deck = [2,13,11,2,3,5,7]\n index = [1,2,3,4,5,6] \n values = [3,5,7,11,13,17]\n flip = true\n\n now flip is reversed so er are suppose to leave the index and do not make any change \n step 2 deck = [2,13,11,2,3,5,7]\n index = [2,3,4,5,6,1] \n values = [3,5,7,11,13,17] \n flip = false\n\n again we iterate and next states will be \n step 3 deck = [2,13,3,2,3,5,7]\n index = [3,4,5,6,1] \n values = [5,7,11,13,17] \n flip = true\n\n step 4 deck = [2,13,3,2,3,5,7]\n index = [4,5,6,1,3] \n values = [5,7,11,13,17] \n flip = false\n\n step 5 deck = [2,13,3,2,5,5,7]\n index = [5,6,1,3] \n values = [7,11,13,17] \n flip = true\n\n step 6 deck = [2,13,3,2,5,5,7]\n index = [6,1,3,5] \n values = [7,11,13,17] \n flip = false\n\n step 7 deck = [2,13,3,2,5,5,7]\n index = [1,3,5] \n values = [11,13,17] \n flip = true\n\n step 8 deck = [2,13,3,2,5,5,7]\n index = [3,5,1] \n values = [11,13,17] \n flip = false\n\n step 9 deck = [2,13,3,11,5,5,7]\n index = [5,1] \n values = [13,17] \n flip = true\n\n step 10 deck = [2,13,3,11,5,5,7]\n index = [1,5] \n values = [13,17] \n flip = false\n\n step 11 deck = [2,13,3,11,5,5,7]\n index = [5] \n values = [17] \n flip = true\n\n step 12 deck = [2,13,3,11,5,5,7]\n index = [5] \n values = [17] \n flip = false\n\n step 13 deck = [2,13,3,11,5,17,7]\n index = [] \n values = [] \n flip = true\n\n deck is now updated to required form hence we will return it\n\n\n# Complexity\n- Time complexity:O( n log(n))\n\n- Space complexity: O(n)\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n queue <int> index;\n priority_queue <int, vector<int>, greater<int> >value;\n int n = deck.size();\n for(int i=0;i<n;i++){\n index.push(i);\n value.push(deck[i]);\n }\n bool flip = false;\n\n while(!index.empty()){\n if(flip){\n flip = !flip;\n int newIndex = index.front();\n index.pop();\n index.push(newIndex);\n }\n else{\n deck[index.front()] = value.top();\n value.pop();\n index.pop();\n flip = !flip;\n }\n }\n\n return deck;\n }\n};\n``` | 2 | 0 | ['Queue', 'Heap (Priority Queue)', 'C++'] | 0 |
reveal-cards-in-increasing-order | EASY CPP SOLUTION 💡🔥 || EASY TO UNDERSTOOD🚀 | easy-cpp-solution-easy-to-understood-by-nagwn | \n\n# Approach\n\n## 1.Vector Initialization:\nThe code initializes a new vector v with the same elements as the input deck. This is done by using the construct | himanshu_dhage | NORMAL | 2024-04-10T12:16:30.131656+00:00 | 2024-04-10T12:16:30.131688+00:00 | 9 | false | \n\n# Approach\n\n## **1.Vector Initialization:**\n**The code initializes a new vector v with the same elements as the input deck. This is done by using the constructor of the vector class that accepts two iterators pointing to the beginning and end of the range to be copied.\nThe resize() function is then called to resize the vector to the same size as the input deck. This ensures that the vector has enough space to accommodate all the elements from the deck.****Bold**\n\n## **2.Sorting:**\n\n**The sort() function is used to sort the elements of the vector v in increasing order**.\n\n## 3.Reversing:\n**After sorting, the reverse() function is called to reverse the order of the elements in the vector. This step effectively makes the vector\'s order decreasing.**\n\n## 4.Card Revealing Process:\n**Two nested loops are used to simulate the card revealing process.\nThe outer loop iterates over each card position in the vector.\nThe inner loop iterates from the beginning of the vector to the current position (i).\nWithin the inner loop, adjacent cards are swapped. This effectively mimics the process of revealing cards according to a specific pattern.**\n\n## 5.Restoring Original Order:\n**After the card revealing process, the vector is reversed again to restore its original order.**\n\n## 6.Adjusting First Card:\n**The first card of the vector (v[0]) is stored in a variable k.\nThen, the erase() function is called to remove the first element from the vector.\nFinally, the stored first card (k) is pushed back to the end of the vector using push_back().**\n\n## 7.Return:\n**The modified vector (v) is returned as the result of the function.**\n\n# Complexity\n- Time complexity: O(N^2)\n- Space complexity:O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) \n {\n vector<int> v(deck.begin(),deck.end());\n v.resize(deck.size());\n sort(v.begin(),v.end());\n reverse(v.begin(),v.end()); \n\n // vector<int>ans(v.size());\n \n for(int i = 0 ; i < v.size();i++)\n {\n for(int j = 0 ; j < i;j++)\n {\n \n swap(v[j],v[j+1]);\n \n }\n }\n \n reverse(v.begin(),v.end());\n\n int k = v[0];\n v.erase(v.begin());\n v.push_back(k);\n return v;\n }\n};\n``` | 2 | 0 | ['Array', 'Queue', 'Sorting', 'Simulation', 'C++'] | 0 |
reveal-cards-in-increasing-order | QUEUE + SORTING || Solution of reveal cards in increasing order problem | queue-sorting-solution-of-reveal-cards-i-lz5d | This was a daily challenge for April 10th 2024.\n# Queue\nTo solve this problem we use the queue structure\n# Definition\nLike a stack, the queue is a linear da | tiwafuj | NORMAL | 2024-04-10T11:05:26.782822+00:00 | 2024-04-10T11:15:41.776188+00:00 | 84 | false | # This was a daily challenge for April 10th 2024.\n# Queue\nTo solve this problem we use the queue structure\n# Definition\nLike a stack, the queue is a linear data structure that stores items in a First In First Out (FIFO) manner. With a queue, the least recently added item is removed first. A good example of a queue is any queue of consumers for a resource where the consumer that came first is served first.\n# Usage\nOperations associated with queue are: \n- Enqueue: Adds an item to the queue. If the queue is full, then it is said to be an Overflow condition \u2013 Time Complexity : $$O(1)$$\n- Dequeue: Removes an item from the queue. The items are popped in the same order in which they are pushed. If the queue is empty, then it is said to be an Underflow condition \u2013 Time Complexity : $$O(1)$$\n- Front: Get the front item from queue \u2013 Time Complexity : $$O(1)$$\n- Rear: Get the last item from queue \u2013 Time Complexity : $$O(1)$$\n# Approach\n- First step: sort deck\n- Second step: rotate* queue and add argument to the left end** of the deque for each element in sorted deck\n- Third step: return answer\n> - rotate():- This function rotates the deque by the number specified in arguments. If the number specified is negative, rotation occurs to the left. Else rotation is to right.\n> - appendleft():- This function is used to insert the value in its argument to the left end of the deque.\n# Code\n```\nclass Solution:\n def deckRevealedIncreasing(self, deck: List[int]) -> List[int]:\n queue = deque()\n desc_sorted_deck = sorted(deck)[::-1]\n for value in desc_sorted_deck:\n queue.rotate()\n queue.appendleft(value)\n return queue\n``` | 2 | 0 | ['Array', 'Queue', 'Sorting', 'Simulation', 'Python3'] | 0 |
reveal-cards-in-increasing-order | EASY || JAVA || SORTING || USING QUEUES !!! | easy-java-sorting-using-queues-by-va-run-kdqi | Intuition:\nThe problem is to reveal the cards in increasing order based on their unique integers. To accomplish this, we can simulate the process of revealing | va-run-6626 | NORMAL | 2024-04-10T10:33:21.966356+00:00 | 2024-04-10T10:33:21.966406+00:00 | 63 | false | # Intuition:\nThe problem is to reveal the cards in increasing order based on their unique integers. To accomplish this, we can simulate the process of revealing cards as described in the problem statement. The essential steps involve sorting the deck initially and then iteratively revealing the cards while maintaining their order.\n\n# Approach:\n- **Sort the deck:** We start by sorting the deck of cards in ascending order. This step ensures that when we reveal the cards, they will be in increasing order.\n- **Create a Queue:** We use a queue to keep track of the indices of the cards. Initially, each index corresponds to the position of a card in the sorted deck.\n- **Simulate Revealing Process:** We simulate the process of revealing cards by iterating through the sorted deck. For each card:\n - **Take the top card:** We pop the top card from the sorted deck.\n - **Pop an index from the queue:** This index determines where to place the revealed card in the result array.\n - **Place the card in the result array:** We place the revealed card in the result array at the determined index.\n - **Update the queue:** If there are more cards left, we put the next index to the bottom of the queue.\n- **Return the Result:** Once all cards are revealed and placed in the result array, we return the result.\n\n# Complexity Analysis:\n## Time Complxity:\n#### Sorting:\n- Sorting the deck takes $$O(n log n)$$ time, where n is the number of cards.\n#### Queue Operations:\n- For each card, we perform queue operations, which takes $$O(n)$$ time in total.\n### Overall Time Complexity:\n- $$O(n log n$$) due to sorting, where n is the number of cards.\n## Space Complexity: \n - $$O(n)$$ for the result array, as it stores the revealed cards.\n - $$O(n)$$ for the queue, as it stores the indices of the cards.\n - Overall space complexity is $$O(n)$$.\n\n# Code\n```\nclass Solution {\n public int[] deckRevealedIncreasing(int[] deck) {\n Arrays.sort(deck);\n Queue<Integer> queue = new LinkedList<>();\n for(int i = 0;i < deck.length; i++){\n queue.add(i);\n }\n int[] res = new int[deck.length];\n for(int card : deck){\n int idx = queue.poll();\n res[idx] = card;\n if(!queue.isEmpty()){\n queue.add(queue.poll());\n }\n }\n return res;\n }\n}\n```\n\n | 2 | 0 | ['Array', 'Queue', 'Simulation', 'Java'] | 0 |
reveal-cards-in-increasing-order | 🔥 C++ || 2 interview approaches using simulator vector, queue - best explanation and example | c-2-interview-approaches-using-simulator-jk93 | 2 solutions\n1. First solution: using queue\n2. Second solution: using simulator vector\n\n# First Approach\n- Look at an example to explore the solution and de | minhle3003 | NORMAL | 2024-04-10T10:28:43.219044+00:00 | 2024-04-10T10:28:43.219075+00:00 | 10 | false | # 2 solutions\n1. First solution: using queue\n2. Second solution: using simulator vector\n\n# First Approach\n- Look at an example to explore the solution and decide which data structures that you use:\n1. First, sorting the deck helps us to start with the smallest card.\n2. Pop the front element and push it at the end of the queue.\n3. Add the next element.\n\n## Example\n```ts\ndeck = [17,13,11,2,3,5,7]\nans = [2,13,3,11,5,17,7]\n\nStep by step if the answer is correct\n[2,13,3,11,5,17,7]\n[3,11,5,17,7,13].\n[5,17,7,13,11].\n[7,13,11,17].\n[11,17,13].\n[13,17].\n[17].\n\nHere look from the bottom to top. you can see:\nqueue = []\n- push 17 -> [17]\n- pop 17 and push 17 at the end, then add 13 -> [13,17]\n- pop 17 and push 17 at the end, then add 11 -> [11,17,13]\n- pop 13 and push 13 at the end, then add 7 -> [7,13,11,17]\n- pop 17 and push 17 at the end, then add 5 -> [5,17,7,13,11]\n- pop 11 and push 11 at the end, then add 3 -> [3,11,5,17,7,13]\n- pop 13 and push 13 at the end, then add 2 -> [2,13,3,11,5,17,7]\n```\n\n## Complexity\n- Time complexity: $$0(n)$$\n- Space complexity: $$O(n)$$ where queue contains `n` elements\n\n## Code\n```\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n sort(deck.begin(), deck.end());\n\n queue<int> q;\n for(int i = deck.size()-1; i >= 0; i--)\n {\n if(!q.empty())\n {\n q.push(q.front());\n q.pop();\n }\n q.push(deck[i]);\n }\n\n for(int i = deck.size()-1; i >= 0; i--)\n {\n deck[i] = q.front();\n q.pop();\n }\n\n return deck;\n }\n};\n```\n\n# Second Approach\n1. First, sorting the deck helps us to start with the smallest card.\n2. Create answer vector and simulator vector to simulate the process\n3. Look at an example below to understand more the idea\n\n## Example\n```ts\ndeck = [17,13,11,2,3,5,7]\n\nAfter sorted and creating vectors\ndeck = [2,3,5,7,11,13,15]\nans = [0,0,0,0,0,0,0]\nsimulator = [0,1,2,3,4,5,6]\n i\n\n- With 2\ni = 0 -> ans[0] = 2;\npush 1 (i+1) at the end\nsimulator = [0,1,2,3,4,5,6,1]\n i\n\n- With 3\ni = 2 -> ans[2] = 2;\npush 3 (i+1) at the end\nsimulator = [0,1,2,3,4,5,6,1,3]\n i\n\n- With 5\ni = 4 -> ans[4] = 5;\npush 5 (i+1) at the end\nsimulator = [0,1,2,3,4,5,6,1,3,5]\n i\n\n- With 7\ni = 6 -> ans[6] = 7;\npush 1 (i+1) at the end\nsimulator = [0,1,2,3,4,5,6,1,3,5,1]\n i\n\n- With 11\ni = 3 -> ans[3] = 11;\npush 5 (i+1) at the end\nsimulator = [0,1,2,3,4,5,6,1,3,5,1,5]\n i\n\n- With 13\ni = 1 -> ans[1] = 13;\npush 5 (i+1) at the end\nsimulator = [0,1,2,3,4,5,6,1,3,5,1,5]\n i\n\n- With 17\ni = 5 -> ans[5] = 17;\nend\n```\n\n## Code\n```\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n sort(deck.begin(), deck.end());\n\n int n = deck.size();\n vector<int> ans(n);\n vector<int> simulator;\n\n for(int i = 0; i < n; i++)\n {\n simulator.push_back(i);\n }\n\n int k = 0;\n for(int i = 0; i < n; i++)\n {\n int index = simulator[k];\n ans[index] = deck[i];\n\n if(k == simulator.size()-1) break;\n\n k++;\n int tmp = simulator[k];\n simulator.push_back(tmp);\n k++;\n }\n\n return ans;\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
reveal-cards-in-increasing-order | Easy C++ solution for beginners || Easy intuitive and explained approach | easy-c-solution-for-beginners-easy-intui-h1pa | Intuition\n Describe your first thoughts on how to solve this problem. \nThis C++ solution implements the deckRevealedIncreasing function, which takes a vector | deleted_user | NORMAL | 2024-04-10T10:13:05.977263+00:00 | 2024-04-10T10:13:05.977289+00:00 | 50 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis C++ solution implements the deckRevealedIncreasing function, which takes a vector of integers representing a deck of cards and returns a vector where the cards are revealed in increasing order. The intuition behind this solution is to simulate the process of revealing cards based on the given algorithm.\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n\nSorting the deck:\nThe input deck is sorted in increasing order to ensure that the revealed cards are also in increasing order.\n\n !!!! After it we try to do reverse of what we did to get our sorted order !!!!!!\n\nSimulation using a queue :\nWe use a queue to simulate the process of revealing cards. Initially, we iterate through the sorted deck in reverse order and push the cards onto the queue. For each card pushed, we simulate the process of revealing by popping the front card from the queue and pushing it to the back. This process continues until all cards are processed.\n\nCreating the result vector:\nAfter the simulation, we retrieve the revealed cards from the queue and store them in the result vector in reverse order. This step ensures that the cards are in increasing order as required.\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n\n\nSorting the deck: O(n log n), where n is the number of cards in the deck.\nSimulating the process using a queue: O(n), as each card is pushed and popped once.\nCreating the result vector: O(n), as we iterate through the deck once to retrieve the revealed cards.\nOverall, the time complexity is dominated by the sorting step, so the total time complexity is O(n log n).\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\nAdditional space for the queue: O(n), as we use a queue to simulate the process, which can hold up to n elements.\nAdditional space for the result vector: O(n), as we create a new vector to store the revealed cards.\nOverall, the space complexity is O(n) due to the space used by the queue and the result vector.\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n int n=deck.size();\n sort(deck.begin(),deck.end());\n queue <int> q;\n for(int i=n-1;i>=0;i--){\n q.push(deck[i]);\n if(i==0) continue;\n int k=q.front();\n q.pop();\n q.push(k);\n }\n vector<int> ret(n,-1);\n for(int i=0;i<n;i++){\n ret[n-i-1]=q.front();\n q.pop();\n }\n return ret; \n }\n};\n```\n\n | 2 | 0 | ['Array', 'Queue', 'Sorting', 'Simulation', 'C++'] | 0 |
reveal-cards-in-increasing-order | Scala: simple Queue simulation with indices | scala-simple-queue-simulation-with-indic-v6hs | Code\n\nobject Solution {\n def deckRevealedIncreasing(deck: Array[Int]): Array[Int] = {\n val q = collection.mutable.Queue.range(0, deck.length)\n \n | SerhiyShaman | NORMAL | 2024-04-10T08:58:18.932125+00:00 | 2024-04-10T08:58:18.932161+00:00 | 11 | false | # Code\n```\nobject Solution {\n def deckRevealedIncreasing(deck: Array[Int]): Array[Int] = {\n val q = collection.mutable.Queue.range(0, deck.length)\n \n deck.sorted.foreach { c => \n deck(q.dequeue) = c\n if (q.nonEmpty) q.enqueue(q.dequeue)\n }\n\n deck\n }\n}\n``` | 2 | 0 | ['Scala'] | 0 |
reveal-cards-in-increasing-order | 2 Easy Interview Approaches ✅ || using Dequeue👍 || Without Dequeue 🔥|| C++ || Java || Python | 2-easy-interview-approaches-using-dequeu-k0pq | \n\n# Approach 1\n Describe your approach to solving the problem. \nusing dequeue \n\n# Complexity\n- Time complexity: O(nlogn)\n Add your time complexity here, | naman_malik | NORMAL | 2024-04-10T08:54:57.156023+00:00 | 2024-04-10T08:54:57.156048+00:00 | 138 | false | \n\n# Approach 1\n<!-- Describe your approach to solving the problem. -->\nusing dequeue \n\n# Complexity\n- Time complexity: O(nlogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n) \nfor taking dequeue -> O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```C++ []\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n sort(deck.begin(),deck.end()); // Sort the deck in increasing order\n\n int n=deck.size();\n\n deque<int>dq;\n vector<int>result(n);\n\n for(int i=0; i<n; i++)\n {\n dq.push_back(i); // Initialize deque with indices 0, 1, 2, ..., n-1\n }\n\n for(int i=0; i<n; i++)\n {\n //perfromed the following steps give in question\n int idx = dq.front(); // Get the next available index\n dq.pop_front(); // Remove the index from the front\n\n result[idx]=deck[i]; // Place the card in the result array at give index i.e idx\n dq.push_back(dq.front()); //put the next front index in the back of the dequeue\n dq.pop_front(); //and pop it in the front\n }\n \n return result;\n \n }\n};\n```\n```Java []\npublic class Solution {\n public int[] deckRevealedIncreasing(int[] deck) {\n Arrays.sort(deck); // Sort the deck in increasing order\n\n int n = deck.length;\n\n Deque<Integer> dq = new LinkedList<>();\n int[] result = new int[n];\n\n for (int i = 0; i < n; i++) {\n dq.offer(i); // Initialize deque with indices 0, 1, 2, ..., n-1\n }\n\n for (int i = 0; i < n; i++) {\n int idx = dq.poll(); // Get the next available index\n result[idx] = deck[i]; // Place the card in the result array at the given index (idx)\n dq.offer(dq.poll()); // Put the next front index in the back of the dequeue\n }\n\n return result;\n }\n}\n```\n```Python []\nclass Solution(object):\n def deckRevealedIncreasing(self, deck):\n deck.sort() # Sort the deck in increasing order\n\n n = len(deck)\n\n dq = deque()\n result = [0] * n\n\n for i in range(n):\n dq.append(i) # Initialize deque with indices 0, 1, 2, ..., n-1\n\n for i in range(n):\n idx = dq.popleft() if dq else None # Get the next available index if the deque is not empty\n if idx is not None:\n result[idx] = deck[i] # Place the card in the result array at the given index (idx)\n if dq: # Check if the deque is not empty\n dq.append(dq.popleft()) # Put the next front index in the back of the dequeue\n\n return result\n\n```\n\n\n# Approach 2\n<!-- Describe your approach to solving the problem. -->\nBetter Approach (without dequeue) \n\n# Complexity\n- Time complexity: O(nlogn)\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```C++ []\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n sort(deck.begin(),deck.end());\n\n int i = 0; // Index for deck array\n int j = 0; // Index for result array\n int n = deck.size(); // Size of the deck array\n bool flip = true; // A flag to indicate whether to flip or not\n\n vector<int>result(n,0);\n\n while(i<n) // Iterate through the deck and assign values to the result vector\n {\n if(result[j]==0) // If the current position in the result vector is empty\n {\n if(flip==true) // If flip is true, assign the value from the sorted deck to the result\n {\n result[j]=deck[i];\n i++; // Move to the next value in the sorted deck\n }\n flip = !flip; // Flip the flag for the next iteration\n }\n j=(j+1)%n; // Move to next position in the result vector (circular manner)\n }\n \n return result; // Return resultant vector\n \n }\n};\n```\n```Java []\nclass Solution {\n public int[] deckRevealedIncreasing(int[] deck) {\n Arrays.sort(deck);\n\n int i = 0; // Index for deck array\n int j = 0; // Index for result array\n int n = deck.length; // Size of the deck array\n boolean flip = true; // A flag to indicate whether to flip or not\n\n int[] result = new int[n];\n\n while(i<n) // Iterate through the deck and assign values to the result vector\n {\n if(result[j]==0) // If the current position in the result vector is empty\n {\n if(flip==true) // If flip is true, assign the value from the sorted deck to the result\n {\n result[j]=deck[i];\n i++; // Move to the next value in the sorted deck\n }\n flip = !flip; // Flip the flag for the next iteration\n }\n j=(j+1)%n; // Move to next position in the result vector (circular manner)\n }\n \n return result; // Return resultant vector\n }\n}\n```\n```Python []\nclass Solution(object):\n def deckRevealedIncreasing(self, deck):\n deck.sort()\n\n i = 0 # Index for deck array\n j = 0 # Index for result array\n n = len(deck) # Size of the deck array\n flip = True # A flag to indicate whether to flip or not\n\n result = [0] * n\n\n while i < n:\n if result[j] == 0:\n if flip:\n result[j] = deck[i]\n i += 1\n flip = not flip\n j = (j + 1) % n\n\n return result\n```\n\n\n\n | 2 | 0 | ['Array', 'Queue', 'Swift', 'C', 'Python', 'C++', 'Java', 'Rust', 'Kotlin', 'JavaScript'] | 0 |
reveal-cards-in-increasing-order | Simple solution | simple-solution-by-techtinkerer-q71b | Intuition\njust put indexes in queue from 1 to n and do what is said. After put values in the indices of the answer vector.\n Describe your first thoughts on ho | TechTinkerer | NORMAL | 2024-04-10T07:17:09.958068+00:00 | 2024-04-10T07:17:09.958090+00:00 | 8 | false | # Intuition\njust put indexes in queue from 1 to n and do what is said. After put values in the indices of the answer vector.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n\n# 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```\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n int n=deck.size();\n vector<int> mid,ans(n,0);\n queue<int> q;\n for(int i=0;i<n;i++)\n q.push(i);\n\n while(!q.empty()){\n int f=q.front();\n mid.push_back(f);\n q.pop();\n if(!q.empty()){\n int s=q.front();\n q.pop();\n\n q.push(s);\n }\n }\n\n sort(deck.begin(),deck.end());\n \n\n\n for(int i=0;i<n;i++){\n ans[mid[i]]=deck[i];\n }\n return ans;\n }\n};\n``` | 2 | 0 | ['Greedy', 'Queue', 'Simulation', 'C++'] | 0 |
reveal-cards-in-increasing-order | Easy and Beginner Friendly || Beats 100% | easy-and-beginner-friendly-beats-100-by-mii9i | \n\n\n# Intuition\n Describe your first thoughts on how to solve this problem. \nAfter looking to the problem,we can see that we have to start from last ie, we | adrijchakraborty7 | NORMAL | 2024-04-10T06:21:56.295941+00:00 | 2024-04-10T12:35:28.842414+00:00 | 102 | false | \n\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAfter looking to the problem,we can see that we have to start from last ie, we will sort the array and start with the biggest element.\nSee this example :\n\n[22,2,4,14]\n\nHere, take the highest element,ie, 22.\nBefore this the 2nd highest,ie, 14 should be placed.\ntherefore, [14,22]\n\nNow as per the problem,the smaller one will be gone and the next element will go to the end.\n\nSo our small array follow this.\n\nNow take the 3rd highest element,ie, 4.\nSo we can arrange the array like [4,22,14]\nHere 4 will go away and 22 will go to the last.So our array is correct.\n\nThis will continue upto the 1st element.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n1. Take a deque so that we can delete element from back and push it in front.\n2. Sort the array before going to any process.\n3. Now push and pop element according to the intution.\n4. Declare a answer vector and store the answer to this.\n5. Return the answer.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nAs we are using sorting, So time complexity becomes $$O(nlogn)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nAs we are using deque,it require some extra space of $$O(n)$$\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n if (deck.size() <= 1) {\n return deck;\n }\n sort(deck.begin(), deck.end());\n deque<int> dq;\n int i = deck.size() - 1;\n for (i; i >= 0; i--) {\n if (dq.size() >= 2) {\n int r = dq.back();\n dq.pop_back();\n dq.push_front(r);\n }\n dq.push_front(deck[i]);\n }\n\n vector<int> ans(dq.size());\n\n copy(dq.begin(), dq.end(), ans.begin());\n\n return ans;\n }\n};\n```\n\nYou can optimise the solution. Refer to others solution also for better understanding. | 2 | 0 | ['C'] | 0 |
time-based-key-value-store | C++ 3 lines, hash map + map | c-3-lines-hash-map-map-by-votrubac-e4ui | We use hash map to lookup ordered {timestamp, value} pairs by key in O(1). Then, we use binary search to find the value with a timestamp less or equal than the | votrubac | NORMAL | 2019-01-27T04:03:00.480601+00:00 | 2019-07-29T17:18:35.051867+00:00 | 56,316 | false | We use hash map to lookup ordered ```{timestamp, value}``` pairs by key in O(1). Then, we use binary search to find the value with a timestamp less or equal than the requested one.\n```\nunordered_map<string, map<int, string>> m;\nvoid set(string key, string value, int timestamp) {\n m[key].insert({ timestamp, value });\n}\nstring get(string key, int timestamp) {\n auto it = m[key].upper_bound(timestamp);\n return it == m[key].begin() ? "" : prev(it)->second;\n}\n```\nSince our timestamps are only increasing, we can use a vector instead of a map, though it\'s not as concise.\n```\nunordered_map<string, vector<pair<int, string>>> m;\nvoid set(string key, string value, int timestamp) {\n m[key].push_back({ timestamp, value });\n}\nstring get(string key, int timestamp) {\n auto it = upper_bound(begin(m[key]), end(m[key]), pair<int, string>(timestamp, ""), [](\n const pair<int, string>& a, const pair<int, string>& b) { return a.first < b.first; });\n return it == m[key].begin() ? "" : prev(it)->second;\n}\n```\n# Complexity analysis\nAssuming ```n``` is the number of set operations, and ```m``` is the number of get operations:\n- Time Complexity: \n - Set: ```O(1)``` single operation, and total ```O(n)```.\nNote: assuing timestamps are only increasing. If not, it\'s ```O(n log n)```.\n - Get: ```O(log n)``` for a single operation, and total ```O(m log n)```.\n- Space Complexity: ```O(n)``` (assuming every ```{ timestamp, value }``` is unique). | 331 | 7 | [] | 42 |
time-based-key-value-store | TreeMap Solution Java | treemap-solution-java-by-poorvank-dq9b | \npublic class TimeMap {\n\n private Map<String,TreeMap<Integer,String>> map;\n\n /** Initialize your data structure here. */\n public TimeMap() {\n | poorvank | NORMAL | 2019-01-27T04:02:54.033868+00:00 | 2019-01-27T04:02:54.033921+00:00 | 36,141 | false | ```\npublic class TimeMap {\n\n private Map<String,TreeMap<Integer,String>> map;\n\n /** Initialize your data structure here. */\n public TimeMap() {\n map = new HashMap<>();\n }\n\n public void set(String key, String value, int timestamp) {\n if(!map.containsKey(key)) {\n map.put(key,new TreeMap<>());\n }\n map.get(key).put(timestamp,value);\n }\n\n public String get(String key, int timestamp) {\n TreeMap<Integer,String> treeMap = map.get(key);\n if(treeMap==null) {\n return "";\n }\n Integer floor = treeMap.floorKey(timestamp);\n if(floor==null) {\n return "";\n }\n return treeMap.get(floor);\n }\n}\n``` | 250 | 5 | [] | 26 |
time-based-key-value-store | [Python] Dict and Binary search Implementation | python-dict-and-binary-search-implementa-5r46 | Most of the solution here doesn\'t give you the binary search implementation, but you propabaly needs to write it during the interview...\n\n\nclass TimeMap(obj | yidong_w | NORMAL | 2019-01-28T23:30:38.837300+00:00 | 2019-01-28T23:30:38.837378+00:00 | 33,058 | false | Most of the solution here doesn\'t give you the binary search implementation, but you propabaly needs to write it during the interview...\n\n```\nclass TimeMap(object):\n\n def __init__(self):\n self.dic = collections.defaultdict(list)\n \n\n def set(self, key, value, timestamp):\n self.dic[key].append([timestamp, value])\n\n def get(self, key, timestamp):\n arr = self.dic[key]\n n = len(arr)\n \n left = 0\n right = n\n \n while left < right:\n mid = (left + right) / 2\n if arr[mid][0] <= timestamp:\n left = mid + 1\n elif arr[mid][0] > timestamp:\n right = mid\n \n return "" if right == 0 else arr[right - 1][1]\n```\n | 220 | 7 | [] | 21 |
time-based-key-value-store | Java beats 100% | java-beats-100-by-ramankes-09g1 | \nclass Data {\n String val;\n int time;\n Data(String val, int time) {\n this.val = val;\n this.time = time;\n }\n}\nclass TimeMap {\ | ramankes | NORMAL | 2019-02-25T23:01:35.076938+00:00 | 2019-02-25T23:01:35.076993+00:00 | 23,572 | false | ```\nclass Data {\n String val;\n int time;\n Data(String val, int time) {\n this.val = val;\n this.time = time;\n }\n}\nclass TimeMap {\n\n /** Initialize your data structure here. */\n Map<String, List<Data>> map;\n public TimeMap() {\n map = new HashMap<String, List<Data>>();\n }\n \n public void set(String key, String value, int timestamp) {\n if (!map.containsKey(key)) map.put(key, new ArrayList<Data>());\n map.get(key).add(new Data(value, timestamp));\n }\n \n public String get(String key, int timestamp) {\n if (!map.containsKey(key)) return "";\n return binarySearch(map.get(key), timestamp);\n }\n \n protected String binarySearch(List<Data> list, int time) {\n int low = 0, high = list.size() - 1;\n while (low < high) {\n int mid = (low + high) >> 1;\n if (list.get(mid).time == time) return list.get(mid).val;\n if (list.get(mid).time < time) {\n if (list.get(mid+1).time > time) return list.get(mid).val;\n low = mid + 1;\n }\n else high = mid -1;\n }\n return list.get(low).time <= time ? list.get(low).val : "";\n }\n}\n``` | 152 | 3 | [] | 19 |
time-based-key-value-store | Python concise 6-liner | python-concise-6-liner-by-cenkay-775v | \nclass TimeMap:\n\n def __init__(self):\n self.times = collections.defaultdict(list)\n self.values = collections.defaultdict(list)\n\n def | cenkay | NORMAL | 2019-03-02T13:07:52.133181+00:00 | 2019-03-02T13:07:52.133243+00:00 | 14,977 | false | ```\nclass TimeMap:\n\n def __init__(self):\n self.times = collections.defaultdict(list)\n self.values = collections.defaultdict(list)\n\n def set(self, key: str, value: str, timestamp: int) -> None:\n self.times[key].append(timestamp)\n self.values[key].append(value)\n\n def get(self, key: str, timestamp: int) -> str:\n i = bisect.bisect(self.times[key], timestamp)\n return self.values[key][i - 1] if i else \'\'\n\n``` | 79 | 3 | [] | 12 |
time-based-key-value-store | C++ unordered_map + Binary Search(last occurrence) | c-unordered_map-binary-searchlast-occurr-5uwg | \nclass TimeMap {\npublic:\n /** Initialize your data structure here. */\n unordered_map<string, vector<pair<int, string>>> m;\n TimeMap() {\n \ | dawar | NORMAL | 2019-05-26T09:31:19.890868+00:00 | 2020-04-25T06:21:05.495465+00:00 | 8,801 | false | ```\nclass TimeMap {\npublic:\n /** Initialize your data structure here. */\n unordered_map<string, vector<pair<int, string>>> m;\n TimeMap() {\n \n }\n \n void set(string key, string value, int timestamp) {\n m[key].push_back({timestamp, value});\n }\n \n string get(string key, int timestamp) {\n if(!m.count(key))\n return "";\n int start = 0, end = m[key].size();\n while(start < end) {\n int mid = start + (end-start)/2;\n if(m[key][mid].first > timestamp)\n end = mid;\n else\n start = mid + 1;\n }\n return start > 0 and start <= m[key].size() ? m[key][start-1].second : "";\n }\n};\n\n``` | 52 | 1 | [] | 10 |
time-based-key-value-store | ✅Three Simple Java Solutions | three-simple-java-solutions-by-ahmedna12-nbcw | 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 | ahmedna126 | NORMAL | 2023-09-29T09:25:24.815388+00:00 | 2023-11-07T11:35:14.737732+00:00 | 5,428 | 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# Code1\n<details>\n <summary>Explain</summary> \n\n1. `Pair` Class:\n - The `Pair` class is a simple data structure that holds two values: a `timestamp` (an integer) and a `val` (a string). This represents a key-value pair with a timestamp.\n\n2. `TimeMap` Class:\n - The `TimeMap` class contains a private `HashMap` called `hashMap`, which maps keys (strings) to a list of `Pair` objects. Each list contains key-value pairs associated with the same key but different timestamps.\n\n - The `TimeMap` class provides two main methods:\n\n - `set(String key, String value, int timestamp)`: This method allows you to add a key-value pair with a specific timestamp to the `TimeMap`. If the key already exists in the `hashMap`, it appends the new pair to the existing list. If the key doesn\'t exist, it creates a new list and adds the pair to it.\n\n - `get(String key, int timestamp)`: This method retrieves the value associated with the given key at or just before the specified timestamp. It does this using binary search within the list of key-value pairs associated with the key.\n\n - It initializes a candidate value `cand` to an empty string.\n\n - If the `key` exists in the `hashMap`, it retrieves the list of pairs associated with that key and performs a binary search within that list.\n\n - The binary search looks for the closest pair whose timestamp is less than or equal to the target `timestamp`. If an exact match is found (timestamp matches), it returns the corresponding value. If not, it keeps track of the closest lower value (`cand`) and continues the search.\n\n - The binary search continues until `low` is less than or equal to `high`. Once it finishes, it returns the `cand` value.\n\n</details>\n <br>\n\n```Java\nclass Pair {\n int timestamp;\n String val;\n\n Pair(int timestamp, String val) {\n this.timestamp = timestamp;\n this.val = val;\n }\n}\n\npublic class TimeMap {\n\n private HashMap<String, ArrayList<Pair>> hashMap;\n\n public TimeMap() {\n hashMap = new HashMap<>();\n }\n\n public void set(String key, String value, int timestamp) {\n if (hashMap.containsKey(key)) {\n hashMap.get(key).add(new Pair(timestamp, value));\n } else {\n ArrayList<Pair> arr = new ArrayList<>();\n arr.add(new Pair(timestamp, value));\n hashMap.put(key, arr);\n }\n }\n\n public String get(String key, int timestamp) {\n\n String cand = "";\n\n if (hashMap.containsKey(key)) {\n ArrayList<Pair> arr = hashMap.get(key);\n int low = 0, high = arr.size() - 1;\n\n while (low <= high) {\n int mid = (low + high) / 2;\n int timeVal = arr.get(mid).timestamp;\n if (timeVal == timestamp) {\n return arr.get(mid).val;\n } else if (timeVal < timestamp) {\n cand = arr.get(low).val;\n low = mid + 1;\n } else {\n high = mid - 1;\n }\n }\n }\n return cand;\n }\n\n}\n\n/**\n * Your TimeMap object will be instantiated and called as such:\n * TimeMap obj = new TimeMap();\n * obj.set(key,value,timestamp);\n * String param_2 = obj.get(key,timestamp);\n */\n```\n\n# Code2\n```Java\nclass TimeMap {\n\n private HashMap<String , String> hashMap;\n private LinkedList<Integer> list;\n\n public TimeMap() {\n hashMap = new HashMap<>();\n list = new LinkedList<>();\n }\n\n public void set(String key, String value, int timestamp) {\n hashMap.put(timestamp + key , value);\n list.add(timestamp);\n }\n\n public String get(String key, int timestamp) {\n if (hashMap.containsKey(timestamp+key)) {\n return hashMap.get(timestamp+key);\n }else {\n int length = list.size()-1;\n boolean cond = false;\n while (length >= 0 && !cond) {\n String str = list.get(length)+ key;\n cond = timestamp > list.get(length) && hashMap.containsKey(str);\n if (cond) {\n return hashMap.get(str);\n }\n length--;\n }\n }\n return "";\n }\n}\n\n```\n\n\n\n# Code3\n```\nclass TimeMap {\n\n private HashMap<String, TreeMap<Integer, String>> hashMap;\n\n public TimeMap() {\n hashMap = new HashMap<>();\n }\n\n public void set(String key, String value, int timestamp) {\n hashMap.computeIfAbsent(key, k -> new TreeMap<>()).put(timestamp, value);\n }\n\n public String get(String key, int timestamp) {\n if (!hashMap.containsKey(key)) {\n return "";\n }\n\n TreeMap<Integer, String> timeValueMap = hashMap.get(key);\n\n Integer floorTimestamp = timeValueMap.floorKey(timestamp);\n\n return (floorTimestamp == null) ? "" : timeValueMap.get(floorTimestamp);\n }\n}\n\n```\n\n## For additional problem-solving solutions, you can explore my repository on GitHub: [GitHub Repository](https://github.com/ahmedna126/java_leetcode_challenges)\n\n\n\n | 51 | 0 | ['Hash Table', 'Binary Search', 'Tree', 'Java'] | 5 |
time-based-key-value-store | Clearly Explained Python Solution Using Binary Search | Time complexity O(log n) | clearly-explained-python-solution-using-54i85 | Problem Description\n\nThe problem requires implementing a time-based key-value store where you can set a key-value pair with an associated timestamp and retrie | KhadimHussainDev | NORMAL | 2024-04-14T15:36:58.093691+00:00 | 2024-04-14T15:36:58.093725+00:00 | 6,843 | false | ## Problem Description\n\nThe problem requires implementing a time-based key-value store where you can set a key-value pair with an associated timestamp and retrieve the value of a key at a specific timestamp.\n\n## Approach Explanation\n\nThis solution uses a dictionary (`self.dic`) to store key-value pairs where each value is a list of `[value, timestamp]` pairs associated with the key:\n- **Initialization (`__init__`)**:\n - Initialize an empty dictionary `self.dic` to store key-value pairs.\n\n- **Set Method (`set`)**:\n - If the key does not exist in `self.dic`, initialize it with an empty list.\n - Append the `[value, timestamp]` pair to the list associated with the key in `self.dic`.\n\n- **Get Method (`get`)**:\n - Retrieve the list of `[value, timestamp]` pairs associated with the given `key` from `self.dic`.\n - Use binary search to find the most recent value (`res`) that has a timestamp less than or equal to the given `timestamp`:\n - Initialize `l` to 0 and `r` to the index of the last element in the list.\n - While `l` is less than or equal to `r`:\n - Calculate the `mid` index.\n - If the timestamp at `mid` is less than or equal to the given `timestamp`, update `res` with the value at `mid` and adjust `l` to search the right half of the list.\n - Otherwise, adjust `r` to search the left half of the list.\n - Return `res` as the value associated with the key at the specified `timestamp`.\n\n```python\nclass TimeMap:\n\n def __init__(self):\n self.dic = {}\n\n def set(self, key: str, value: str, timestamp: int) -> None:\n if key not in self.dic:\n self.dic[key] = []\n self.dic[key].append([value , timestamp])\n\n def get(self, key: str, timestamp: int) -> str:\n res = ""\n values = self.dic.get(key , [])\n l , r = 0 , len(values) - 1\n while l <= r :\n mid = (l + r) >> 1\n if values[mid][1] <= timestamp:\n l = mid + 1\n res = values[mid][0]\n else:\n r = mid - 1\n return res\n\n\n# Your TimeMap object will be instantiated and called as such:\n# obj = TimeMap()\n# obj.set(key,value,timestamp)\n# param_2 = obj.get(key,timestamp)\n```\n\n## Complexity Analysis\n\n- **Time Complexity**:\n - `set`: O(1) for inserting a `[value, timestamp]` pair into the list associated with a key in `self.dic`.\n - `get`: O(log n) for performing binary search on the list of `[value, timestamp]` pairs associated with a key in `self.dic`, where `n` is the number of entries for the key.\n \n- **Space Complexity**:\n - O(n) for storing all `[value, timestamp]` pairs in `self.dic`, where `n` is the total number of key-value pairs inserted using the `set` method.\n\n> #### ***If You Found it helpful, please upvote it. Thanks***\n\n | 47 | 0 | ['Binary Search', 'Python3'] | 3 |
time-based-key-value-store | Java binary search & treemap solution | java-binary-search-treemap-solution-by-t-8fjm | Binary search:\n\nclass TimeMap {\n\n class Node {\n String value;\n int timestamp;\n Node(String value, int timestamp) {\n t | tankztc | NORMAL | 2019-04-27T21:42:28.240822+00:00 | 2019-04-27T21:42:28.240868+00:00 | 9,002 | false | Binary search:\n```\nclass TimeMap {\n\n class Node {\n String value;\n int timestamp;\n Node(String value, int timestamp) {\n this.value = value;\n this.timestamp = timestamp;\n }\n }\n \n Map<String, List<Node>> map;\n /** Initialize your data structure here. */\n public TimeMap() {\n map = new HashMap();\n }\n \n public void set(String key, String value, int timestamp) {\n map.putIfAbsent(key, new ArrayList());\n map.get(key).add(new Node(value, timestamp));\n }\n \n public String get(String key, int timestamp) {\n List<Node> nodes = map.get(key);\n if (nodes == null) return "";\n \n int left = 0, right = nodes.size() - 1;\n while (left + 1 < right) {\n int mid = left + (right - left) / 2;\n Node node = nodes.get(mid);\n if (node.timestamp == timestamp) {\n return node.value;\n } else if (node.timestamp < timestamp) {\n left = mid;\n } else {\n right = mid;\n }\n }\n if (nodes.get(right).timestamp <= timestamp) return nodes.get(right).value;\n else if (nodes.get(left).timestamp <= timestamp) return nodes.get(left).value;\n return "";\n }\n}\n```\n\nTreeMap:\n```\nclass TimeMap {\n\n Map<String, TreeMap<Integer, String>> map;\n /** Initialize your data structure here. */\n public TimeMap() {\n map = new HashMap();\n }\n \n public void set(String key, String value, int timestamp) {\n map.putIfAbsent(key, new TreeMap());\n map.get(key).put(timestamp, value);\n }\n \n public String get(String key, int timestamp) {\n TreeMap<Integer, String> treeMap = map.get(key);\n \n if (treeMap == null) return "";\n \n Integer floorKey = treeMap.floorKey(timestamp);\n \n if (floorKey == null) return "";\n return treeMap.get(floorKey);\n }\n}\n``` | 39 | 1 | [] | 6 |
time-based-key-value-store | Python clean solution, binary search | python-clean-solution-binary-search-by-j-zjce | \nclass TimeMap(object):\n\n def __init__(self):\n self.map = collections.defaultdict(list)\n \n\n def set(self, key, value, timestamp):\n | jdjw | NORMAL | 2019-10-19T19:34:42.055918+00:00 | 2019-10-19T19:34:59.665888+00:00 | 7,409 | false | ```\nclass TimeMap(object):\n\n def __init__(self):\n self.map = collections.defaultdict(list)\n \n\n def set(self, key, value, timestamp):\n self.map[key].append((timestamp, value))\n \n\n def get(self, key, timestamp):\n values = self.map[key]\n if not values: return \'\'\n left, right = 0, len(values) - 1\n while left < right:\n mid = (left + right + 1) / 2\n pre_time, value = values[mid]\n if pre_time > timestamp:\n right = mid - 1\n else:\n left = mid\n return values[left][1] if values[left][0] <= timestamp else \'\'\n\n``` | 30 | 0 | ['Binary Tree', 'Python'] | 4 |
time-based-key-value-store | Time Based Key-Value Store || 95.83% FASTER || 3 LINE C++CODE || RUNTIME: 333 ms | time-based-key-value-store-9583-faster-3-7ziw | SHIVAM DAILY LEETCODE SOLUTIONS || CHECK : https://bit.ly/leetcode-solutions\nRuntime: 333 ms, faster than 95.83% of C++ online submissions for Time Based Key-V | shivambit | NORMAL | 2022-10-06T04:44:16.705571+00:00 | 2022-10-06T04:45:44.809574+00:00 | 5,719 | false | **SHIVAM DAILY LEETCODE SOLUTIONS || CHECK : [https://bit.ly/leetcode-solutions](https://bit.ly/leetcode-solutions)\nRuntime: 333 ms, faster than 95.83% of C++ online submissions for Time Based Key-Value Store.\nMemory Usage: 130.7 MB, less than 29.45% of C++ online submissions for Time Based Key-Value Store.**\n\n```\nclass TimeMap {\npublic:\n unordered_map<string,map<int,string>>m;\n TimeMap() {\n \n }\n \n void set(string key, string value, int timestamp) {\n m[key][timestamp]=value;\n }\n \n string get(string key, int timestamp) {\n auto it=m[key].upper_bound(timestamp);\n if(it==m[key].begin())return "";\n it--;\n return it->second;\n }\n};\n```\n\n\n | 25 | 1 | ['C', 'C++'] | 4 |
time-based-key-value-store | Easy C++ [[ 7 Lines of Code ]] | easy-c-7-lines-of-code-by-code_report-nsvm | ```\nclass TimeMap {\npublic:\n /* Initialize your data structure here. /\n unordered_map> m;\n\n TimeMap() {}\n\n void set(string key, string value, in | code_report | NORMAL | 2019-01-27T04:01:53.843852+00:00 | 2019-01-27T04:01:53.843919+00:00 | 5,257 | false | ```\nclass TimeMap {\npublic:\n /** Initialize your data structure here. */\n unordered_map<string, map<int, string>> m;\n\n TimeMap() {}\n\n void set(string key, string value, int timestamp) {\n auto& inner_map = m[key];\n inner_map[-timestamp] = value;\n }\n\n string get(string key, int timestamp) {\n auto i = m.find(key);\n if (i == m.end()) return "";\n auto j = i->second.lower_bound(-timestamp);\n return j != i->second.end() ? j->second : "";\n }\n}; | 24 | 1 | [] | 7 |
time-based-key-value-store | Python Binary Search Solution | python-binary-search-solution-by-anch999-u2t3 | The idea is using binary search to find the closest timestamp_prev in TimeMap\n\n\nclass TimeMap:\n\n def __init__(self):\n self._dic = defaultdict(li | anch9999 | NORMAL | 2019-05-18T08:25:25.377103+00:00 | 2019-08-22T04:01:24.156379+00:00 | 5,986 | false | The idea is using binary search to find the closest timestamp_prev in TimeMap\n\n```\nclass TimeMap:\n\n def __init__(self):\n self._dic = defaultdict(list)\n\n def set(self, key: str, value: str, timestamp: int) -> None:\n self._dic[key].append((value, timestamp,))\n\n def get(self, key: str, timestamp: int) -> str:\n if key in self._dic:\n li = self._dic[key]\n l, r = 0, len(self._dic[key]) - 1\n \n if li[l][1] > timestamp:\n return ""\n elif li[r][1] <= timestamp:\n return li[r][0]\n else:\n while l <= r:\n mid = l + (r - l) // 2\n\n if li[mid][1] == timestamp:\n return li[mid][0]\n\n if li[mid][1] < timestamp:\n l = mid + 1\n else:\n r = mid - 1\n\n return li[r][0]\n return ""\n``` | 20 | 0 | [] | 4 |
time-based-key-value-store | [Python3] Clean and efficient code - O(1), O(log n) | python3-clean-and-efficient-code-o1-olog-n858 | Code\npython\nclass TimeMap:\n def __init__(self):\n self.meta = collections.defaultdict(list)\n self.data = collections.defaultdict(list)\n\n | spark9625 | NORMAL | 2021-05-22T09:58:32.711356+00:00 | 2021-05-22T10:07:13.957134+00:00 | 5,516 | false | ## Code\n```python\nclass TimeMap:\n def __init__(self):\n self.meta = collections.defaultdict(list)\n self.data = collections.defaultdict(list)\n\n def set(self, key: str, value: str, timestamp: int) -> None:\n self.meta[key].append(timestamp)\n self.data[key].append(value)\n\n def get(self, key: str, timestamp: int) -> str:\n idx = bisect.bisect(self.meta[key], timestamp)\n if idx == 0:\n return \'\'\n return self.data[key][idx - 1]\n```\n\n## Comment\nThis question is very similar to [1146. Snapshot Array](https://leetcode.com/problems/snapshot-array/). Keep two dictionaries of lists, where `self.meta<str, List<int>>` keeps track of the list of timestamps for each key, and `self.data<str, List<str>>` keeps track of the corresponding data.\n\nThen, `set` is very easy. Just append the timestamp and the value to their respective lists.\nOn the other hand, `get` requires a search through the list of timestamps in order to find the largest timestamp less than or equal to the given timestamp. This can be done efficiently using binary search. Notice that `bisect.bisect` is actually synonymous to `bisect.bisect_right`, meaning that it returns the index of the first element that is strictly greater than the requested value. Therefore, you need to use `idx - 1` when indexing.\n\n## Complexity \nTime: `O(1)` for `set`. `O(log k)` for `get`, where `k` is the length of the list corresponding to the key. In the worst case where `k == n`, the complexity becomes `O(log n)`.\nSpace: `O(n)`, where `n` is the total number of values to track.\n | 19 | 0 | ['Binary Tree', 'Python', 'Python3'] | 3 |
time-based-key-value-store | Javascript map | javascript-map-by-acassara-nupc | javascript\nvar TimeMap = function() {\n this.map = new Map();\n};\n\nTimeMap.prototype.set = function(key, value, timestamp) {\n if (!this.map.has(key)) | acassara | NORMAL | 2019-11-10T18:05:21.006027+00:00 | 2019-11-10T18:05:33.452530+00:00 | 3,853 | false | ```javascript\nvar TimeMap = function() {\n this.map = new Map();\n};\n\nTimeMap.prototype.set = function(key, value, timestamp) {\n if (!this.map.has(key)) this.map.set(key, []);\n this.map.get(key)[timestamp] = value;\n};\n\nTimeMap.prototype.get = function(key, timestamp) {\n if (!this.map.has(key)) return \'\';\n const item = this.map.get(key);\n if (item[timestamp]) return item[timestamp];\n while (timestamp-- > -1) {\n if (item[timestamp]) return item[timestamp];\n }\n return \'\';\n};\n``` | 18 | 2 | ['JavaScript'] | 5 |
time-based-key-value-store | 3 Solutions | Binary | Linear {fastest} | Tree | Easy to understand | 95% beat | Java | 3-solutions-binary-linear-fastest-tree-e-60g6 | Intuition\n\n1. As we need to find the values corresponding to a key: HashMap would be the choice\n2. We need to find those values whose timestampPrev <= times | nits2010 | NORMAL | 2019-09-14T11:18:54.250228+00:00 | 2019-09-14T11:21:05.523429+00:00 | 2,727 | false | **Intuition**\n\n1. As we need to find the values corresponding to a key: `HashMap` would be the choice\n2. We need to find those values whose `timestampPrev <= timestamp`. i.e. means we need to store all the values of a key of different timestamp. Since we are looking `timestampPrev <= timestamp` then keeping those values sorted would make sense. Note, we don\'t need to maintain the sorted order as `timestamp` is always in increasing order\n\nHence, we need `HashMap<Key, List<Values>>`. \n\n**Algo 1:** Do Binary Search on values\n\n```\n\n/**\n * Runtime: 204 ms, faster than 82.02% of Java online submissions for Time Based Key-Value Store.\n * Memory Usage: 140.2 MB, less than 27.03% of Java online submissions for Time Based Key-Value Store.\n */\nclass TimeMapUsingMapBinarySearch implements ITimeMap {\n\n /**\n * Node holding data\n */\n private static class Node {\n\n final String value;\n final int timeStamp;\n\n public Node(String value, int timeStamp) {\n this.value = value;\n this.timeStamp = timeStamp;\n }\n }\n\n\n private final Map<String, List<Node>> timeMap;\n\n public TimeMapUsingMapBinarySearch() {\n this.timeMap = new HashMap<>();\n }\n\n //O(1)\n public void set(String key, String value, int timestamp) {\n\n if (!timeMap.containsKey(key))\n timeMap.put(key, new ArrayList<>());\n\n timeMap.get(key).add(new Node(value, timestamp));\n\n }\n\n //O(log(L)) ; L is the length of values in a key\n public String get(String key, int timestamp) {\n final String EMPTY_RESPONSE = "";\n if (!timeMap.containsKey(key))\n return EMPTY_RESPONSE;\n\n Node returnValue = binarySearch(timeMap.get(key), timestamp);\n return returnValue == null ? EMPTY_RESPONSE : returnValue.value;\n }\n\n\n /**\n * O(log(L))\n * Since we need to find timestamp_prev <= timestamp. then whenever we move right, cache the value you have seen as potential solution\n *\n * @param nodes nodes\n * @param timeStamp timeStamp\n * @return {@code Node} when found otherwise null\n */\n private Node binarySearch(final List<Node> nodes, int timeStamp) {\n\n if (nodes.isEmpty())\n return null;\n\n\n int low = 0, high = nodes.size() - 1;\n Node returnValue = null;\n\n while (low <= high) {\n\n int mid = (high + low) >> 1;\n\n final Node current = nodes.get(mid);\n\n if (current.timeStamp == timeStamp)\n return returnValue = nodes.get(mid);\n\n else if (current.timeStamp > timeStamp)\n high = mid - 1;\n else {\n returnValue = current;\n low = mid + 1;\n }\n }\n\n return returnValue;\n }\n\n\n /**\n * Another way\n */\n protected String binarySearch1(List<Node> nodes, int time) {\n int low = 0, high = nodes.size() - 1;\n while (low < high) {\n int mid = (low + high) >> 1;\n final Node current = nodes.get(mid);\n\n if (current.timeStamp == time)\n return current.value;\n\n if (current.timeStamp < time) {\n\n if (nodes.get(mid + 1).timeStamp > time)\n return current.value;\n\n low = mid + 1;\n } else\n high = mid - 1;\n }\n return nodes.get(low).timeStamp <= time ? nodes.get(low).value : "";\n }\n}\n\n\n```\n\n**Algo 2:** Do reverse search on values\n* Run through from end, this will make slight advantage as we may able to break the condition much before as compare to BinarySearch because of timestamp in increasing order\n\n```\n\n/**\n * Runtime: 187 ms, faster than 93.87% of Java online submissions for Time Based Key-Value Store.\n * Memory Usage: 143.4 MB, less than 8.11% of Java online submissions for Time Based Key-Value Store.\n */\nclass TimeMapUsingMapBinarySearchLinkedList implements ITimeMap {\n\n /**\n * Node holding data\n */\n private static class Node {\n\n final String key;\n final String value;\n final int timeStamp;\n\n public Node(String key, String value, int timeStamp) {\n this.key = key;\n this.value = value;\n this.timeStamp = timeStamp;\n }\n\n @Override\n public String toString() {\n return "Node{" +\n "key=\'" + key + \'\\\'\' +\n ", value=\'" + value + \'\\\'\' +\n ", timeStamp=" + timeStamp +\n \'}\';\n }\n }\n\n\n private final Map<String, LinkedList<Node>> timeMap;\n\n public TimeMapUsingMapBinarySearchLinkedList() {\n this.timeMap = new HashMap<>();\n }\n\n //O(1)\n public void set(String key, String value, int timestamp) {\n\n if (!timeMap.containsKey(key))\n timeMap.put(key, new LinkedList<>());\n\n timeMap.get(key).add(new Node(key, value, timestamp));\n\n }\n\n //O(L) ; L is the length of values in a key\n public String get(String key, int timestamp) {\n\n final String EMPTY_RESPONSE = "";\n\n if (!timeMap.containsKey(key))\n return EMPTY_RESPONSE;\n\n //Run through from end, this will make slight advantage as we may able to break the condition much before as compare to BinarySearch because of timestamp in increasing order\n final Iterator<Node> iterator = timeMap.get(key).descendingIterator();\n\n while (iterator.hasNext()) {\n Node node = iterator.next();\n if (node.timeStamp > timestamp)\n continue;\n\n return node.value;\n }\n\n return EMPTY_RESPONSE;\n }\n\n\n}\n```\n\n**Algo 3:**\nUtilize java inbuild search functionality using `TreeMap`\n\n```\n\n//243 ms\nclass TimeMapUsingTreeMap implements ITimeMap {\n\n\n //Holds the key vs tree map of timestamp vs values\n private final Map<String, TreeMap<Integer, String>> timeMap;\n\n public TimeMapUsingTreeMap() {\n this.timeMap = new HashMap<>();\n }\n\n //O(1)\n public void set(String key, String value, int timestamp) {\n\n if (!timeMap.containsKey(key))\n timeMap.put(key, new TreeMap<>());\n\n timeMap.get(key).put(timestamp, value);\n\n }\n\n //O(log(L)) ; L is the length of values in a key\n public String get(String key, int timestamp) {\n\n final String EMPTY_RESPONSE = "";\n\n if (!timeMap.containsKey(key))\n return EMPTY_RESPONSE;\n\n final Map.Entry<Integer, String> entry = timeMap.get(key).floorEntry(timestamp);\n return entry == null ? EMPTY_RESPONSE : entry.getValue();\n\n }\n\n\n}\n\n```\n\n\nInterface\n\n```\n\ninterface ITimeMap {\n\n /**\n * Stores the key and value, along with the given timestamp.\n *\n * @param key key\n * @param value value\n * @param timestamp timestamp\n */\n void set(String key, String value, int timestamp);\n\n /**\n * @param key key\n * @param timestamp timestamp\n * @return * Returns a value such that set(key, value, timestamp_prev) was called previously, with timestamp_prev <= timestamp.\n * * If there are multiple such values, it returns the one with the largest timestamp_prev.\n * * If there are no values, it returns the empty string ("").\n */\n String get(String key, int timestamp);\n}\n\n```\n\nQuote\n`Solving the question is as important as desiging the solution` | 17 | 0 | ['Binary Search', 'Tree'] | 2 |
time-based-key-value-store | Short python binary search solution | short-python-binary-search-solution-by-c-s3er | The idea is to have a map, with the values as a list with timestamp attached.\nFor get, its then a simple binary search in the list.\n\n\nfrom collections impor | Cubicon | NORMAL | 2019-01-27T04:01:13.986104+00:00 | 2020-03-02T16:52:08.468038+00:00 | 5,220 | false | The idea is to have a map, with the values as a list with timestamp attached.\nFor get, its then a simple binary search in the list.\n\n```\nfrom collections import defaultdict\nfrom bisect import bisect_right\n\nclass TimeMap:\n def __init__(self):\n self.ktimestamp = defaultdict(list)\n self.kv = defaultdict(list)\n\n def set(self, key: \'str\', value: \'str\', timestamp: \'int\') -> \'None\':\n self.kv[key].append(value)\n self.ktimestamp[key].append(timestamp)\n\n def get(self, key: \'str\', timestamp: \'int\') -> \'str\':\n if key not in self.kv: return \'\'\n idx = bisect_right(self.ktimestamp[key], timestamp)\n return \'\' if idx == 0 else self.kv[key][idx-1]\n``` | 16 | 5 | [] | 9 |
time-based-key-value-store | Java TreeMap solution. Time O(logn), Space O(n) | java-treemap-solution-time-ologn-space-o-7ldz | A two dimensional hashmap. The second dimension is sorted. \n\n\n\nclass TimeMap {\n private static final String DEFAULT_VALUE = "";\n private final HashM | edickcoding | NORMAL | 2021-09-12T23:06:59.889231+00:00 | 2021-09-12T23:06:59.889263+00:00 | 3,520 | false | A two dimensional hashmap. The second dimension is sorted. \n\n\n```\nclass TimeMap {\n private static final String DEFAULT_VALUE = "";\n private final HashMap<String, TreeMap<Integer, String>> map;\n\n /** Initialize your data structure here. */\n public TimeMap() {\n map = new HashMap<>();\n }\n \n public void set(String key, String value, int timestamp) {\n TreeMap<Integer, String> timeMap;\n if (map.containsKey(key)) {\n timeMap = map.get(key);\n } else {\n timeMap = new TreeMap<>();\n map.put(key, timeMap);\n }\n timeMap.put(timestamp, value);\n }\n \n public String get(String key, int timestamp) {\n if (map.containsKey(key)) {\n TreeMap<Integer, String> timeMap = map.get(key);\n Integer floorKey = timeMap.floorKey(timestamp);\n if (floorKey != null) {\n return timeMap.get(floorKey);\n }\n }\n return DEFAULT_VALUE;\n }\n}\n ``` | 14 | 1 | ['Tree', 'Java'] | 2 |
time-based-key-value-store | Commented | Easy to UnderStand | Faster | 100% less memory | JavaScript Solution | commented-easy-to-understand-faster-100-majyd | Please do upvote, it motivates me to write more such posts\uD83D\uDE03\n\n\nTimeMap.prototype.set = function(key, value, timestamp) {\n let obj = this.obj;\n | mrmagician | NORMAL | 2019-12-02T23:22:43.706595+00:00 | 2019-12-02T23:22:43.706649+00:00 | 2,034 | false | **Please do upvote, it motivates me to write more such posts\uD83D\uDE03**\n\n```\nTimeMap.prototype.set = function(key, value, timestamp) {\n let obj = this.obj;\n if(!obj[key]){\n obj[key] = [];\n }\n obj[key].push([value, timestamp]); \n};\n\n\nTimeMap.prototype.get = function(key, timestamp) {\n let obj = this.obj;\n let out = []\n let arr = obj[key];\n let end = arr.length-1;\n let start = 0;\n \n// Doing simple binary search\n while(start<end){ \n let mid = Math.floor((start + end)/2);\n let time = arr[mid][1];\n let val = arr[mid][0];\n if(time<timestamp){\n start = mid+1;\n// Storing the last known value which is less than timestamp\n out = arr[mid];\n }\n else if(time>timestamp){\n end = mid-1;\n }\n else{\n return val;\n } \n }\n \n \n try{\n if(arr[end][1]<=timestamp) return arr[end][0];\n else if(out[1]<timestamp) return out[0];\n }\n catch(err){\n return "";\n }\n // return out;\n};\n``` | 14 | 1 | ['Binary Search', 'JavaScript'] | 1 |
time-based-key-value-store | Beats 99%✅ | O( log n )✅ | C++ (Step by step explanation) | beats-99-o-log-n-c-step-by-step-explanat-pffq | Intuition\nThe problem requires designing a data structure to store key-value pairs with associated timestamps and efficiently retrieve the value for a given ke | monster0Freason | NORMAL | 2023-10-16T15:14:52.521892+00:00 | 2023-10-16T17:14:31.581561+00:00 | 1,058 | false | # Intuition\nThe problem requires designing a data structure to store key-value pairs with associated timestamps and efficiently retrieve the value for a given key at a specific timestamp. To achieve this, we use an unordered_map to map keys to vectors of pairs, where each pair contains a value and a timestamp. The primary challenge is to design efficient methods to set and get values associated with keys and timestamps.\n\n# Approach\n1. Design a class called `TimeMap` to encapsulate the data structure. Inside this class, maintain an unordered_map named `structure`, where keys are strings (representing the data keys), and values are vectors of pairs. Each pair consists of a string (representing the actual value) and an integer (representing the timestamp).\n\n2. Implement a private helper method called `search`, which takes a vector of pairs and a target timestamp as arguments. This method is responsible for finding the value associated with a given timestamp within a vector. The method performs binary search within the vector to efficiently locate the value or the value associated with the greatest timestamp that is less than the target timestamp.\n\n3. In the `set` method, add key-value pairs along with timestamps to the data structure. The method takes three parameters: `key`, `value`, and `timestamp`. Check if the key exists in the unordered_map. If it doesn\'t exist, create a new entry with an empty vector. Push a new pair `(value, timestamp)` into the vector associated with the key.\n\n4. In the `get` method, retrieve the value associated with a key at a specific timestamp. First, check if the key exists in the unordered_map. If the key doesn\'t exist, return an empty string, indicating that the key is not found. If the key exists, call the `search` function with the vector associated with the key and the provided timestamp.\n\n5. The `search` method performs a binary search within a vector of pairs. Maintain two pointers, `low` and `high`, representing the range in which to search. Inside a while loop, calculate the middle index, `mid`, and compare the timestamp of the middle pair with the target timestamp. Adjust the `low` and `high` pointers based on the comparison until the loop terminates. If the target timestamp is not found, return the value associated with the greatest timestamp less than the target timestamp (or an empty string if none is found).\n\n# Complexity\n- The \'set\' method has a time complexity of O(1) for adding a value to the vector associated with the key.\n- The \'get\' method performs a binary search within the vector, which has a time complexity of O(log n), where \'n\' is the number of pairs in the vector.\n- The space complexity is O(n), where \'n\' is the total number of pairs stored in the data structure, considering both the unordered_map and vectors of pairs.\n\n\n\n\n# Code\n```\nclass TimeMap {\nprivate:\n unordered_map<string, vector<pair<string, int>>> structure; \n \n string search(vector<pair<string, int>> &temp, const int ×tamp) {\n int low = 0;\n int high = temp.size() - 1;\n \n while (low <= high) {\n int mid = low + (high - low) / 2;\n \n if (temp[mid].second > timestamp) {\n high = mid - 1;\n } else if (temp[mid].second < timestamp) {\n low = mid + 1;\n } else {\n return temp[mid].first;\n }\n }\n \n return high >= 0 ? temp[high].first : "";\n }\npublic:\n TimeMap() {\n \n }\n \n void set(string key, string value, int timestamp) {\n structure[key].push_back({value, timestamp});\n }\n \n string get(string key, int timestamp) {\n if (structure.find(key) == structure.end()) {\n return "";\n }\n return search(structure[key], timestamp);\n }\n};\n```\n\n# Please upvote the solution if you understood it.\n\n | 13 | 0 | ['Binary Search', 'C++'] | 2 |
time-based-key-value-store | Easy to read C++ solution, Binary search with hashMap | easy-to-read-c-solution-binary-search-wi-p6kk | \nclass TimeMap {\nprivate:\n unordered_map<string, vector<pair<string, int>>> map; // key, {value, timestamp}\n \n string searchVal(vector<pair<string | tinfu330 | NORMAL | 2021-11-03T16:04:50.699384+00:00 | 2021-11-03T16:09:50.384880+00:00 | 3,002 | false | ```\nclass TimeMap {\nprivate:\n unordered_map<string, vector<pair<string, int>>> map; // key, {value, timestamp}\n \n string searchVal(vector<pair<string, int>> &vec, const int ×tamp) {\n int low = 0;\n int high = vec.size() - 1;\n \n while (low <= high) {\n int mid = low + (high - low) / 2;\n \n if (vec[mid].second > timestamp) {\n high = mid - 1;\n } else if (vec[mid].second < timestamp) {\n low = mid + 1;\n } else {\n return vec[mid].first;\n }\n }\n \n return high >= 0 ? vec[high].first : "";\n }\npublic:\n TimeMap() {\n \n }\n \n void set(string key, string value, int timestamp) {\n map[key].push_back({value, timestamp});\n }\n \n string get(string key, int timestamp) {\n if (map.find(key) == map.end()) {\n return "";\n }\n return searchVal(map[key], timestamp);\n }\n};\n``` | 12 | 0 | ['C', 'Binary Tree', 'C++'] | 3 |
time-based-key-value-store | Python Line BY Line Perfect Explanations - Fast & Well Commented(Using DefaultDict) | python-line-by-line-perfect-explanations-cz3i | ```\nclass TimeMap:\n\n def init(self):\n #Declare Default Dictionary because we want to append [values,timestamp] to the key\n self.d = defaul | iamkshitij77 | NORMAL | 2021-05-12T12:52:16.979705+00:00 | 2021-05-12T12:52:16.979735+00:00 | 3,748 | false | ```\nclass TimeMap:\n\n def __init__(self):\n #Declare Default Dictionary because we want to append [values,timestamp] to the key\n self.d = defaultdict(list)\n """\n Initialize your data structure here.\n """\n \n\n def set(self, key: str, value: str, timestamp: int) -> None:\n #Append the value to the key with the timestamp\n self.d[key].append([value,timestamp])\n \n\n def get(self, key: str, timestamp: int) -> str:\n #Store the value of key in a variable\n if key in self.d:\n temp = self.d[key]\n \n #print(temp) to get clear idea\n \n #Edgecase 1\n if not temp:\n return ""\n \n #Edgecase2\n if timestamp>temp[-1][1]:\n return temp[-1][0]\n \n #Egdecase3\n if timestamp<temp[0][1]:\n return ""\n \n #We will have an array with timestamp values and we have to find a particular timestamp value or smaller than it\n #We will use binary search O(logN) time\n l = 0\n r = len(temp)-1\n while l<=r:\n mid = (l+r)//2\n if temp[mid][1]>timestamp:\n r = mid-1\n else:\n l = mid +1\n \n #Return the matching value\n if l<len(temp)-1:\n return temp[l][0]\n else:\n return temp[r][0]\n | 12 | 1 | ['Binary Tree', 'Python', 'Python3'] | 2 |
time-based-key-value-store | Javascript | Binary Search | javascript-binary-search-by-shekhar90-n33j | \n\nvar TimeMap = function () {\n this.map = new Map();\n};\n\nTimeMap.prototype.set = function (key, value, timestamp) {\n const map = this.map;\n if | shekhar90 | NORMAL | 2022-05-19T17:44:00.296401+00:00 | 2022-05-19T17:44:00.297445+00:00 | 1,304 | false | ```\n\nvar TimeMap = function () {\n this.map = new Map();\n};\n\nTimeMap.prototype.set = function (key, value, timestamp) {\n const map = this.map;\n if (!map.has(key)) map.set(key, []);\n map.get(key).push([value, timestamp]);\n};\n\nTimeMap.prototype.get = function (key, timestamp) {\n const arr = this.map.get(key) || [];\n\n let [l, r] = [0, arr.length - 1];\n let res = "";\n while (l <= r) {\n const mid = Math.floor((l + r) / 2);\n const [v, t] = arr[mid];\n if (timestamp === t) return v;\n if (timestamp >= t) {\n l = mid + 1;\n res = v;\n } else r = mid - 1;\n\n }\n return res;\n};\n\n``` | 11 | 0 | ['Binary Tree', 'JavaScript'] | 0 |
time-based-key-value-store | Python solution | python-solution-by-aj_to_rescue-qm0p | Using Heaps\n\nfrom heapq import *\nclass TimeMap:\n\n def __init__(self):\n """\n Initialize your data structure here.\n """\n s | aj_to_rescue | NORMAL | 2019-12-12T05:47:04.060278+00:00 | 2019-12-12T05:47:04.060316+00:00 | 1,642 | false | Using Heaps\n```\nfrom heapq import *\nclass TimeMap:\n\n def __init__(self):\n """\n Initialize your data structure here.\n """\n self.times = collections.defaultdict(list)\n \n def set(self, key: str, value: str, timestamp: int) -> None:\n # -1 to make it a maxheap\n heappush(self.times[key], (timestamp*-1, value))\n \n def get(self, key: str, timestamp: int) -> str:\n res = ""\n for value in self.times[key]:\n if abs(value[0]) <= timestamp:\n res = value[1]\n break\n return res\n```\n\nBinary search:\n```\nclass TimeMap:\n\n def __init__(self):\n """\n Initialize your data structure here.\n """\n self.times = collections.defaultdict(list)\n \n def set(self, key: str, value: str, timestamp: int) -> None:\n self.times[key].append((timestamp, value))\n \n def get(self, key: str, timestamp: int) -> str:\n values = self.times[key]\n if not values: return \'\'\n left, right = 0, len(values) - 1\n while left < right:\n mid = (left + right + 1) // 2\n pre_time, value = values[mid]\n if pre_time > timestamp:\n right = mid - 1\n else:\n left = mid\n return values[left][1] if values[left][0] <= timestamp else \'\'\n```\n | 11 | 0 | [] | 4 |
time-based-key-value-store | JAVA || 98 % Faster Code || HashMap | java-98-faster-code-hashmap-by-shivrasto-8rsy | \tPLEASE UPVOTE IF YOU LIKE.\n\nclass TimeMap {\n\n Map<String, List<Pair<String, Integer>>> map = new HashMap<>();\n public TimeMap() { }\n \n publ | shivrastogi | NORMAL | 2022-10-06T04:45:17.807032+00:00 | 2022-10-06T04:45:17.807077+00:00 | 1,308 | false | \tPLEASE UPVOTE IF YOU LIKE.\n```\nclass TimeMap {\n\n Map<String, List<Pair<String, Integer>>> map = new HashMap<>();\n public TimeMap() { }\n \n public void set(String key, String value, int timestamp) {\n if(!map.containsKey(key)) {\n map.put(key, new ArrayList<>());\n }\n map.get(key).add(new Pair(value, timestamp));\n }\n \n public String get(String key, int timestamp) {\n if(!map.containsKey(key)) {\n return "";\n }\n return binaryGet(map.get(key), 0, map.get(key).size() - 1, timestamp);\n }\n \n private String binaryGet(List<Pair<String, Integer>> list, int start, int end, int timestamp) {\n \n if(start > end) return "";\n \n int mid = start + (end - start) / 2;\n Pair<String, Integer> midItem = list.get(mid);\n \n if(timestamp == midItem.getValue()) return midItem.getKey();\n \n if(timestamp < midItem.getValue()) {\n if(mid - 1 < 0) return "";\n if(list.get(mid - 1).getValue() <= timestamp) return list.get(mid - 1).getKey();\n return binaryGet(list, start, mid - 1, timestamp);\n }\n else {\n if(mid + 1 >= list.size()) return midItem.getKey();\n if(list.get(mid + 1).getValue() == timestamp) return list.get(mid + 1).getKey();\n return binaryGet(list, mid + 1, end, timestamp);\n }\n }\n}\n``` | 10 | 1 | ['Java'] | 1 |
time-based-key-value-store | Beats 99%✅ | O( log n )✅ | Python (Step by step explanation) | beats-99-o-log-n-python-step-by-step-exp-fj3w | Intuition\n Add a brief description of your first thoughts on how to solve this problem. \n\nThe problem involves designing a data structure that allows you to | monster0Freason | NORMAL | 2023-10-16T13:20:54.175917+00:00 | 2023-10-16T17:15:31.871342+00:00 | 1,288 | false | # Intuition\n<!-- Add a brief description of your first thoughts on how to solve this problem. -->\n\nThe problem involves designing a data structure that allows you to set values associated with keys at specific timestamps and retrieve the values at a specified timestamp for a given key. The intuition is to use a data structure that can efficiently store and retrieve values based on timestamps.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n1. Create a class `TimeMap` to manage the data structure.\n2. In the `__init__` method, initialize an empty dictionary (`structure`) to store the key-value pairs with timestamps.\n\n3. In the `set` method:\n - If the key doesn\'t exist in the `structure`, create an entry with an empty list.\n - Append the value and timestamp as a pair to the list associated with the key.\n\n4. In the `get` method:\n - Initialize an empty string `ans` to store the result.\n - Retrieve the list of value-timestamp pairs associated with the key using `self.structure.get(key, [])`.\n\n5. Perform a binary search on the list to find the value associated with the closest timestamp less than or equal to the given timestamp.\n - Initialize `low` and `high` pointers to search the list.\n - While `low` is less than or equal to `high`, calculate the middle index (`mid`).\n - If the timestamp at `temp[mid]` is less than or equal to the target timestamp, update `ans` with the value at `temp[mid]` and adjust `low` to `mid + 1`.\n - If the timestamp at `temp[mid]` is greater than the target timestamp, adjust `high` to `mid - 1`.\n\n6. Return `ans` as the result, which will be the value associated with the closest timestamp that is less than or equal to the given timestamp.\n\nThe provided approach allows you to efficiently store and retrieve values based on timestamps using binary search.\n\n# Complexity\n- Time complexity:\n - The `set` method has a time complexity of O(1) for adding a value to the list associated with the key.\n - The `get` method performs binary search, which has a time complexity of O(log n), where \'n\' is the number of values associated with the key.\n- Space complexity:\n - The space complexity is O(n) as it depends on the number of values stored in the `structure` dictionary.\n\n# Code\n```python\nclass TimeMap:\n\n def __init__(self):\n self.structure = {}\n \n\n def set(self, key: str, value: str, timestamp: int) -> None:\n if key not in self.structure:\n self.structure[key] = []\n self.structure[key].append([value, timestamp])\n \n\n def get(self, key: str, timestamp: int) -> str:\n ans = ""\n temp = self.structure.get(key, [])\n\n low, high = 0, len(temp) - 1\n while low <= high:\n mid = (low + high) // 2\n\n if temp[mid][1] <= timestamp:\n ans = temp[mid][0]\n low = mid + 1\n else:\n high = mid - 1\n return ans\n```\n\n# Please upvote the solution if you understood it.\n\n | 9 | 0 | ['Binary Search', 'Python3'] | 2 |
time-based-key-value-store | C++ || Binary search in map of {string , vector} | c-binary-search-in-map-of-string-vector-cbv7r | \nclass TimeMap {\npublic:\n map<string, vector<pair<int,string>>> mp;\n// TimeMap() {\n \n// }\n \n void set(string key, string value, | ashay028 | NORMAL | 2022-10-06T12:18:52.732602+00:00 | 2022-10-06T12:18:52.732639+00:00 | 354 | false | ```\nclass TimeMap {\npublic:\n map<string, vector<pair<int,string>>> mp;\n// TimeMap() {\n \n// }\n \n void set(string key, string value, int timestamp) {\n mp[key].push_back({timestamp,value});\n }\n \n string get(string key, int timestamp) {\n string ans="";\n // for(auto &it : mp[key] )\n // {\n // if(it.first>timestamp) break;\n // ans=it.second;\n // }\n int left=0,right=mp[key].size()-1,mid;\n while(left<=right)\n {\n mid=(left+right)/2;\n if(mp[key][mid].first<timestamp) left=mid+1;\n else if(mp[key][mid].first==timestamp) return mp[key][mid].second;\n else right=mid-1;\n \n }\n if(right>=0) ans=mp[key][right].second;\n return ans;\n }\n};\n``` | 9 | 0 | [] | 2 |
time-based-key-value-store | ✅ C++ || Two approaches || Using Binary Search & Map | c-two-approaches-using-binary-search-map-8mag | Using Map\n\nclass TimeMap {\npublic:\n unordered_map<string, map<int, string, greater<int>>> mp;\n TimeMap() {}\n \n void set(string key, string va | mayank888k | NORMAL | 2022-05-23T18:39:15.601568+00:00 | 2022-05-23T18:39:15.601596+00:00 | 1,394 | false | **Using Map**\n```\nclass TimeMap {\npublic:\n unordered_map<string, map<int, string, greater<int>>> mp;\n TimeMap() {}\n \n void set(string key, string value, int timestamp) {\n mp[key][timestamp] = value;\n }\n \n string get(string key, int timestamp) {\n \n auto &v = mp[key];\n \n auto itm = v.lower_bound(timestamp);\n if(itm == v.end()) return "";\n \n return itm->second;\n\n }\n};\n```\n**Using Binary Search**\n```\n\nclass TimeMap {\npublic:\n unordered_map<string, vector<pair<int, string>>> mp;\n TimeMap() {}\n \n void set(string key, string value, int timestamp) {\n mp[key].push_back({timestamp, value});\n }\n \n string get(string key, int timestamp) {\n \n auto &v = mp[key];\n \n int low = 0;\n int high = v.size()-1;\n int idx = -1;\n \n while(low <= high)\n {\n int mid = low + (high - low)/2;\n if(v[mid].first <= timestamp)\n {\n idx = mid;\n low = mid+1;\n }\n else high = mid-1;\n }\n if(idx == -1) return "";\n return v[idx].second;\n\n }\n \n};\n```\n | 9 | 0 | ['C', 'Binary Tree', 'C++'] | 1 |
time-based-key-value-store | Java || 100% faster || easy solution || binary search | java-100-faster-easy-solution-binary-sea-mog1 | \nclass TimeValue {\n String val;\n int timestamp;\n \n public TimeValue(String val, int time){\n this.val = val;\n timestamp = time;\ | achyutav | NORMAL | 2021-11-20T02:52:49.101325+00:00 | 2022-02-08T23:38:32.774548+00:00 | 2,482 | false | ```\nclass TimeValue {\n String val;\n int timestamp;\n \n public TimeValue(String val, int time){\n this.val = val;\n timestamp = time;\n }\n}\nclass TimeMap {\n Map<String, List<TimeValue>> map;\n public TimeMap() {\n map = new HashMap<>();\n }\n \n public void set(String key, String value, int timestamp) {\n map.computeIfAbsent(key, k -> new ArrayList<>()).add(new TimeValue(value, timestamp));\n }\n \n public String get(String key, int timestamp) {\n List<TimeValue> list = map.getOrDefault(key, null);\n if(list == null) return "";\n int low = 0, high = list.size()-1;\n if(list.get(low).timestamp > timestamp) return "";\n if(list.get(high).timestamp <= timestamp) return list.get(high).val;\n while(low < high){\n int mid = (low + high) / 2;\n if(list.get(mid).timestamp == timestamp) return list.get(mid).val;\n if(list.get(mid).timestamp < timestamp) low = mid + 1;\n else high = mid - 1;\n \n }\n return list.get(low - 1).val;\n \n }\n}\n\n/**\n * Your TimeMap object will be instantiated and called as such:\n * TimeMap obj = new TimeMap();\n * obj.set(key,value,timestamp);\n * String param_2 = obj.get(key,timestamp);\n */\n``` | 9 | 0 | ['Binary Tree', 'Java'] | 4 |
time-based-key-value-store | Key Value Store logN solution with explanation | key-value-store-logn-solution-with-expla-ltg1 | Intuition\n Describe your first thoughts on how to solve this problem. \nDesign Redis\n# Approach\nBasic set operations, the tricky part here is the get operati | samitmohan | NORMAL | 2022-12-11T07:13:26.650916+00:00 | 2022-12-11T07:13:26.650968+00:00 | 1,700 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nDesign Redis\n# Approach\nBasic set operations, the tricky part here is the get operation which hints at binary search (as it\'s based on increasing timestamp values)\nOther than that, use a simple hashmap to implement a KVS where key = key and value = list of values [val and timestamp]\n# Complexity\n- Time complexity:\n$$O(logn)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\n# How to know when to use binary search -> Constraints\n# O(logN)\nclass TimeMap:\n # bin search soln\n def __init__(self):\n self.store = {} # hashmap, key = string, val = [list of [val, timestamp]] {foo -> [bar, 1]}\n\n def set(self, key: str, value: str, timestamp: int) -> None:\n if key not in self.store:\n # insert\n self.store[key] = [] # set to empty list.\n self.store[key].append([value, timestamp]) # append val & times\n\n def get(self, key: str, timestamp: int) -> str:\n res = "" # if not exist just return empty\n values = self.store.get(key, []) # find match it\'ll return that list if doesn\'t then returns empty list (by default) [values is a list]\n \n # binary search\n low, high = 0, len(values) - 1\n while low <= high:\n mid = (low + high) // 2\n # values[mid] will be a pair of values and timestamps\n # we only need to check timestamps (which is in incr order) hence values[mid][1]\n if values[mid][1] <= timestamp:\n # if equal or less than timestamp -> ans found\n res = values[mid][0] # closest we\'ve seen so far -> store in ans\n low = mid + 1 # check for closer values\n else:\n # not allowed (acc to question)\n high = mid - 1 # don\'t assign any result here as this is an invalid val\n return res\n``` | 8 | 0 | ['Hash Table', 'Binary Search', 'Python3'] | 1 |
time-based-key-value-store | python 3 || binSearch || T/S: 99%/97% | python-3-binsearch-ts-9997-by-spaulding-bd2s | \nclass TimeMap:\n def __init__(self):\n\t\n self.values = defaultdict(list)\n self.stamps = defaultdict(list)\n \n def set(self, key: st | Spaulding_ | NORMAL | 2022-10-06T00:14:08.545901+00:00 | 2024-05-31T19:54:27.065195+00:00 | 370 | false | ```\nclass TimeMap:\n def __init__(self):\n\t\n self.values = defaultdict(list)\n self.stamps = defaultdict(list)\n \n def set(self, key: str, value: str, timestamp: int) -> None:\n\t\n self.values[key].append(value)\n self.stamps[key].append(timestamp)\n return\n \n def get(self, key: str, timestamp: int) -> str:\n\t\n i = bisect_right(self.stamps[key],timestamp)-1\n return \'\' if i == -1 else self.values[key][i]\n```\n[https://leetcode.com/problems/time-based-key-value-store/submissions/1273601574/](https://leetcode.com/problems/time-based-key-value-store/submissions/1273601574/)\n\nI could be wrong, but I think that time complexity is *O*(log *N*) and space complexity is *O*(*N*), in which *N* ~ `len(stamps)`.\n | 8 | 0 | ['Python'] | 0 |
time-based-key-value-store | [JS] Using HashMap and Binary Search | js-using-hashmap-and-binary-search-by-wi-to2v | \nclass TimeMap {\n constructor() { // O(1)\n this.map = new Map(); // SC: O(T)\n }\n set(key, value, timestamp) { // O(1)\n | wintryleo | NORMAL | 2021-08-28T12:40:36.814630+00:00 | 2021-08-28T12:42:09.412427+00:00 | 1,569 | false | ```\nclass TimeMap {\n constructor() { // O(1)\n this.map = new Map(); // SC: O(T)\n }\n set(key, value, timestamp) { // O(1)\n const keyVals = this.map.has(key) ? this.map.get(key) : [];\n keyVals.push([timestamp, value]);\n this.map.set(key, keyVals);\n }\n get(key, timestamp) { // O(logT)\n const keyTimestamps = this.map.has(key) ? this.map.get(key) : [];\n let left = 0,\n right = keyTimestamps.length - 1,\n mid, ts = null\n \n\t\t// using binary search to find the ts <= timestamp\n while(left <= right) {\n mid = left + Math.floor((right - left) / 2);\n if(keyTimestamps[mid][0] <= timestamp) {\n ts = keyTimestamps[mid][1];\n left = mid + 1;\n } else {\n right = mid - 1;\n }\n }\n return ts === null ? "" : ts;\n }\n}\n```\nTime Complexity:\n`set: O(1)`\n`get: O(logT)`\nSpace Complexity: `O(T)`\n[T - number of timestamps]\n\nSimilar approach as https://leetcode.com/problems/snapshot-array/discuss/1429705/JS-Initial-and-Optimised-solution Solution 2 and 3 | 8 | 0 | ['Binary Tree', 'JavaScript'] | 3 |
time-based-key-value-store | c++, supper short, map and unordered_map | c-supper-short-map-and-unordered_map-by-bjb3g | \nclass TimeMap {\nprivate:\n unordered_map<string, map<int, string>> m;\npublic:\n /** Initialize your data structure here. */\n TimeMap() {\n | huawenli | NORMAL | 2020-05-13T05:52:56.461467+00:00 | 2020-05-13T05:52:56.461505+00:00 | 771 | false | ```\nclass TimeMap {\nprivate:\n unordered_map<string, map<int, string>> m;\npublic:\n /** Initialize your data structure here. */\n TimeMap() {\n \n }\n \n void set(string key, string value, int timestamp) {\n m[key][timestamp] = value;\n }\n \n string get(string key, int timestamp) {\n if (m.find(key) == m.end()) {\n return "";\n }\n auto it = m[key].upper_bound(timestamp);\n if (it != m[key].begin()) {\n it--;\n return it->second;\n } else {\n return "";\n }\n }\n};\n\n```\n | 8 | 0 | [] | 3 |
time-based-key-value-store | Beats 91.26% java. Modified Binary Search Explanation with Pics | beats-9126-java-modified-binary-search-e-liu7 | Intuition\n Describe your first thoughts on how to solve this problem. \nBinary search\n\nExplanation for the modified binary search:\n\n\n\n Conventionaly we p | dhanush_kannan_dk | NORMAL | 2024-10-02T19:15:03.765439+00:00 | 2024-10-02T19:28:16.267285+00:00 | 949 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBinary search\n\nExplanation for the modified binary search:\n\n\n\n* Conventionaly we push the left to right.\n* When we push the left, mid selection should be left.\n* Here we need to push the right to left (to get the previous value).\n* When we push the right, mid selection should be right (to avoid infinite loop)\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nMap + List< Data >\n\n# Complexity\n- Time complexity: \n set: O(1) \n get: O(log 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)$$ -->\nThe space complexity is O(K + T), where K is the number of unique keys and T is the total number of set calls or the total number of timestamp and value pairs\n\n# Code\n```java []\nclass Data {\n String val;\n int time;\n Data(String val, int time) {\n this.val = val;\n this.time = time;\n }\n}\nclass TimeMap {\n\n /** Initialize your data structure here. */\n Map<String, List<Data>> map;\n public TimeMap() {\n map = new HashMap<String, List<Data>>();\n }\n\n public void set(String key, String value, int timestamp) {\n map.computeIfAbsent(key, k -> new ArrayList<Data>()).add(new Data(value, timestamp));\n }\n\n public String get(String key, int timestamp) {\n if (!map.containsKey(key)) return "";\n return binarySearch(map.get(key), timestamp);\n }\n\n private String binarySearch(List<Data> list, int time) {\n int left = 0, right = list.size() - 1;\n while (left < right) {\n int mid = (left + right + 1) >>> 1;\n if (time < list.get(mid).time)\n right = mid - 1;\n else\n left = mid;\n }\n return list.get(left).time <= time ? list.get(left).val : ""; // left == right\n }\n}\n``` | 7 | 0 | ['Java'] | 2 |
time-based-key-value-store | c++ || 3 line code || binary search in map of pair in 1 line | c-3-line-code-binary-search-in-map-of-pa-283d | \n\n# Code\n\nclass TimeMap {\npublic:\n map<pair<string , int> , string > mp;\n\n TimeMap() {}\n\n void set(string key, string val, int tt) { mp[{key | amankatiyar783597 | NORMAL | 2023-03-28T13:49:45.815922+00:00 | 2023-03-28T13:57:14.256099+00:00 | 1,087 | false | \n\n# Code\n```\nclass TimeMap {\npublic:\n map<pair<string , int> , string > mp;\n\n TimeMap() {}\n\n void set(string key, string val, int tt) { mp[{key , tt}] = val; }\n\n string get(string key, int tt) {\n auto it = mp.lower_bound({key,tt});\n if(it != mp.end()) if((*it).first.first == key && (*it).first.second <= tt ) return (*it).second; it--;\n if((*it).first.first == key && (*it).first.second <= tt ) return (*it).second; return "";\n }\n};\n\n``` | 7 | 1 | ['C++'] | 0 |
time-based-key-value-store | Python3 - HashMap and Binary Search Solution. | python3-hashmap-and-binary-search-soluti-g338 | \nclass TimeMap:\n\n def __init__(self):\n self.s_v = {}\n self.s_t = {}\n\n def set(self, key: str, value: str, timestamp: int) -> None:\n | yukkk | NORMAL | 2022-10-06T15:56:10.259813+00:00 | 2022-10-06T15:56:10.259857+00:00 | 2,340 | false | ```\nclass TimeMap:\n\n def __init__(self):\n self.s_v = {}\n self.s_t = {}\n\n def set(self, key: str, value: str, timestamp: int) -> None:\n self.s_v.setdefault(key, []).append(value)\n self.s_t.setdefault(key, []).append(timestamp)\n\n def get(self, key: str, timestamp: int) -> str:\n lo, hi = 0, len(self.s_t.get(key, [])) - 1\n mid = 0\n while lo <= hi:\n mid = lo + (hi - lo) // 2\n if self.s_t[key][mid] == timestamp: break\n elif self.s_t[key][mid] > timestamp: hi = mid - 1\n else: lo = mid + 1\n else:\n mid = lo - 1\n return self.s_v[key][mid] if mid >= 0 else ""\n``` | 7 | 0 | ['Binary Tree', 'Python', 'Python3'] | 0 |
time-based-key-value-store | Java || HashMap + TreeMap Solution | java-hashmap-treemap-solution-by-kadamyo-1rd8 | \nclass TimeMap {\n HashMap<String,TreeMap<Integer,String>> hm;\n public TimeMap() {\n hm=new HashMap<>();\n }\n \n public void set(String | kadamyogesh7218 | NORMAL | 2022-10-06T05:37:41.531432+00:00 | 2022-10-06T05:37:41.531467+00:00 | 1,271 | false | ```\nclass TimeMap {\n HashMap<String,TreeMap<Integer,String>> hm;\n public TimeMap() {\n hm=new HashMap<>();\n }\n \n public void set(String key, String value, int timestamp) {\n if(!hm.containsKey(key)){\n TreeMap<Integer,String> hm2=new TreeMap<>();\n hm2.put(timestamp,value);\n hm.put(key,hm2);\n }\n else{\n hm.get(key).put(timestamp,value);\n }\n }\n \n public String get(String key, int timestamp) {\n if(hm.containsKey(key)){\n if(hm.get(key).containsKey(timestamp)){\n return hm.get(key).get(timestamp);\n }\n else{\n Integer prevTimestamp=hm.get(key).floorKey(timestamp);\n if(prevTimestamp!=null){\n return hm.get(key).get(prevTimestamp);\n }\n // for(int i=timestamp;i>=1;i--){\n // if(hm.get(key).containsKey(i)){\n // return hm.get(key).get(i);\n // }\n // }\n }\n }\n return "";\n }\n}\n``` | 7 | 0 | ['Tree', 'Java'] | 2 |
time-based-key-value-store | [EXPLAINED] Using TypeScript, Runtime Beats 94.74%, Memory Beats 42.10% | explained-using-typescript-runtime-beats-ba2r | Intuition\nStore values with timestamps in sorted order for each key. Use binary search to efficiently find the most recent value before the queried timestamp. | r9n | NORMAL | 2024-08-22T00:48:44.868857+00:00 | 2024-08-22T00:48:44.868878+00:00 | 423 | false | # Intuition\nStore values with timestamps in sorted order for each key. Use binary search to efficiently find the most recent value before the queried timestamp. This ensures quick lookups and updates.\n\n# Approach\nData Storage: Use a Map where each key maps to a sorted list of timestamp-value pairs.\n\nInsertion: Add new timestamp-value pairs to the list associated with the key.\n\nQuery: Use binary search on the sorted list to find the closest timestamp less than or equal to the queried timestamp.\n\n# Complexity\n Time complexity:\nO(logN) for binary search (set and get).\n\nSpace complexity:\nO(N) for storing timestamps and values.\n\n# Code\n```typescript []\nclass TimeMap {\n private map: Map<string, [number[], string[]]>; // [timestamps, values]\n\n constructor() {\n this.map = new Map();\n }\n\n set(key: string, value: string, timestamp: number): void {\n if (!this.map.has(key)) {\n this.map.set(key, [[], []]); // Initialize with empty arrays for timestamps and values\n }\n const [timestamps, values] = this.map.get(key)!;\n const index = this.binarySearch(timestamps, timestamp);\n if (index < timestamps.length && timestamps[index] === timestamp) {\n values[index] = value; // Update value if timestamp exists\n } else {\n timestamps.splice(index, 0, timestamp); // Insert new timestamp\n values.splice(index, 0, value); // Insert corresponding value\n }\n }\n\n get(key: string, timestamp: number): string {\n if (!this.map.has(key)) {\n return "";\n }\n const [timestamps, values] = this.map.get(key)!;\n const index = this.binarySearch(timestamps, timestamp);\n return index > 0 ? values[index - 1] : ""; // Return the value for the closest timestamp\n }\n\n private binarySearch(timestamps: number[], target: number): number {\n let low = 0;\n let high = timestamps.length;\n while (low < high) {\n const mid = Math.floor((low + high) / 2);\n if (timestamps[mid] <= target) {\n low = mid + 1;\n } else {\n high = mid;\n }\n }\n return low;\n }\n}\n\n// Example usage:\nconst timeMap = new TimeMap();\ntimeMap.set("foo", "bar", 1);\nconsole.log(timeMap.get("foo", 1)); // Output: "bar"\nconsole.log(timeMap.get("foo", 3)); // Output: "bar"\ntimeMap.set("foo", "bar2", 4);\nconsole.log(timeMap.get("foo", 4)); // Output: "bar2"\nconsole.log(timeMap.get("foo", 5)); // Output: "bar2"\n\n``` | 6 | 0 | ['TypeScript'] | 1 |
time-based-key-value-store | Java | Hash map and Binary Search | Explained | java-hash-map-and-binary-search-explaine-xm0c | Intuition\nWe need to search values by key and timestamp.\nFirst of all let\'s bucket all relevant entires together by key, we will do this with a hash map.\n\n | nadaralp | NORMAL | 2022-10-06T05:08:17.753261+00:00 | 2022-10-06T05:08:17.753305+00:00 | 386 | false | # Intuition\nWe need to search values by `key` and `timestamp`.\nFirst of all let\'s bucket all relevant entires together by key, we will do this with a `hash map`.\n\nNow every key has many timestamps with values, we can have an array to represent that. Because the timestamp come in `increasing` order, the insert to our list is going to be `O(1)` because no re-indexing is done, we only append to the end.\n\nWhenever we need to get an element, we first search the `key` in the hash map `O(1)`, and then binary search the timestamp values `O(logn)` because we know we have inserted them in linearly increasing order.\n\nThe code should be very readable. Just go through it.\n\n# Code\n```\nimport java.util.Optional;\n\nclass TimeStampedValue {\n public int timestamp;\n public String value;\n \n public TimeStampedValue(int timestamp, String value) {\n this.timestamp = timestamp;\n this.value = value;\n }\n}\n\nclass TimeMap {\n Map<String, ArrayList<TimeStampedValue>> entriesByKey;\n\n public TimeMap() {\n entriesByKey = new HashMap<>(); \n }\n \n // We know that timestmap is strictly increasing. Hence O(1) insertion\n public void set(String key, String value, int timestamp) {\n if(!entriesByKey.containsKey(key)) {\n entriesByKey.put(key, new ArrayList<TimeStampedValue>());\n }\n ArrayList<TimeStampedValue> timeStampedValues = entriesByKey.get(key);\n timeStampedValues.add(new TimeStampedValue(timestamp, value));\n }\n \n // O(logn) because of binary search\n public String get(String key, int timestamp) {\n if(!entriesByKey.containsKey(key)) return "";\n \n ArrayList<TimeStampedValue> timeStampedValues = entriesByKey.get(key);\n Optional<TimeStampedValue> timeStamp = binarySearchTimestamp(timeStampedValues, timestamp);\n if(timeStamp.isEmpty()) {\n return "";\n }\n \n return timeStamp.get().value;\n }\n \n private Optional<TimeStampedValue> binarySearchTimestamp(ArrayList<TimeStampedValue> arr, int target) {\n int left = 0, right = arr.size() - 1;\n int matchIndex = -1;\n \n while (left <= right) {\n int mid = left + (right - left) / 2;\n TimeStampedValue cur = arr.get(mid);\n if(cur.timestamp <= target) {\n matchIndex = mid;\n left = mid + 1;\n }\n else {\n right = mid - 1;\n }\n }\n \n if(matchIndex == -1) {\n return Optional.empty();\n }\n return Optional.of(arr.get(matchIndex));\n }\n}\n``` | 6 | 0 | ['Java'] | 0 |
time-based-key-value-store | JAVA || USING HASHMAP & UPPERBOUND | java-using-hashmap-upperbound-by-flyroko-r1hw | \n\n class pair{\n int x;\n String y;\n pair(int x1,String y1){\n x=x1;\n y=y1;\n }\n}\n \n\t class TimeMap {\n Map> | flyRoko123 | NORMAL | 2022-08-12T07:39:39.074898+00:00 | 2022-08-12T07:39:39.074927+00:00 | 172 | false | \n\n class pair{\n int x;\n String y;\n pair(int x1,String y1){\n x=x1;\n y=y1;\n }\n}\n \n\t class TimeMap {\n Map<String,List<pair>> m;\n Map<Integer,String> m1;\n public TimeMap() {\n m=new HashMap<>();\n m1=new HashMap<>();\n }\n \n public void set(String key, String val, int time) {\n if(!m.containsKey(key)){\n m.put(key,new ArrayList<>());\n }\n m.get(key).add(new pair(time,val));\n m1.put(time,val);\n }\n \n public String get(String key, int time) {\n if(!m.containsKey(key))return "";\n List<pair> l=m.get(key);\n \n int ind=upperbound(l,time);\n \n if(ind==-1)return "";\n return m1.get(ind);\n }\n public int upperbound(List<pair> l,int x1){\n int i=0;\n int j=l.size()-1;\n int ans=-1;\n while(i<=j){\n int mid=(i+j)/2;\n if(l.get(mid).x<=x1){\n ans=mid;\n i=mid+1;\n }\n else j=mid-1;\n }\n if(ans==-1)return -1;\n return l.get(ans).x;\n }\n}\n\n \n /**\n * Your TimeMap object will be instantiated and called as such:\n * TimeMap obj = new TimeMap();\n * obj.set(key,value,timestamp);\n * String param_2 = obj.get(key,timestamp);\n */ | 6 | 0 | [] | 0 |
time-based-key-value-store | Java TreeMap Solution | java-treemap-solution-by-ortez1-v6xg | \nclass TimeMap {\n Map<String, TreeMap<Integer, String>> map = new HashMap<>();\n\n public void set(String key, String value, int timestamp) {\n map.putIf | ortez1 | NORMAL | 2022-01-19T03:45:12.130419+00:00 | 2022-01-19T03:45:12.130454+00:00 | 616 | false | ```\nclass TimeMap {\n Map<String, TreeMap<Integer, String>> map = new HashMap<>();\n\n public void set(String key, String value, int timestamp) {\n map.putIfAbsent(key, new TreeMap<>());\n map.get(key).put(timestamp, value);\n }\n\n public String get(String key, int timestamp) {\n if (!map.containsKey(key)) return "";\n Integer timestampPrev = map.get(key).floorKey(timestamp);\n return timestampPrev != null ? map.get(key).get(timestampPrev) : "";\n }\n}\n``` | 6 | 0 | ['Java'] | 0 |
time-based-key-value-store | Map with Binary Search Approach || C++ Clean Code | map-with-binary-search-approach-c-clean-szvad | Code :\n\n\nclass TimeMap {\n\t// Map { key, vec[timestamp, value] }\n unordered_map<string,vector<pair<int, string>>> mp; \npublic: \n \n static bool | i_quasar | NORMAL | 2021-10-10T15:27:45.332638+00:00 | 2021-10-10T15:27:45.332683+00:00 | 694 | false | # Code :\n\n```\nclass TimeMap {\n\t// Map { key, vec[timestamp, value] }\n unordered_map<string,vector<pair<int, string>>> mp; \npublic: \n \n static bool compare(const int& val, const pair<int, string>& a) {\n return a.first > val;\n }\n\n TimeMap() {\n \n }\n \n void set(string key, string value, int timestamp) {\n mp[key].push_back({timestamp, value});\n }\n \n string get(string key, int timestamp) {\n auto& vec = mp[key];\n auto itr = upper_bound(vec.begin(), vec.end(), timestamp, compare);\n \n return itr == vec.begin() ? "" : prev(itr)->second;\n }\n};\n``` | 6 | 0 | ['C', 'Binary Tree'] | 2 |
time-based-key-value-store | [Python3/Python] Simple solution using bisect module. | python3python-simple-solution-using-bise-f8it | \nimport bisect\nfrom collections import defaultdict\n\nclass TimeMap:\n\n def __init__(self):\n self.values = defaultdict(list)\n self.timesta | ssshukla26 | NORMAL | 2021-08-29T03:30:18.446185+00:00 | 2021-08-29T03:30:18.446210+00:00 | 1,087 | false | ```\nimport bisect\nfrom collections import defaultdict\n\nclass TimeMap:\n\n def __init__(self):\n self.values = defaultdict(list)\n self.timestamps = defaultdict(list)\n return\n\n def set(self, key: str, value: str, timestamp: int) -> None:\n self.values[key].append(value)\n self.timestamps[key].append(timestamp)\n # Note: All the timestamps are strictly increasing hence no sorting required.\n return\n\n def get(self, key: str, timestamp: int) -> str:\n res = ""\n if key in self.timestamps:\n # NOTE: If there are multiple such values returns the value associated with the largest timestamp_prev\n pos = bisect.bisect_right(self.timestamps[key], timestamp)\n res = self.values[key][pos-1] if pos else res\n return res\n\n\n# Your TimeMap object will be instantiated and called as such:\n# obj = TimeMap()\n# obj.set(key,value,timestamp)\n# param_2 = obj.get(key,timestamp)\n``` | 6 | 0 | ['Python', 'Python3'] | 1 |
time-based-key-value-store | simple python solution, beat 99.9% | simple-python-solution-beat-999-by-xiemi-6bcu | ```\nclass TimeMap:\n\n def init(self):\n """\n Initialize your data structure here.\n """\n self.dct = {}\n\n def set(self, k | xiemian | NORMAL | 2021-03-29T22:20:00.852627+00:00 | 2021-03-29T22:20:53.186062+00:00 | 298 | false | ```\nclass TimeMap:\n\n def __init__(self):\n """\n Initialize your data structure here.\n """\n self.dct = {}\n\n def set(self, key: str, value: str, timestamp: int) -> None:\n if key not in self.dct:\n self.dct[key] = [[timestamp], [value]]\n else:\n self.dct[key][0].append(timestamp)\n self.dct[key][1].append(value)\n\n def get(self, key: str, timestamp: int) -> str:\n if key not in self.dct: return ""\n time, val = self.dct[key]\n idx = bisect.bisect_right(time, timestamp)\n if idx == 0: return ""\n return val[idx - 1]\n | 6 | 0 | [] | 1 |
time-based-key-value-store | Java Solution Map with Binary Search and Python bisect | java-solution-map-with-binary-search-and-2k7y | Java\n\nclass TimeMap {\n class Tval{\n String val;\n int time;\n Tval(String x, int y){\n val = x; time = y; \n }\n | Big_Hustler | NORMAL | 2020-04-27T17:27:09.282930+00:00 | 2024-01-03T16:13:00.229159+00:00 | 1,390 | false | Java\n```\nclass TimeMap {\n class Tval{\n String val;\n int time;\n Tval(String x, int y){\n val = x; time = y; \n }\n }\n Map<String,ArrayList<Tval>> map;\n /** Initialize your data structure here. */\n public TimeMap() {\n map = new HashMap<>();\n }\n \n public void set(String key, String value, int timestamp) {\n if(!map.containsKey(key)) map.put(key,new ArrayList<>());\n map.get(key).add(new Tval(value,timestamp));\n }\n \n public String get(String key, int timestamp) {\n int ind = binarySearch(map.getOrDefault(key,new ArrayList<Tval>()),timestamp);\n if(ind == -1) return "";\n return map.get(key).get(ind).val;\n }\n \n public int binarySearch(ArrayList<Tval> list,int t){\n int l = 0,r = list.size() - 1,ind = -1;\n if(r == -1) return r;\n while(l <= r){\n int mid = l + (r - l)/2;\n int x = list.get(mid).time;\n if(x == t) return mid;\n else if(x > t) r = mid - 1;\n else {\n l = mid + 1;\n ind = mid;\n }\n }\n return ind;\n }\n \n}\n\n```\nPython\n\n```\nclass Tval:\n def __init__(self, x , y):\n self.val = x\n self.time = y\n\nclass TimeMap:\n\n def __init__(self):\n self.data = {}\n\n def set(self, key: str, value: str, timestamp: int) -> None:\n data = self.data\n if key not in data:\n data[key] = []\n data[key].append(Tval(value, timestamp))\n\n def get(self, key: str, timestamp: int) -> str:\n if key not in self.data:\n return ""\n ind = bisect.bisect_right(self.data[key], timestamp, key=lambda i: i.time) - 1\n if self.data[key][ind].time > timestamp:\n return ""\n return self.data[key][ind].val\n``` | 6 | 0 | ['Binary Search', 'Java', 'Python3'] | 0 |
time-based-key-value-store | Concise HashMap with TreeMap solution in Java | concise-hashmap-with-treemap-solution-in-8ndu | \nclass TimeMap {\n HashMap<String, TreeMap<Integer, String>> timeMap;\n\n public TimeMap() {\n timeMap = new HashMap<String, TreeMap<Integer, Stri | hkolli123 | NORMAL | 2020-02-26T19:37:57.198687+00:00 | 2020-02-26T19:37:57.198741+00:00 | 594 | false | ```\nclass TimeMap {\n HashMap<String, TreeMap<Integer, String>> timeMap;\n\n public TimeMap() {\n timeMap = new HashMap<String, TreeMap<Integer, String>>();\n }\n \n public void set(String key, String value, int timestamp) {\n timeMap.putIfAbsent(key, new TreeMap<Integer, String>());\n timeMap.get(key).put(timestamp, value);\n }\n \n public String get(String key, int timestamp) {\n if(timeMap.get(key) == null) return "";\n\n Map.Entry<Integer, String> res = timeMap.get(key).floorEntry(timestamp);\n return res == null ? "" : res.getValue();\n }\n}\n\n/**\n * Your TimeMap object will be instantiated and called as such:\n * TimeMap obj = new TimeMap();\n * obj.set(key,value,timestamp);\n * String param_2 = obj.get(key,timestamp);\n */\n``` | 6 | 0 | ['Tree', 'Java'] | 0 |
time-based-key-value-store | 💡JavasScrip Simple Solution w/ Explanation | javasscrip-simple-solution-w-explanation-ffcm | The idea\nfor every key, its value is a series timestamp and a value corresponds to that timestamp, we can store these two information into a array where the ar | aminick | NORMAL | 2019-10-21T23:15:28.471769+00:00 | 2019-10-21T23:15:28.471824+00:00 | 768 | false | #### The idea\nfor every key, its value is a series timestamp and a value corresponds to that timestamp, we can store these two information into a array where the array index is the timestamp. I know this is a bad idea but for this question it is accepected.\n\n``` javascript\nvar TimeMap = function() {\n this.map = new Map();\n};\n\n/** \n * @param {string} key \n * @param {string} value \n * @param {number} timestamp\n * @return {void}\n */\nTimeMap.prototype.set = function(key, value, timestamp) {\n if (!this.map.has(key)) this.map.set(key, []);\n let item = this.map.get(key);\n item[timestamp] = value;\n};\n\n/** \n * @param {string} key \n * @param {number} timestamp\n * @return {string}\n */\nTimeMap.prototype.get = function(key, timestamp) {\n if (!this.map.has(key)) return "";\n let item = this.map.get(key);\n for (let i = timestamp;i>=0;i--) {\n if(item[i] != null) {\n return item[i];\n }\n }\n return "";\n};\n``` | 6 | 1 | ['JavaScript'] | 1 |
time-based-key-value-store | Rust - BTreeMap + HashMap | rust-btreemap-hashmap-by-dcc-9x3n | It turned out to be slightly faster (~170ms vs ~250ms) to use HashMap<String, BTreeMap<i32, String>> over a BTreeMap<i32, HashMap<String, String>>.\n\nuse std:: | dcc | NORMAL | 2019-01-29T01:10:30.524321+00:00 | 2019-01-29T01:10:30.524389+00:00 | 744 | false | It turned out to be slightly faster (~170ms vs ~250ms) to use ```HashMap<String, BTreeMap<i32, String>>``` over a ```BTreeMap<i32, HashMap<String, String>>```.\n```\nuse std::collections::{BTreeMap, HashMap};\n\nstruct TimeMap {\n tm : HashMap<String, BTreeMap<i32, String>>,\n}\n\nimpl TimeMap {\n fn new() -> Self {\n TimeMap {\n tm : HashMap::new(),\n }\n }\n \n fn set(&mut self, key: String, value: String, timestamp: i32) {\n self.tm.entry(key).or_insert(BTreeMap::new()).insert(timestamp, value);\n }\n \n fn get(&self, key: String, timestamp: i32) -> String {\n if let Some((_,v)) = self.tm[&key].range(0..=timestamp).rev().next() {\n return v.clone();\n }\n String::new()\n }\n}\n``` | 6 | 1 | [] | 3 |
time-based-key-value-store | 4 Line solution with Hashmaps And Lowerbound O(logN) in c++ | 4-line-solution-with-hashmaps-and-lowerb-u2e7 | 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 | vik_97 | NORMAL | 2024-03-06T20:27:30.130468+00:00 | 2024-03-06T20:27:30.130501+00:00 | 617 | 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```\nclass TimeMap {\npublic:\n map<string,map<int,string,greater<int>>> mp;\n TimeMap() {\n \n }\n \n void set(string key, string val, int timestamp) {\n mp[key][timestamp] = val;\n }\n \n string get(string key, int timestamp) {\n if(mp.count(key) ==0) return "";\n\n auto itr =mp[key]. lower_bound(timestamp);\n\n if(itr == mp[key].end()) return "";\n\n return itr->second;\n }\n};\n\n/**\n * Your TimeMap object will be instantiated and called as such:\n * TimeMap* obj = new TimeMap();\n * obj->set(key,value,timestamp);\n * string param_2 = obj->get(key,timestamp);\n */\n``` | 5 | 0 | ['Hash Table', 'String', 'Binary Search', 'C++'] | 1 |
time-based-key-value-store | [Python] ✅ || Easy Explanation - Mind Map Diagram || Walkthrough from LS - O(n) to BS - O(logn) | python-easy-explanation-mind-map-diagram-aape | Intuition\nWhen first approaching this problem, the key realization is that it closely resembles the task of finding the floor of a target value in a sorted lis | chitralpatil | NORMAL | 2024-01-16T23:29:39.669880+00:00 | 2024-01-16T23:29:39.669899+00:00 | 772 | false | # Intuition\nWhen first approaching this problem, the key realization is that it closely resembles the task of **finding the floor of a target value** in a sorted list, a classic binary search problem. If you\'re familiar with the concept of finding the floor in a binary search, or have solved similar problems, then you\'ll recognize that this challenge is essentially an application of that same principle. It\'s crucial to start with a basic understanding of how to handle the `get` operation. Initially, one might consider a brute force approach, which linearly searches for the correct timestamp. However, recognizing the limitations of this method is part of the learning curve, leading to a more efficient binary search solution. The problem also opens up discussions about the trade-offs involved in managing the keys of a dictionary. Specifically, whether it\'s beneficial to delete keys with no associated values, considering the possibility of adding those keys back in the future. This decision heavily depends on the nature of the inputs we are dealing with.\n\n\n\n\n# Approach\nThe approach involves two primary operations: `set` and `get`. The `set` operation is straightforward, where we store values in a dictionary with timestamps. The complexity arises in the `get` operation. Here, I start with the brute force method, iterating over each timestamp linearly to find the closest timestamp that is not greater than the given one. Soon, the realization dawns that this process can be optimized using binary search, thanks to the non-decreasing nature of the timestamps. This insight allows for a more efficient retrieval of data. It\'s a classic example of optimizing a naive solution to a more sophisticated one by identifying the underlying pattern and applying a well-known algorithm.\n\n# Complexity\n- Time complexity:\n - The time complexity for the `set` operation is $$O(1)$$, as it involves appending to a list in a dictionary.\n - For the `get` operation, the time complexity is $$O(\\log n)$$ due to the binary search in a sorted list, where \\(n\\) is the number of timestamps for a key.\n\n- Space complexity:\n - The space complexity is $$O(n)$$, where \\(n\\) is the total number of `set` operations performed, as each operation stores a key-value pair in the dictionary.\n\n# Code\nThe `set` method simply appends the value and timestamp to the list associated with the key. The `get` method utilizes binary search to efficiently find the closest timestamp. This method checks if the key exists in the dictionary, and then performs a binary search to locate the timestamp that is closest to and not greater than the given timestamp. If such a timestamp is found, the corresponding value is returned; otherwise, an empty string is returned.\n\nThis approach, starting from a brute force solution and moving towards binary search, demonstrates a typical problem-solving pathway in algorithm design. It\'s important to build a strong foundation with simpler methods and then optimize as you understand the problem\'s intricacies. This progression not only enhances problem-solving skills but also deepens the understanding of why certain algorithms are more efficient in specific scenarios.\n\nThe decision to use binary search was further reinforced by the hint that timestamps are always increasing. This detail is crucial as it guarantees the list of timestamps for each key is sorted, making binary search applicable. The challenge also lies in the decision-making process regarding the management of dictionary keys, especially when considering the deletion of keys with no values. Such decisions require a careful assessment of the potential future use of these keys and the nature of the input data. \n\nIn conclusion, this problem is a great example of how starting with a basic approach and gradually moving to a more sophisticated method can lead to efficient problem-solving. It underscores the importance of understanding fundamental algorithms and recognizing opportunities to apply them in various contexts. This journey from a linear to a binary search approach in handling the `get` operation, and the considerations in managing the dictionary keys, encapsulate the essence of practical and efficient algorithm design.\n\n```\nfrom collections import defaultdict \nclass TimeMap:\n\n def __init__(self):\n self.hasho = defaultdict(list)\n \n\n def set(self, key: str, value: str, timestamp: int) -> None:\n self.hasho[key].append((value, timestamp))\n \n\n def get(self, key: str, timestamp: int) -> str:\n if key in self.hasho:\n l, r = 0, len(self.hasho[key])-1\n\n while l <= r:\n m = (l+r) // 2\n\n if self.hasho[key][m][1] == timestamp:\n return self.hasho[key][m][0]\n elif self.hasho[key][m][1] > timestamp:\n r = m - 1\n else:\n l = m + 1\n \n if r >= 0: return self.hasho[key][r][0]\n \n return ""\n\n\n# Your TimeMap object will be instantiated and called as such:\n# obj = TimeMap()\n# obj.set(key,value,timestamp)\n# param_2 = obj.get(key,timestamp)\n``` | 5 | 0 | ['Hash Table', 'String', 'Binary Search', 'Design', 'Python3'] | 0 |
time-based-key-value-store | C++ vector pair solution Solution 389 ms | c-vector-pair-solution-solution-389-ms-b-pi7w | class TimeMap {\npublic:\n vector<pair< string, pair>> v;\n \n TimeMap() \n {\n \n }\n \n void set(string key, string value, int time | Paresh15 | NORMAL | 2022-10-06T17:20:04.848972+00:00 | 2022-10-06T17:20:04.849015+00:00 | 899 | false | class TimeMap {\npublic:\n vector<pair< string, pair<string, int>>> v;\n \n TimeMap() \n {\n \n }\n \n void set(string key, string value, int timestamp) \n {\n pair<string, int> p = {value, timestamp};\n pair<string, pair<string, int> > p1 = {key, p};\n v.push_back(p1);\n \n \n }\n \n string get(string key, int timestamp) \n {\n string ans="";\n for(int i=v.size()-1; i>=0; i--)\n {\n if(v[i].first==key)\n {\n \n if(v[i].second.second==timestamp)\n {\n return v[i].second.first;\n }\n else if(v[i].second.second<timestamp)\n {\n return v[i].second.first;\n // ans = v[i].second.first;\n \n }\n }\n }\n return ans;\n }\n};\n\n/**\n * Your TimeMap object will be instantiated and called as such:\n * TimeMap* obj = new TimeMap();\n * obj->set(key,value,timestamp);\n * string param_2 = obj->get(key,timestamp);\n */ | 5 | 0 | [] | 2 |
time-based-key-value-store | ✅✅ Using Binary Search || Map of Vector of Pair | using-binary-search-map-of-vector-of-pai-l6mr | \nclass TimeMap {\npublic:\n // Unordered Map of string, vector of pairs\n unordered_map<string,vector<pair<int,string>>> mp;\n TimeMap() {\n \n | Arpit507 | NORMAL | 2022-10-06T14:12:33.167188+00:00 | 2022-10-22T06:28:35.101376+00:00 | 788 | false | ```\nclass TimeMap {\npublic:\n // Unordered Map of string, vector of pairs\n unordered_map<string,vector<pair<int,string>>> mp;\n TimeMap() {\n \n }\n \n void set(string key, string value, int timestamp) {\n mp[key].push_back({timestamp,value});\n }\n \n string get(string key, int timestamp) {\n if(mp.find(key) == mp.end()) return "";\n int low = 0, high = mp[key].size()-1;\n if(mp[key][0].first > timestamp) return "";\n string ans = "";\n while(low <= high){\n int mid = low + (high-low)/2;\n if(mp[key][mid].first == timestamp) return mp[key][mid].second;\n if(mp[key][mid].first > timestamp){\n high = mid-1;\n }\n else{\n ans = mp[key][mid].second;\n low = mid+1;\n }\n }\n return ans;\n }\n};\n``` | 5 | 0 | ['C', 'Binary Tree'] | 0 |
time-based-key-value-store | Java || Using HashMap, TreeMap || Easy Solution | java-using-hashmap-treemap-easy-solution-buun | IF YOU LIKE THE SOLUTION\nPLEASE MAKE SURE TO UPVOTE IT !\n\n\nclass TimeMap {\n \n // HashMap of key(String) corresponding of TreeMap<TimeStamp,Value>>\n | ashutosh_pandey | NORMAL | 2022-10-06T08:48:28.655415+00:00 | 2022-10-06T08:48:28.655448+00:00 | 498 | false | IF YOU LIKE THE SOLUTION\nPLEASE MAKE SURE TO UPVOTE IT !\n\n```\nclass TimeMap {\n \n // HashMap of key(String) corresponding of TreeMap<TimeStamp,Value>>\n HashMap<String,TreeMap<Integer,String>> map;\n \n public TimeMap() {\n map = new HashMap<String,TreeMap<Integer,String>>();\n }\n \n public void set(String key, String value, int timestamp) {\n\n TreeMap<Integer,String> tmap;\n // if key is not present create a new instance otherwise get that treemap which is already there in hashmap corresponding to key.\n if(map.get(key) != null)\n tmap = map.get(key); \n else\n tmap = new TreeMap<>(Collections.reverseOrder()); \n // finally put key value in treemap and then in hashmap.\n tmap.put(timestamp,value);\n map.put(key,tmap);\n \n }\n \n public String get(String key, int timestamp) {\n // Iterate in hashmap first.\n for(Map.Entry m : map.entrySet()){\n // if key is equal to our hashmap key \n if(m.getKey().equals(key)){\n // get the value which is treemap correspond to given key.\n TreeMap<Integer,String> tmap = (TreeMap<Integer,String>)m.getValue();\n // Iterate in treemap\n for(Map.Entry tm : tmap.entrySet()){\n if((int)tm.getKey() <= timestamp) return String.valueOf(tm.getValue());\n }\n }\n }\n return "";\n \n }\n}\n\n/**\n * Your TimeMap object will be instantiated and called as such:\n * TimeMap obj = new TimeMap();\n * obj.set(key,value,timestamp);\n * String param_2 = obj.get(key,timestamp);\n */\n``` | 5 | 0 | ['Tree', 'Java'] | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.