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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
valid-permutations-for-di-sequence | Java- Bottom Up solution- DP | java-bottom-up-solution-dp-by-mvahidaliz-ux37 | Let\'s define our dp first:\ndp[i][j]=permutations with lenght i with last digit j. The trick is that when you are iterating from i=1 to i=n, you select differe | mvahidalizadeh | NORMAL | 2021-04-28T19:32:23.965399+00:00 | 2021-04-28T19:32:23.965437+00:00 | 228 | false | Let\'s define our dp first:\ndp[i][j]=permutations with lenght i with last digit j. The trick is that when you are iterating from i=1 to i=n, you select different j from 0 to i. Then, for each one of those j, you need to sum the relevant DPs. If S.charAt(i-1)=\'I\', then the prev digit should have been less than the current. So, we use the left half (0,j-1). If it is \'D\', then the prev digit should have been greater than the current one. So, we use (j,i-1). At the end, we sum up the last row dp[n][...] which means all the permuations with length n ending in different digits. Since the result might be big, be careful of the required mods.\n```\n public int numPermsDISequence(String S) {\n int mod = 1_000_000_007;\n int n = S.length();\n long[][] dp = new long[n + 1][n + 1];\n dp[0][0] = 1;\n for (int i = 1; i <= n; i++) { // We start from 1 to\n char c = S.charAt(i - 1);\n for (int j = 0; j <= i; j++) { // curr: dp[i][...] prev dp[i-1][...]\n long sum = 0;\n if (c == \'I\') { // Increasing- the prev digit was less than the current->use prev(0,j-1)\n for (int k = 0; k <= j - 1; k++) sum = (sum + dp[i - 1][k]) % mod;\n } else { // c==\'D\'- Decreasing- the prev digit was greater than the current->use prev(j,i-1)\n for (int k = j; k <= i - 1; k++) sum = (sum + dp[i - 1][k]) % mod;\n }\n dp[i][j] = sum;\n }\n }\n Long res = 0L; // Sum the last row- dp[n][...]\n for (int i = 0; i <= n; i++) res = (res + dp[n][i]) % mod;\n res = res % mod;\n return res.intValue();\n }\n``` | 0 | 0 | [] | 0 |
valid-permutations-for-di-sequence | Python3 Top Down DP | python3-top-down-dp-by-chang_liu-hcea | \nfrom functools import lru_cache\nclass Solution:\n def numPermsDISequence(self, S: str) -> int:\n n = len(S) + 1\n @lru_cache(maxsize = 40000 | chang_liu | NORMAL | 2021-03-20T23:39:48.576485+00:00 | 2021-03-20T23:39:48.576514+00:00 | 233 | false | ```\nfrom functools import lru_cache\nclass Solution:\n def numPermsDISequence(self, S: str) -> int:\n n = len(S) + 1\n @lru_cache(maxsize = 40000)\n def dfs(lastPos, pos):\n total = 0\n if pos == 0:\n for i in range(n):\n total += dfs(i, pos + 1)\n return total%1000000007\n letter = S[pos - 1]\n if pos == len(S):\n if letter == \'I\':\n return 1 - lastPos\n else:\n return lastPos\n else:\n if letter == \'I\':\n for i in range(lastPos, n-pos):\n total += dfs(i, pos + 1)\n else:\n for i in range(lastPos):\n total += dfs(i, pos + 1)\n \n return total%1000000007\n \n return dfs(0,0)%1000000007\n``` | 0 | 0 | [] | 0 |
valid-permutations-for-di-sequence | Java | java-by-aravind2679-4i1b | \npublic int numPermsDISequence(String S) {\n int n = S.length(), mod = (int)1e9 + 7;\n int[][] dp = new int[n + 1][n + 1];\n for (int j = | aravind2679 | NORMAL | 2021-03-18T07:33:28.198773+00:00 | 2021-03-18T07:33:55.889725+00:00 | 162 | false | ```\npublic int numPermsDISequence(String S) {\n int n = S.length(), mod = (int)1e9 + 7;\n int[][] dp = new int[n + 1][n + 1];\n for (int j = 0; j <= n; j++) dp[0][j] = 1;\n for (int i = 0; i < n; i++)\n if (S.charAt(i) == \'I\')\n for (int j = 0, cur = 0; j < n - i; j++)\n dp[i + 1][j] = cur = (cur + dp[i][j]) % mod;\n else\n for (int j = n - i - 1, cur = 0; j >= 0; j--)\n dp[i + 1][j] = cur = (cur + dp[i][j + 1]) % mod;\n return dp[n][0];\n }\n``` | 0 | 0 | [] | 0 |
valid-permutations-for-di-sequence | p23_5 | p23_5-by-p23_5-dtom | Puting n-1 and then putting nth\nLet\'s change the definition of dp matrix to make the calculation simple: let\'s say dp[i][j] represents the number of permutat | p23_5 | NORMAL | 2021-01-25T22:43:39.886343+00:00 | 2021-01-26T12:37:38.694763+00:00 | 63 | false | Puting n-1 and then putting nth\nLet\'s change the definition of dp matrix to make the calculation simple: let\'s say dp[i][j] represents the number of permutation of number 0, 1, ... , i which ends with j. Also, it represents the answer of s.substring(0, i) which ends with j.\nWe will have two conditions:\n\ns.charAt(i - 1) == \'I\': In this case, dp[i][j] = sum(dp[i - 1][0], dp[i - 1][1], ... , dp[i - 1][j - 1]).\ns.charAt(i - 1) == \'D\': In this case, dp[i][j] = sum(dp[i - 1][j], dp[i - 1][j + 1], ... , dp[i - 1][i - 1]).\nImagine each time when appending the j to the previous permutations, you have to add 1 to each number in the previous permutation which is greater than or equals to j. In this way, we keep the orders and counts of previous permutations and cumulate.\n\neg. We already have permutation (1, 0, 3, 2). We are trying to append 2. Now the (1, 0, 3, 2) changes to (1, 0, 4, 3) then appended with a 2. We have (1, 0, 4, 3, 2). Although the values change but the order and count don\'t change.\nWhy in case of D, <=l is used explanation\nMethod:\nstep 1.\nfor the original permutation 1032, we add 1 to the digits that are larger than or equal to 2.\n\n1032->1043\n ^^\nstep 2.\nthen directly append 2 to 1043, i.e., 1043 -> 10432\n\nRemark on step 1:\n(1) By performing add operation, 2 in the original permutation now becomes 3, and thus there is no duplicate element for the new arrival 2.\n(2) More importantly, such operation on the digits will not break the original DI-rule. e.g., 1043 still keeps its old DI-rule, i.e., "DID". The proof is straight-forward, you can validate yourself. | 0 | 1 | [] | 0 |
time-needed-to-buy-tickets | ✅97.44%🔥Easy Solution🔥With explanation🔥 | 9744easy-solutionwith-explanation-by-mra-ofg7 | Approach\n#### 1. Initialize a variable time to keep track of the total time taken.\n#### 2. While the person at position k hasn\'t bought all their tickets:\n- | MrAke | NORMAL | 2024-04-09T00:04:52.295762+00:00 | 2024-04-09T00:20:44.276690+00:00 | 35,950 | false | # Approach\n#### 1. Initialize a variable `time` to keep track of the total time taken.\n#### 2. While the person at position k hasn\'t bought all their tickets:\n- Iterate through the queue and let each person buy a ticket.\n- Update the queue by decrementing the number of tickets for the person who bought a ticket.\n- Increment the time by 1 second for each pass.\n#### 3. Return the total time taken.\n\n\n# Complexity\n- ## Time complexity:\n#### The algorithm iterates through each person in the queue once, so the time complexity of the loop is $$O(n)$$, where n is the number of people in the queue.\n\n- ## Space complexity:\n#### The algorithm uses only a constant amount of extra space for variables such as `total`, `i`, and `x`.\n#### Therefore, the space complexity is $$O(1)$$.\n----\n# Code\n\n\n```python []\nclass Solution:\n def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:\n total = 0\n\n for i, x in enumerate(tickets):\n if i <= k:\n total += min(tickets[i], tickets[k])\n else:\n total += min(tickets[i], tickets[k] - 1)\n\n return total\n```\n```C++ []\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& tickets, int k) {\n int total = 0;\n\n for (int i = 0; i < tickets.size(); ++i) {\n if (i <= k) {\n total += min(tickets[i], tickets[k]);\n } else {\n total += min(tickets[i], tickets[k] - 1);\n }\n }\n\n return total;\n }\n};\n```\n```java []\nclass Solution {\n public int timeRequiredToBuy(int[] tickets, int k) {\n int total = 0;\n\n for (int i = 0; i < tickets.length; i++) {\n if (i <= k) {\n total += Math.min(tickets[i], tickets[k]);\n } else {\n total += Math.min(tickets[i], tickets[k] - 1);\n }\n }\n\n return total;\n }\n}\n\n```\n```javascript []\nvar timeRequiredToBuy = function(tickets, k) {\n let total = 0;\n\n for (let i = 0; i < tickets.length; i++) {\n if (i <= k) {\n total += Math.min(tickets[i], tickets[k]);\n } else {\n total += Math.min(tickets[i], tickets[k] - 1);\n }\n }\n\n return total;\n};\n\n```\n```C# []\npublic class Solution {\n public int TimeRequiredToBuy(int[] tickets, int k) {\n int total = 0;\n\n for (int i = 0; i < tickets.Length; i++) {\n if (i <= k) {\n total += Math.Min(tickets[i], tickets[k]);\n } else {\n total += Math.Min(tickets[i], tickets[k] - 1);\n }\n }\n\n return total;\n }\n}\n\n```\n---\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n | 152 | 10 | ['Array', 'Python', 'C++', 'Java', 'Python3', 'JavaScript', 'C#'] | 32 |
time-needed-to-buy-tickets | C++ One Pass | c-one-pass-by-lzl124631x-j5w2 | See my latest update in repo LeetCode\n## Solution 1. Brute Force Simulation\n\ncpp\n// OJ: https://leetcode.com/problems/time-needed-to-buy-tickets/\n// Author | lzl124631x | NORMAL | 2021-11-14T04:01:31.954917+00:00 | 2021-11-14T23:36:29.789073+00:00 | 12,435 | false | See my latest update in repo [LeetCode](https://github.com/lzl124631x/LeetCode)\n## Solution 1. Brute Force Simulation\n\n```cpp\n// OJ: https://leetcode.com/problems/time-needed-to-buy-tickets/\n// Author: github.com/lzl124631x\n// Time: O(SUM(A))\n// Space: O(1)\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& A, int k) {\n int step = 0;\n while (true) {\n for (int i = 0; i < A.size(); ++i) {\n if (A[i] == 0) continue;\n A[i]--;\n ++step;\n if (A[k] == 0) return step;\n }\n }\n }\n};\n```\n\n## Solution 2. One Pass\n\nFor `i <= k`, `A[i]` contributes `min(A[k], A[i])` steps.\n\nFor `i > k`, `A[i]` contributes `min(A[k] - 1, A[i])` steps.\n\n```cpp\n// OJ: https://leetcode.com/problems/time-needed-to-buy-tickets/\n// Author: github.com/lzl124631x\n// Time: O(N)\n// Space: O(1)\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& A, int k) {\n int ans = 0;\n for (int i = 0; i < A.size(); ++i) {\n ans += min(A[k] - (i > k), A[i]);\n }\n return ans;\n }\n};\n``` | 117 | 2 | [] | 13 |
time-needed-to-buy-tickets | O(n) | on-by-votrubac-1vmp | We know the value of k-th element. Elements before k (and the element itself) will appear in the line min(t[k], t[i]) times.\n\nAll elements after k will appear | votrubac | NORMAL | 2021-11-14T04:44:19.934704+00:00 | 2024-04-09T18:48:43.517404+00:00 | 9,494 | false | We know the value of `k`-th element. Elements before `k` (and the element itself) will appear in the line `min(t[k], t[i])` times.\n\nAll elements after `k` will appear in the line `min(t[k] - 1, t[i])` times.\n\n**Python 3**\n```python\nclass Solution:\n def timeRequiredToBuy(self, t: List[int], k: int) -> int:\n return sum(min(v, t[k] - (i > k)) for i, v in enumerate(t))\n```\n\nAlternative solution, matching the explanation above.\n```python\nclass Solution:\n def timeRequiredToBuy(self, t: List[int], k: int) -> int:\n return sum([min(t[i], t[k]) for i in range(k + 1)] + [min(t[i], t[k] - 1) for i in range(k + 1, len(t))])\n```\n**Java**\n```java\npublic int timeRequiredToBuy(int[] t, int k) {\n return IntStream.range(0, t.length).map(i -> Math.min(t[i], t[k] - (i > k ? 1 : 0))).sum();\n}\n```\n**C++**\n```cpp\nint timeRequiredToBuy(vector<int>& t, int k) {\n int res = 0;\n for (int i = 0; i < t.size(); ++i)\n res += min(t[k] - (i > k), t[i]);\n return res;\n}\n```\nAlso a (slightly mouthful) functional version.\n```cpp\nint timeRequiredToBuy(vector<int>& t, int k) {\n return accumulate(begin(t), begin(t) + k + 1, 0, [&](int s, int v){ return s + min(v, t[k]); })\n + accumulate(begin(t) + k + 1, end(t), 0, [&](int s, int v){ return s + min(v, t[k] - 1); });\n}\n``` | 68 | 4 | ['C', 'Python', 'Java'] | 17 |
time-needed-to-buy-tickets | 2 interview Approaches with Video Solution ✅ || Brute Force -> Optimal (1 Pass) 🔥 | 2-interview-approaches-with-video-soluti-6wx0 | Happy Ugadi, I wish you have wonderful year ahead \uD83D\uDE00\n\n# Intuition\n Describe your first thoughts on how to solve this problem. \nUnderstand the ques | ayushnemmaniwar12 | NORMAL | 2024-04-09T02:51:58.629780+00:00 | 2024-04-09T04:03:38.848615+00:00 | 10,673 | false | *Happy Ugadi, I wish you have wonderful year ahead* \uD83D\uDE00\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUnderstand the question clearly and dry-run few examples then you can implement the solution\n\n***If you learned something from the solution. Please Upvote and subscribe to my youtube channel***\n\n# ***Easy Video Explanation***\n\nhttps://youtu.be/1Ri51bORarI\n \n\n# Brute Force\n\n\n```C++ []\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& v, int k) {\n int n=v.size();\n int t=0;\n while(true) {\n for(int i=0;i<n;i++) {\n if(v[i]>0) {\n v[i]=v[i]-1;\n t++;\n }\n if(i==k && v[i]==0)\n return t;\n }\n }\n return 0;\n }\n};\n```\n```python []\nclass Solution:\n def timeRequiredToBuy(self, v: List[int], k: int) -> int:\n n = len(v)\n t = 0\n while True:\n for i in range(n):\n if v[i] > 0:\n v[i] -= 1\n t += 1\n if i == k and v[i] == 0:\n return t\n\n```\n```Java []\npublic class Solution {\n public int timeRequiredToBuy(int[] v, int k) {\n int n = v.length;\n int t = 0;\n while (true) {\n for (int i = 0; i < n; i++) {\n if (v[i] > 0) {\n v[i] = v[i] - 1;\n t++;\n }\n if (i == k && v[i] == 0)\n return t;\n }\n }\n }\n}\n\n```\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(n * m)\n n: size of array\n m : max number within the array\n \n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(1)\n\n# Optimal Solution (1 pass)\n\n\n```C++ []\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& v, int k) {\n int n=v.size();\n int value=v[k];\n int t=0;\n for(int i=0;i<n;i++) {\n if(i<k) {\n t=t+min(v[i],value);\n } else if(i==k) {\n t=t+value;\n } else {\n if(v[i]<value)\n t=t+v[i];\n else\n t=t+value-1;\n }\n }\n return t;\n }\n};\n```\n```python []\nfrom typing import List\n\nclass Solution:\n def timeRequiredToBuy(self, v: List[int], k: int) -> int:\n n = len(v)\n value = v[k]\n t = 0\n for i in range(n):\n if i < k:\n t += min(v[i], value)\n elif i == k:\n t += value\n else:\n if v[i] < value:\n t += v[i]\n else:\n t += value - 1\n return t\n\n```\n```Java []\nimport java.util.List;\n\npublic class Solution {\n public int timeRequiredToBuy(List<Integer> v, int k) {\n int n = v.size();\n int value = v.get(k);\n int t = 0;\n for (int i = 0; i < n; i++) {\n if (i < k) {\n t += Math.min(v.get(i), value);\n } else if (i == k) {\n t += value;\n } else {\n if (v.get(i) < value)\n t += v.get(i);\n else\n t += value - 1;\n }\n }\n return t;\n }\n}\n\n\n```\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(N)\n \n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(1)\n\n# ***If you like the solution Please Upvote and subscribe to my youtube channel***\n\n*Thank you* \uD83D\uDE00 | 47 | 2 | ['Math', 'Queue', 'Python', 'C++', 'Java'] | 11 |
time-needed-to-buy-tickets | [Python] | BruteForce and O(N) | python-bruteforce-and-on-by-mokshitsuran-1du4 | Please upvote if you find it helpful\n\nBruteForce:\n\nclass Solution:\n def timeRequiredToBuy(self, tickets: list[int], k: int) -> int:\n secs = 0 \n | MokshitSurana | NORMAL | 2021-11-14T04:11:30.806630+00:00 | 2021-11-14T05:41:15.737981+00:00 | 5,541 | false | Please upvote if you find it helpful\n\nBruteForce:\n```\nclass Solution:\n def timeRequiredToBuy(self, tickets: list[int], k: int) -> int:\n secs = 0 \n i = 0\n while tickets[k] != 0:\n if tickets[i] != 0: # if it is zero that means we dont have to count it anymore\n tickets[i] -= 1 # decrease the value by 1 everytime\n secs += 1 # increase secs by 1\n\n i = (i + 1) % len(tickets) # since after getting to the end of the array we have to return to the first value so we use the mod operator\n \n return secs\n```\n\nO(N):\n```\nclass Solution:\n def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:\n return sum(min(x, tickets[k] if i <= k else tickets[k] - 1) for i, x in enumerate(tickets))\n```\nThe values before tickets[k] will appear min(x, t[x]) times and values after tickets[k] will appear min(x, t[x] -1) times\nLet\'s take an example:\n`tickets = [5, 2, 3, 4]` and `k = 2`\n```1st iteration: [4, 1, 2, 3]```\n```2nd iteration: [3, 0, 1, 2]```\n```3rd iteration: [2, 0, 0, 1]```\nYou see `tickets[0]` appeared 3 times which is min(5, 3) and that is 3, \n `tickets[1]` appeared 2 times which is min(2, 3) that is 2, \n\t\t\t `tickets[2]` appeared 3 times which is min(3, 3) that is 3 and \n\t\t\t `tickets[3]` appeared 2 times which is min(4, 2) that is 2.\n | 47 | 1 | ['Python', 'Python3'] | 10 |
time-needed-to-buy-tickets | [Java] O(n) || One Pass || Explained | java-on-one-pass-explained-by-abhijeetma-uzp4 | Explanation / Approach:\nBrute force is somewhat easy to come up with. You just need to iterate as long as tickets[k] != 0.\n\nFor an optimized approach :\n1. A | abhijeetmallick29 | NORMAL | 2021-11-14T04:01:12.875196+00:00 | 2022-03-30T05:59:15.656402+00:00 | 5,594 | false | **Explanation / Approach:**\nBrute force is somewhat easy to come up with. You just need to iterate as long as tickets[k] != 0.\n\n**For an optimized approach :**\n1. Add min(tickets[i],tickets[k]) upto k (inclusive).\n2. Add min(tickets[i],tickets[k] - 1) after k.\n3. Return the count.\n\nTime : O(n) , Space : O(1)\n```\nclass Solution {\n public int timeRequiredToBuy(int[] tickets, int k) {\n int res = 0;\n for(int i = 0;i<tickets.length;i++){\n if(i <= k){\n res += Math.min(tickets[k],tickets[i]);\n }else{\n res += Math.min(tickets[k] - 1,tickets[i]);\n }\n }\n return res;\n }\n}\n``` | 46 | 5 | ['Java'] | 11 |
time-needed-to-buy-tickets | [C++] Brute Force vs. Single Pass Solution Compared and Explained, 100% Time, ~80% Space | c-brute-force-vs-single-pass-solution-co-298u | Given the constraints, we can easily afford to go for a brute force-ish solution first (a fully legitimate approach during any interview, as long as you keep th | Ajna2 | NORMAL | 2021-11-21T11:29:58.818318+00:00 | 2021-11-21T13:09:42.863765+00:00 | 3,601 | false | Given the constraints, we can easily afford to go for a brute force-ish solution first (a fully legitimate approach during any interview, as long as you keep the computationt time reasonable - I wouldn\'t do this if either the queue length or the amount of tickets each queuer might buy were in the order of billions!), so we will go for it first.\n\nIn order to solve our problem we will first of all declare an accumulator variable `res`, initially set to `0` and that will store how many turns we have to wait until the `k`th slot has bought all his tickets.\n\nWe will then have an outer loop just to check that - `ts[k]` still having pending tickets to buy and inside it we will run another one, using the pointer `i` to parse `ts` until `ts[k]` is not `0` and in which we will:\n* check if the currently pointed element `ts[i]` still has elements to remove and, in case:\n\t* decrease `ts[i]` by `1`;\n\t* increase `res` by `1`.\n\nOnce done, we can just `return` `res` :)\n\nThe code:\n\n```cpp\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& ts, int k) {\n // support variables\n int res = 0;\n // running loops until we get all our tickets\n while (ts[k]) {\n // running one loop\n for (int i = 0, lmt = ts.size(); i < lmt && ts[k]; i++) {\n // decreasing one slot and increasing res, if the slot still queues\n if (ts[i]) {\n ts[i]--;\n res++;\n }\n } \n }\n return res;\n }\n};\n```\n\nBut, wait a minute \uD83E\uDD14 ...\n\nDo we really need to decrease all the cells one by one?\n\nWell, probably not, since we might quickly notice that the waiting time each slot to the left of `k` contributes is equal to the minimum between its current value and `ts[k]`, that we will call `target` for convenience; and it\'s almost the same for all the elements to the right of it, being the minimum between its current value and `target - 1` (since we will go and touch them always after having decreased `ts[k]`.\n\nSo, we can put this into code and get much better performance with this version:\n\n```cpp\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& ts, int k) {\n // support variables\n int res = 0, target = ts[k];\n // parsing the queue\n for (int i = 0, lmt = ts.size(); i < lmt; i++) {\n // getting the minimum between the current value and what we need to get\n res += min(ts[i], target - (i > k));\n }\n return res;\n }\n};\n```\n\nFinal micro-optimised version to avoid one conditional inside the loop (which probably would not even shine in terms of performance compared to allocating variables for a sole `for` loop unless we were to get really big ranges):\n\n```cpp\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& ts, int k) {\n // support variables\n int res = 0, target = ts[k];\n // parsing the queue up to k, included\n for (int i = 0; i <= k; i++) {\n // getting the minimum between the current value and target\n res += min(ts[i], target);\n }\n // parsing the queue up from k, excluded\n target--;\n for (int i = k + 1, lmt = ts.size(); i < lmt; i++) {\n // getting the minimum between the current value and target\n res += min(ts[i], target);\n }\n return res;\n }\n};\n``` | 28 | 0 | ['Queue', 'C', 'C++'] | 6 |
time-needed-to-buy-tickets | loop with sum min(buy, tickets[i])->1 liner||0ms Beats 100% | loop-with-sum-minbuy-ticketsi-1-liner0ms-tbmy | Intuition\n Describe your first thoughts on how to solve this problem. \nSuppose $x=tickets[k]$. When $i\leq k$ person i has to buy at most x tickets; when $i>k | anwendeng | NORMAL | 2024-04-09T00:12:46.688534+00:00 | 2024-04-09T14:37:51.589408+00:00 | 5,240 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSuppose $x=tickets[k]$. When $i\\leq k$ person i has to buy at most x tickets; when $i>k$ peson i has to buy at most x-1 tickets.\n- The simulation using queue will take O(nx) time.\n- All codes here provided are O(n)-time solutions with constant space.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n[Please turn on English subtitles if necessary]\n[https://youtu.be/ek9a0iZCsIg?si=TupccfCCHpIe8Z5K](https://youtu.be/ek9a0iZCsIg?si=TupccfCCHpIe8Z5K)\nThe answer is \n$time=\\sum_i \\min(buy, tikets[i])$ where `buy=(i>k)?x-1:x`\n2nd approach uses a sized-2 array to drop off the if-branch. 3x python codes, one of them is 1-liner.\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(1)$$\n# Code||C++ 0ms Beats 100%\n```\n#pragma GCC optimize("O3", "unroll-loops")\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& tickets, int k) {\n int n=tickets.size();\n int x=tickets[k];\n int time=0;\n for(int i=0; i<n; i++){\n int buy=(i>k)?x-1:x;\n time+=min(buy, tickets[i]);\n }\n return time; \n }\n};\n\n\nauto init = []() {\n ios::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n return \'c\';\n}();\n```\n# Python code in film\n```\nclass Solution:\n def timeRequiredToBuy(self, t: List[int], k: int) -> int:\n #loop with sum min(buy, tickets[i])\n n=len(t)\n x=t[k]\n time=0\n for i, y in enumerate(t):\n buy=x\n if i>k: buy=x-1\n time+=min(buy, y)\n return time\n \n```\nAfter solving this question obtained the following Badge!\n\n# C/C++ without if-branches||0ms beats 100%\n```C++ []\n#pragma GCC optimize("O3", "unroll-loops")\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& tickets, int k) {\n int n=tickets.size();\n int x=tickets[k];\n int time=0;\n int buy[2]={x, x-1};\n for(int i=0; i<n; i++){\n time+=min(buy[i>k], tickets[i]);\n }\n return time; \n }\n};\n\n```\n```C []\n#pragma GCC optimize("O3", "unroll-loops")\nint timeRequiredToBuy(int* tickets, int n, int k) {\n int x=tickets[k];\n int time=0;\n int buy[2]={x, x-1};\n for(register int i=0; i<n; i++){\n int b=buy[i>k], y=tickets[i];\n time+=(b<y)?b:y;\n }\n return time;\n}\n```\n\n# 2nd Python using sum function\n```\nclass Solution:\n def timeRequiredToBuy(self, t: List[int], k: int) -> int:\n n=len(t)\n x=t[k]\n time=sum(min(y,x) for y in t[:k+1])\n time+=sum(min(y, x-1) for y in t[k+1:])\n return time\n \n```\n# Python 1-liner\n```\nclass Solution:\n def timeRequiredToBuy(self, t: List[int], k: int) -> int:\n return sum(min(y,x:=t[k]) for y in t[:k+1])+sum(min(y, x-1) for y in t[k+1:])\n \n```\n | 21 | 3 | ['Array', 'C', 'C++', 'Python3'] | 15 |
time-needed-to-buy-tickets | easy to understand | easy-to-understand-by-deleted_user-qy3u | \nvar timeRequiredToBuy = function(tickets, k) {\n \n let countTime = 0;\n\n while(tickets[k] !== 0){\n\n for(let i = 0; i < tickets.length; i+ | deleted_user | NORMAL | 2021-11-14T04:42:49.189339+00:00 | 2021-11-14T04:42:49.189383+00:00 | 1,688 | false | ```\nvar timeRequiredToBuy = function(tickets, k) {\n \n let countTime = 0;\n\n while(tickets[k] !== 0){\n\n for(let i = 0; i < tickets.length; i++){\n \n if(tickets[k] == 0){\n return countTime;\n }\n if(tickets[i] !== 0){\n tickets[i] = tickets[i] - 1;\n countTime++;\n }\n }\n\n }\n\n return countTime;\n};\n``` | 20 | 2 | ['JavaScript'] | 6 |
time-needed-to-buy-tickets | 📌Brute Force⏩Optimized⏩Queue👉interviewer Mindset | brute-forceoptimizedqueueinterviewer-min-h1bj | Intuition\n1. Brute force using loop iteration\n2. optimised using one loop\n3. Queue solution for more in depth\n\n# Approach\nWe find out min of tickets[i] an | Heera-Jat | NORMAL | 2023-08-16T13:42:09.874839+00:00 | 2023-08-16T13:42:09.874857+00:00 | 1,334 | false | # Intuition\n1. Brute force using loop iteration\n2. optimised using one loop\n3. Queue solution for more in depth\n\n# Approach\nWe find out min of tickets[i] and tickets[k]\n\n\n\n## Brute force approach\n- Time complexity: O(N^2)\n```\nclass Solution {\n public int timeRequiredToBuy(int[] tickets, int k){\n int n= tickets.length;\n int time=0;\n \n if(tickets[k]==1) return k+1;\n while(tickets[k]>0){\n for(int i=0;i<n;i++){\n if(tickets[i]==0) continue;\n tickets[i]=tickets[i]-1;\n time++;\n if(tickets[k]==0) break;\n }\n }k--;\n return time;\n }\n}\n\n```\n## Optimized approach: without extra space\n\n- Time complexity: O(N)\n- - space complexity: O(1)\n```\nclass Solution {\n public int timeRequiredToBuy(int[] tickets, int k) {\n int time = 0;\n for(int i = 0;i<tickets.length;i++){\n if(i <= k){\n time += Math.min(tickets[k],tickets[i]);\n }else{\n time+= Math.min(tickets[k] - 1,tickets[i]);\n }\n }\n return time;\n }\n}\n\n```\n## Queue approach : taking extra space\n- Time complexity: O(N)\n- space complexity: O(N)\n```\nclass Solution {\n public int timeRequiredToBuy(int[] tickets, int k) {\n Queue<Integer> q = new LinkedList<>();\n\n for ( int i = 0; i < tickets.length; i++){\n q.add(i);\n }\n int count = 0;\n while(!q.isEmpty()){\n ++count;\n int front = q.poll();\n if(tickets[front] >= 1){\n tickets[front] -= 1;\n }\n if(k == front && tickets[front] == 0){\n break;\n }\n if(k != front && tickets[front] == 0){\n continue;\n }\n q.add(front);\n }\n return count;\n }\n}\n```\n\n | 18 | 0 | ['Array', 'Math', 'Queue', 'Java'] | 5 |
time-needed-to-buy-tickets | Python O(N) easy method | python-on-easy-method-by-smita2195-rwbj | ```\nclass Solution:\n def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:\n\t\t#Loop through all elements in list only once. \n\t\t\n nu | Smita2195 | NORMAL | 2022-02-17T18:00:44.289268+00:00 | 2022-11-17T01:08:13.477974+00:00 | 2,468 | false | ```\nclass Solution:\n def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:\n\t\t#Loop through all elements in list only once. \n\t\t\n nums = tickets \n time_sec = 0\n\t\t# save the number of tickets to be bought by person standing at k position\n least_tickets = nums[k] \n\t\t#(3) Any person nums[i] having tickets more than the k pos person, will buy tickets least_tickets times only.\n\t\t#(2) Person nums[i] having tickets less than kth person ( nums[i] < least_tickets ), and standing before him(i<k), will be able to buy nums[i] amount.\n\t\t#(1) Person nums[i] standing after kth person having more tickets than kth person, will be able to buy one less than the ticket kth person can buy(condition: least_tickets - 1).\n for i in range(len(nums)): \n if k < i and nums[i] >= least_tickets : #(1)\n time_sec += (least_tickets - 1)\n elif nums[i] < least_tickets : #(2)\n time_sec += nums[i]\n else: #(3)\n time_sec += least_tickets\n\t\t\t\t\n return time_sec\n \nPlease upvote if you find it useful and well-explained! | 15 | 1 | ['Queue', 'Python', 'Python3'] | 4 |
time-needed-to-buy-tickets | Java easy solution beats 100% | java-easy-solution-beats-100-by-mokhtar2-5lag | Approach\n Describe your approach to solving the problem. \nThe idea of this solution is to think about the problem differently. Let\'s reformulate it in anothe | Mokhtar2k24 | NORMAL | 2024-04-09T00:53:59.300808+00:00 | 2024-04-09T00:53:59.300827+00:00 | 2,267 | false | # Approach\n<!-- Describe your approach to solving the problem. -->\nThe idea of this solution is to think about the problem differently. Let\'s reformulate it in another way.\n- The persons who are queued in front of the selected person will at most buy the same ticket as the person in index `k`. If they should buy more tickets, person `k` will buy his tickets before that.\n- The persons behind person `k` will buy at most the `(number of tickets of person k) - 1`.\n- In our implementation we will implement it in a way that we pre-calculate how much tickets each person will buy without simulating the whole process.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ --> \nWe iterate through the tickets array only once: $$O(n)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n\n# Code\n```\nclass Solution {\n public int timeRequiredToBuy(int[] tickets, int k) {\n int value = tickets[k];\n int seconds = 0;\n for(int i = 0; i<tickets.length; i++) {\n int max = (i<=k)? value: value-1;\n seconds+= (tickets[i]>max)? max: tickets[i];\n }\n return seconds;\n }\n}\n``` | 13 | 0 | ['Java'] | 3 |
time-needed-to-buy-tickets | Python 1-liner | python-1-liner-by-faceplant-nlzu | python\nreturn sum(min(tickets[k] - (i > k), num) for i, num in enumerate(tickets))\n | FACEPLANT | NORMAL | 2021-11-14T04:06:49.550347+00:00 | 2021-11-14T04:07:40.669214+00:00 | 1,030 | false | ```python\nreturn sum(min(tickets[k] - (i > k), num) for i, num in enumerate(tickets))\n``` | 13 | 0 | [] | 4 |
time-needed-to-buy-tickets | ✅100%🔥Easy Solution🔥Beginner Friendly Solution🔥With explanation🔥 | 100easy-solutionbeginner-friendly-soluti-ko3a | \n\n# Approach\n Describe your approach to solving the problem. \n- To solve this problem, we\'ll maintain a count variable to track the time until the Kth pers | niteshjk | NORMAL | 2024-04-09T05:37:33.513329+00:00 | 2024-04-09T05:37:33.513349+00:00 | 1,591 | false | \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- To solve this problem, we\'ll maintain a count variable to track the time until the Kth person buys all available tickets. We\'ll also use an index variable to iterate through the tickets array.\n\n- We\'ll iterate through the tickets array until the value of the ticket at the Kth position becomes zero, indicating that all tickets have been purchased. Within the loop, we\'ll check two conditions to determine whether to increment the count. If the value of the ticket at the current index is greater than zero, we\'ll decrement the ticket value, increase the count, and increment the index by 1. Additionally, we\'ll use modulo operation to ensure that the index doesn\'t go out of bounds. If the ticket value is zero at the current index, we\'ll simply increment the index by 1.\n\n- Once the loop terminates, we\'ll return the count value, representing the time taken for the Kth person to buy all available tickets.\n\n# Complexity\n- Time complexity: $$O(n)$$ \n\n- Space complexity: $$O(1)$$ \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& tickets, int k) {\n int count = 0; // Variable to store the time\n int index = 0; // Variable to iterate through the array\n \n // Run the loop until the value at the k index becomes zero\n while (tickets[k] != 0) {\n if (tickets[index] > 0) {\n count++;\n tickets[index]--;\n index = (index + 1) % tickets.size();\n } else if (tickets[index] == 0) {\n index = (index + 1) % tickets.size();\n }\n }\n \n return count;\n }\n};\n\n``` | 12 | 0 | ['C++'] | 5 |
time-needed-to-buy-tickets | Java - Easy Solution O(n) | java-easy-solution-on-by-sparkle_30-mrm0 | Time Needed to Buy Tickets\n\nSimple and crisp Solution - \n\nInput: tickets = [2,3,2], k = 2\nOutput: 6\nExplanation: \n- In the first pass, everyone in the li | sparkle_30 | NORMAL | 2021-11-14T04:10:52.055269+00:00 | 2024-03-20T15:38:20.361475+00:00 | 1,897 | false | **Time Needed to Buy Tickets**\n\nSimple and crisp Solution - \n\n**Input:** tickets = [2,3,2], k = 2\n**Output:** 6\n**Explanation:** \n- In the first pass, everyone in the line buys a ticket and the line becomes [1, 2, 1].\n- In the second pass, everyone in the line buys a ticket and the line becomes [0, 1, 0].\nThe person at position 2 has successfully bought 2 tickets and it took 3 + 3 = 6 seconds.\n\n```\npublic int timeRequiredToBuy(int[] tickets, int k) {\n int timeTaken = 0;\n while(tickets[k] > 0) {\n \tfor(int i = 0; i < tickets.length; i++) {\n \t\tif(tickets[i] > 0) {\n \t\t\ttickets[i]--;\n \t\t\ttimeTaken++;\n \t\t}\n if(tickets[k] == 0) break;\n \t}\n }\n return timeTaken;\n }\n```\n\t\nTime Complexity - **O(n*k)**\n\n\t\n```\n\tpublic int timeRequiredToBuy(int[] tickets, int k) {\n\t int timeTaken = 0;\n for(int i = 0; i < tickets.length; i++){\n if(tickets[i] <= tickets[k]){\n timeTaken += tickets[i];\n }\n else timeTaken += tickets[k];\n if(i > k && tickets[i] >= tickets[k]) timeTaken--;\n }\n return timeTaken;\n }\n```\t\n\t\nTime Complexity - **O(n)**\n\nCredit - @yadavharsha50 | 11 | 0 | ['Java'] | 4 |
time-needed-to-buy-tickets | C++ || Very Easy || O(n) || My Thought | c-very-easy-on-my-thought-by-vivek_javiy-22iw | Hint :- Simple solustion is to count time for every element and return sum of it. \n\nJust bruthforces, Element before k index take min of element or that index | vivek_javiya | NORMAL | 2021-11-18T06:20:59.569089+00:00 | 2021-11-18T06:20:59.569139+00:00 | 1,373 | false | Hint :- Simple solustion is to count time for every element and return sum of it. \n\nJust bruthforces, Element before k index take min of element or that index value and ,after k index it take min of element-1 or that index. Here element-1 because in last round we will not go for element which index is greater then k.\n\n\n```\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& tickets, int k) {\n int ans =0;\n int n = tickets.size();\n int ele = tickets[k];\n for(int i=0;i< n; i++){\n if(i<=k){\n ans+= min(ele, tickets[i]);\n }else{\n ans+= min(ele-1, tickets[i]); \n }\n }\n return ans;\n }\n};\n```\n\n**Upvote If like my solustion ::)** | 10 | 0 | ['C', 'C++'] | 3 |
time-needed-to-buy-tickets | Simple approach ✅ with visual explanation 🔥|| No queue needed || Python3 | simple-approach-with-visual-explanation-imkqr | Intuition\nOne approach would be to simulate the exact scenario using a queue. That would work, but in the worst case it may take O(n^2) time because each secon | reas0ner | NORMAL | 2024-04-09T04:43:53.975411+00:00 | 2024-04-09T07:15:10.118015+00:00 | 738 | false | # Intuition\nOne approach would be to simulate the exact scenario using a queue. That would work, but in the worst case it may take O(n^2) time because each second would be needed to be counted in the loop.\n\nIs there something better, to figure out the time needed as we visit every element?\n\n# Approach\nFor the example [4, 2, 3, 5], we can draw out the time required in the queue-based scenario given in the question. \n\n\n\n\nThe number of seconds required can be found by counting in the above figure - 4 + 4 + 1 + 0 + 1 till it takes the 2nd index to have collected the 3 tickets. The rest of the hourglasses are not used.\n\nSo we can see the pattern - on the left, if greater number of tickets, it will only go till our tickets[k] at max, and if it\'s a lower number everything will be used. So we can get additional time of min(entry, target).\n\nOn the right, we will have the same calculation, just till one row less. You can understand from the code given below.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution:\n def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:\n res = 0\n target = tickets[k]\n for person, entry in enumerate(tickets):\n if person <= k:\n res += min(entry, target)\n else:\n if target <= entry:\n res += min(entry, target) - 1\n else:\n res += min(entry, target)\n \n return res\n```\n\nIf the solution helped you understand better please upvote :)\n | 9 | 1 | ['Array', 'Queue', 'Python3'] | 1 |
time-needed-to-buy-tickets | 👏Beats 100.00% of users with Java || ✅Simple & Easy Well Explained Solution 🔥💥 | beats-10000-of-users-with-java-simple-ea-v7s3 | Intuition\nCount the time min of the tickets[i] and tickets[k] except i and k is same and count ignore after k that is no need to count time after tickets[k] is | Rutvik_Jasani | NORMAL | 2024-04-10T06:37:25.275668+00:00 | 2024-04-10T06:37:25.275686+00:00 | 144 | false | # Intuition\nCount the time min of the tickets[i] and tickets[k] except i and k is same and count ignore after k that is no need to count time after tickets[k] is getting 0.\n\n# I Think This Can Help You(For Proof Click on the Image)\n[](https://leetcode.com/problems/time-needed-to-buy-tickets/submissions/1228295358/?envType=daily-question&envId=2024-04-09)\n\n# Approach\n1. Initilize time and ignore counter variable as 0.\n ```\n int time=0;\n int ignore=0;\n ```\n2. Iterate the loop and count time min of the tickets[i] and tickets[k] except when i and k is equal.\n3. Count ignore after k when tickets[k] is equal to 0 and tickets[i] is not equal to 0.\n ```\n for(int i=0;i<tickets.length;i++){\n if(i!=k){\n time = time + Math.min(tickets[k],tickets[i]);\n }\n if(tickets[i]>=tickets[k] && k<i){\n ignore++;\n }\n }\n ```\n4. Icrease time by tickets[k].\n ```\n time+=tickets[k];\n ```\n5. return time - ignore, beacuse we need to remove after k that is not having 0 in the time.\n ```\n return time - ignore;\n ```\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\n public int timeRequiredToBuy(int[] tickets, int k) {\n int time=0;\n int ignore=0;\n for(int i=0;i<tickets.length;i++){\n if(i!=k){\n time = time + Math.min(tickets[k],tickets[i]);\n }\n if(tickets[i]>=tickets[k] && k<i){\n ignore++;\n }\n }\n time+=tickets[k];\n return time - ignore;\n }\n}\n```\n\n | 8 | 0 | ['Array', 'Queue', 'Simulation', 'Java'] | 1 |
time-needed-to-buy-tickets | Beats 100%✅✅||Super Easy🔥 Approach with explanation✅🔥 | beats-100super-easy-approach-with-explan-kuqi | This question practically deals with to exhaust the linear possibilities till the kth ind. so,we check the values which are in corresponding to the kth value:\n | 21eca01 | NORMAL | 2024-04-09T03:57:04.717937+00:00 | 2024-04-09T03:57:04.717966+00:00 | 1,602 | false | **This question practically deals with to exhaust the linear possibilities till the kth ind. so,we check the values which are in corresponding to the kth value:**\n\n**there are 3 poss:**\n\n**1.```i<=k```:\nwhen this arises we will be checking whether the element is lower \n```if Yes``` exhaust it till the end.\n```if No``` exhaust it till the kth val (as gien in the question).**\n\n**2.```i>k```:\nwhen this occurs,we will basically check if the element is lower or not.\n```if yes```then we will exhaust it till the end.\n```if No```then we will exhaust it til kth element-1. beacuse when we reach the kth element linearly we will stop right there and will not move further than that.**\n\n**so,this was the tricky part here.**\n\n**ex.\n1.{1,1,1,2},k=3:\nthis will become{0,0,0,1}->{0,0,0,0} total time was ```5```.**\n\n**2.{1,1,1,2},k=2:\nthis will become {0,0,0,2}-> and we got our answer in ```3 sec``` so why move further so we add 0 for the next columns than k which is nothing but ```kth element-1```**\n# Code\n``` Java []\nclass Solution {\n public int timeRequiredToBuy(int[] tickets, int k) {\n int result=0;\n for(int i=0;i<tickets.length;i++){\n if(tickets[i]<tickets[k]) result+=tickets[i];\n else if(i<=k&&tickets[i]>=tickets[k]) result+=(tickets[k]);\n else result+=tickets[k]-1;\n }\n return result;\n }\n}\n```\n``` Python3 []\nclass Solution:\n def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:\n result = 0\n for i in range(len(tickets)):\n if tickets[i] < tickets[k]:\n result += tickets[i]\n elif i <= k and tickets[i] >= tickets[k]:\n result += tickets[k]\n else:\n result += tickets[k] - 1\n return result\n```\n``` C++ []\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& tickets, int k) {\n int result = 0;\n for (int i = 0; i < tickets.size(); i++) {\n if (tickets[i] < tickets[k]) {\n result += tickets[i];\n } else if (i <= k && tickets[i] >= tickets[k]) {\n result += tickets[k];\n } else {\n result += tickets[k] - 1;\n }\n }\n return result;\n }\n};\n```\n``` JavaScript []\nfunction timeRequiredToBuy(tickets, k) {\n let result = 0;\n for (let i = 0; i < tickets.length; i++) {\n if (tickets[i] < tickets[k]) {\n result += tickets[i];\n } else if (i <= k && tickets[i] >= tickets[k]) {\n result += tickets[k];\n } else {\n result += tickets[k] - 1;\n }\n }\n return result;\n}\n``` | 8 | 0 | ['Array', 'Simulation', 'C++', 'Java', 'Python3', 'JavaScript'] | 4 |
time-needed-to-buy-tickets | Easy Explained in Java, C++ and Python | easy-explained-in-java-c-and-python-by-s-dfi6 | Intuition\n1. Go through the line of people one by one. Each person buys one ticket at a time. Keep count of how many tickets are sold until the kth person has | Shivansu_7 | NORMAL | 2024-04-08T07:41:52.497915+00:00 | 2024-04-08T07:41:52.497948+00:00 | 1,890 | false | # Intuition\n1. Go through the line of people one by one. Each person buys one ticket at a time. Keep count of how many tickets are sold until the kth person has bought all the tickets they want.\n2. We will use Queue data structure for this.\n3. Point to be noted, Remember that those who have no more tickets to buy will leave the line, means we won\'t add them into the queue again.\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. **Create a Queue**: The function `timeRequiredToBuy` initializes a queue (FIFO - First In First Out) using `LinkedList`. This queue will hold indices of people waiting in line.\n\n2. **Initialize Time Counter**: A variable `time` is initialized to keep track of the time taken to sell all tickets.\n\n3. **Fill Queue**: The code loops through the `tickets` array and adds the indices of people to the queue. Each index represents a person in line.\n\n4. **Ticket Selling Loop**: The main part of the code is a while loop that runs as long as the queue is not empty. Inside this loop:\n - It dequeues an index from the queue, indicating the current person being served.\n - Decrements the number of tickets the current person wants to buy.\n - Increments the `time` counter to reflect the time taken.\n - Checks if the current person (`index`) is the same as `k` (the target person we\'re interested in), and if they have bought all their tickets. If so, the function returns the `time` taken.\n - If the current person still wants to buy more tickets (tickets[index] > 0), it enqueues the same index back into the queue, indicating that the person is still in line to buy more tickets.\n\n5. **Return Time**: If the loop completes without finding the kth person or the queue becomes empty, it returns the total `time` taken.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$ Since we are using the queue data Structure.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```Java []\nclass Solution {\n public int timeRequiredToBuy(int[] tickets, int k) {\n Queue<Integer> queue = new LinkedList<>();\n int time = 0;\n\n for(int i=0; i<tickets.length; i++) {\n queue.add(i);\n }\n\n while(!queue.isEmpty()) {\n int index = queue.poll();\n tickets[index]--;\n time++;\n\n if(tickets[index]==0 && index==k) {\n return time;\n }\n if(tickets[index] > 0) {\n queue.add(index);\n }\n }\n return time;\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& tickets, int k) {\n queue<int> queue;\n int time = 0;\n\n for(int i = 0; i < tickets.size(); i++) {\n queue.push(i);\n }\n\n while(!queue.empty()) {\n int index = queue.front();\n queue.pop();\n tickets[index]--;\n time++;\n\n if(tickets[index] == 0 && index == k) {\n return time;\n }\n if(tickets[index] > 0) {\n queue.push(index);\n }\n }\n return time;\n }\n};\n```\n```Python3 []\nclass Solution:\n def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:\n queue = deque()\n time = 0\n\n for i in range(len(tickets)):\n queue.append(i)\n\n while queue:\n index = queue.popleft()\n tickets[index] -= 1\n time += 1\n\n if tickets[index] == 0 and index == k:\n return time\n if tickets[index] > 0:\n queue.append(index)\n\n return time\n```\n | 8 | 1 | ['Queue', 'Python', 'C++', 'Java', 'Python3'] | 9 |
time-needed-to-buy-tickets | VERY EASY | JAVA SOLUTION | USING QUEUE | very-easy-java-solution-using-queue-by-y-m619 | \n\n# Code\n\nclass Solution {\n public int timeRequiredToBuy(int[] tickets, int k) {\n Queue<Integer> queue = new LinkedList<>();\n int ans = | yash_260 | NORMAL | 2023-05-05T19:41:49.040699+00:00 | 2023-05-05T19:41:49.040726+00:00 | 1,125 | false | \n\n# Code\n```\nclass Solution {\n public int timeRequiredToBuy(int[] tickets, int k) {\n Queue<Integer> queue = new LinkedList<>();\n int ans = 0;\n for(int i = 0; i < tickets.length; i++){\n queue.add(i);\n }\n while(!queue.isEmpty()){\n int index = queue.poll();\n tickets[index]--;\n ans++;\n if(tickets[index] == 0 && index == k){\n return ans;\n }\n if(tickets[index] > 0){\n queue.add(index);\n }\n }\n return ans;\n }\n}\n``` | 8 | 0 | ['Queue', 'Java'] | 3 |
time-needed-to-buy-tickets | C++ Solution || Beats 100 % || Easy to Understand and Easy Solution | c-solution-beats-100-easy-to-understand-exa4p | Intuition\nWe have to just keep decreasing 1 from each element.\n\n# Approach\n1. We will traverse the array and keep decreasing 1 from every element till the e | rishunaimish | NORMAL | 2023-02-15T12:58:44.358713+00:00 | 2023-02-15T12:58:44.358744+00:00 | 2,449 | false | # Intuition\nWe have to just keep decreasing 1 from each element.\n\n# Approach\n1. We will traverse the array and keep decreasing 1 from every element till the element at kth position gets 0.\n2. We will also keep a count variable to keep track of the steps required for kth element to reach 0.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& tickets, int k) {\n int count = 0, i = 0;\n\n while(tickets[k] != 0){\n if(i == tickets.size()){\n i = 0;\n }\n if(tickets[i] == 0){\n i++;\n continue;\n }\n tickets[i]--;\n count++;\n i++;\n }\n\n return count;\n }\n};\n``` | 8 | 0 | ['Array', 'Queue', 'C++'] | 4 |
time-needed-to-buy-tickets | 1 ms Java solution | 1-ms-java-solution-by-zac390-7nzi | ```\n public int timeRequiredToBuy(int[] tickets, int k) {\n \n int seconds = 0;\n int i = 0;\n while(tickets[k] != 0)\n {\n | zac390 | NORMAL | 2021-11-17T06:23:28.410315+00:00 | 2021-11-17T06:23:28.410383+00:00 | 628 | false | ```\n public int timeRequiredToBuy(int[] tickets, int k) {\n \n int seconds = 0;\n int i = 0;\n while(tickets[k] != 0)\n {\n if(tickets[i] != 0)\n {\n tickets[i] = tickets[i] -1;\n seconds++;\n }\n if(i == tickets.length - 1)\n {\n i = 0;\n continue;\n }\n i++;\n }\n\n return seconds;\n }\n | 8 | 0 | ['Java'] | 1 |
time-needed-to-buy-tickets | ✅Easy✨||C++|| Beats 100% || With Explanation || | easyc-beats-100-with-explanation-by-olak-v8av | \n# Approach\n Describe your approach to solving the problem. \n1. To solve this problem, we\'ll maintain a count variable to track the time until the Kth perso | olakade33 | NORMAL | 2024-04-09T06:03:11.205514+00:00 | 2024-04-09T06:03:11.205551+00:00 | 715 | false | \n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. To solve this problem, we\'ll maintain a count variable to track the time until the Kth person buys all available tickets. We\'ll also use an index variable to iterate through the tickets array.\n\n2. We\'ll iterate through the tickets array until the value of the ticket at the Kth position becomes zero, indicating that all tickets have been purchased. Within the loop, we\'ll check two conditions to determine whether to increment the count. If the value of the ticket at the current index is greater than zero, we\'ll decrement the ticket value, increase the count, and increment the index by 1. Additionally, we\'ll use modulo operation to ensure that the index doesn\'t go out of bounds. If the ticket value is zero at the current index, we\'ll simply increment the index by 1.\n\n3. Once the loop terminates, we\'ll return the count value, representing the time taken for the Kth person to buy all available tickets.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n# Code\n```\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& tickets, int k) {\n int count = 0; // Variable to store the time\n int index = 0; // Variable to iterate through the array\n \n // Run the loop until the value at the k index becomes zero\n while (tickets[k] != 0) {\n if (tickets[index] > 0) {\n count++;\n tickets[index]--;\n index = (index + 1) % tickets.size();\n } else if (tickets[index] == 0) {\n index = (index + 1) % tickets.size();\n }\n }\n \n return count;\n }\n};\n``` | 7 | 0 | ['C++'] | 1 |
time-needed-to-buy-tickets | BRUTE(DEQUE) + OPTIMISED(IN ONE PASS) | brutedeque-optimisedin-one-pass-by-super-n7j9 | 1)BRUTE FORCE APPROACH -> \nA) SIMULATE THE GIVEN PROBLEM USING DEQUE DATA STRUCTURE \nKEEP A COUNTER WHEN KTH ELEMENT BECOMES 0 THATS EASY :)\n\nTC -> O(K * A | superstar_2000 | NORMAL | 2021-11-14T13:59:55.006338+00:00 | 2021-11-14T14:34:45.004754+00:00 | 560 | false | 1)BRUTE FORCE APPROACH -> \nA) SIMULATE THE GIVEN PROBLEM USING DEQUE DATA STRUCTURE \nKEEP A COUNTER WHEN KTH ELEMENT BECOMES 0 THATS EASY :)\n\nTC -> O(K * ARR[K]) -> IN WORST CASE IF K IS LAST ELEMENT\nSC -> O(2*N) -> TAKEN A PAIR\n\nCODE -> \n```\n\t\tdeque<pair<int,int>>dq;\n for(int i = 0; i < tickets.size(); i++) {\n dq.push_back({tickets[i] , i});\n }\n int ans = 0;\n while(!dq.empty()) {\n int val = dq.front().first;\n int idx = dq.front().second;\n val--;\n ans++;\n if(idx == k && val == 0) {\n break;\n }\n if(val == 0) {\n dq.pop_front();\n } else {\n dq.pop_front();\n dq.push_back({val, idx});\n }\n }\n return ans;\n```\n\nOPTIMISED APPROACH->\n\nTHINK WITH RESPECT TO K -> TAKE 2 CASES\n1) ELEMENTS BEFORE K -> WILL TAKE MIN(ARR[I] , ARR[K]) STEPS IN TOTAL\n2) ELEMENTS AFTER K -> WILL TAKE MIN(ARR[I] , ARR[K] - 1 STEPS) IN TOTAL\n3) YOUR ANS IS (1 + 2) -> \n\nCODE -> \n```\n\t int ans = 1;\n int val = tickets[k];\n for(int i = 0 ; i < tickets.size(); i++) {\n if(i < k) {\n //THE ELEMENTS THAT LIE BEFORE K\n if(tickets[i] < val) {\n ans += tickets[i];\n } else {\n ans += val;\n }\n } else {\n //THE ELEMENTS THAT LIE AFTER K\n if(tickets[i] < val - 1) {\n ans += tickets[i];\n } else {\n ans += (val - 1);\n } \n } \n } \n return ans;\n```\n\nTC -> O(N) SINGLE PASS\nSC -> O(1) :)\n\nTHANK YOU DO SHARE AND UPVOTE IF YOU LIKED THE APPROACH\n | 7 | 0 | ['Queue'] | 2 |
time-needed-to-buy-tickets | C++ ✅ Easy Solution Without Queue 🔥 Beats 100% Users 🔥 | c-easy-solution-without-queue-beats-100-9ah1k | \n\n# Intuition\nThe function timeRequiredToBuy calculates the total time for the person at position k to finish buying all their tickets. The approach simulate | _sxrthakk | NORMAL | 2024-07-26T08:29:02.345020+00:00 | 2024-07-26T08:29:02.345055+00:00 | 143 | false | \n\n# Intuition\nThe function timeRequiredToBuy calculates the total time for the person at position k to finish buying all their tickets. The approach simulates the ticket buying process by looping through the line of people. In each iteration, for every person who still needs tickets (i.e., v[i] > 0), the code decrements their ticket count by one and increments the time counter c. This continues until the person at position k has no tickets left (v[k] == 0). The break statement ensures the loop terminates early if the person at position k finishes buying their tickets during the current pass through the line.\n\n# Approach\n1. **Initialization :**\n- The function timeRequiredToBuy takes a vector v of integers, where v[i] represents the number of tickets the i-th person wants to buy, and an integer k representing the index of the person of interest.\n- A counter c is initialized to 0 to keep track of the total time.\n\n2. **Outer Loop :** The outer while loop runs until the person at index k has bought all their tickets (v[k] == 0).\n\n3. **Inner Loop :**\n- The inner for loop iterates through each person in the queue.\n \n- If the current person (i-th person) has tickets to buy (v[i] > 0):\na) They buy one ticket, so v[i] is decremented by 1.\nb) The counter c is incremented by 1 to represent the time taken for this transaction.\n- After each ticket purchase, it checks if the person at index k has finished buying all their tickets (v[k] == 0). If so, it breaks out of the loop to avoid unnecessary iterations.\n\n4. **Return :** Once the person at index k has bought all their tickets, the function returns the total time c taken for this to happen.\n \n# Example Walkthrough\n\nFor instance, consider v = [2, 3, 2] and k = 2:\n\nInitial state: v = [2, 3, 2], c = 0.\n\n1. **First iteration of the while loop :**\n- v = [1, 3, 2], c = 1 (first person buys 1 ticket).\n- v = [1, 2, 2], c = 2 (second person buys 1 ticket).\n- v = [1, 2, 1], c = 3 (third person buys 1 ticket).\n \n2. **Second iteration of the while loop :**\n- v = [0, 2, 1], c = 4 (first person buys their last ticket).\n- v = [0, 1, 1], c = 5 (second person buys 1 ticket).\n- v = [0, 1, 0], c = 6 (third person buys their last ticket and now v[k] == 0).\n\nSo, the function will return 6, which is the total time taken for the person at position k to finish buying their tickets.\n\n# Time Complexity\n - **Best Case :** O(n) where n is Size of Vector\n- **Average Case :** The total number of iterations will depend on the average value of the array elements. If the average number of tickets each person buys is T/n, where T is the total number of tickets, the time complexity would be approximately O(n.T/n) = O(T).\n- **Worst Case :** If every person wants a large number of tickets, each requiring a full pass through the array, the time complexity is O(n.T).\n\n# Space complexity: O(1)\n\n# Code\n```\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& v, int k) {\n int c=0;\n while(v[k]!=0){\n for(int i =0;i<v.size();i++){\n if(v[i]>0){\n v[i]--;\n c++;\n }\n if(v[k]==0) break;\n }\n }\n return c;\n }\n};\n``` | 6 | 0 | ['Array', 'C++'] | 0 |
time-needed-to-buy-tickets | 🔥Easy||✅Cute||😎Perfecto||💥Beginner Friendly | easycuteperfectobeginner-friendly-by-doa-kdq2 | \n# Code\n\nclass Solution {\n public int timeRequiredToBuy(int[] tickets, int k) {\n int total = 0;\n\n for (int i = 0; i < tickets.length; i+ | DoaaOsamaK | NORMAL | 2024-04-09T10:48:38.186939+00:00 | 2024-04-09T10:48:38.186966+00:00 | 60 | false | \n# Code\n```\nclass Solution {\n public int timeRequiredToBuy(int[] tickets, int k) {\n int total = 0;\n\n for (int i = 0; i < tickets.length; i++) {\n if (i <= k) {\n total += Math.min(tickets[i], tickets[k]);\n } else {\n total += Math.min(tickets[i], tickets[k] - 1);\n }\n }\n\n return total;\n }\n}\n``` | 6 | 0 | ['Java'] | 0 |
time-needed-to-buy-tickets | Time Complexity : O(N) Space Complexity : O(1) [Diagrammatic Explanation] | time-complexity-on-space-complexity-o1-d-3eyp | Intuition & Approach\n\n\n\n\n# Complexity\n- Time complexity: O( size of array tickets[] )\n\n- Space complexity: O( 1 ) Constant\n\n\n# Code\n\nclass Solution | soyama_hakuji | NORMAL | 2024-04-09T08:50:48.360149+00:00 | 2024-04-09T08:50:48.360173+00:00 | 145 | false | # Intuition & Approach\n\n\n\n\n# Complexity\n- Time complexity: O( size of array tickets[] )\n\n- Space complexity: O( 1 ) Constant\n\n\n# Code\n```\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& tickets, int k) {\n int res = 0;\n for(int i = 0; i < tickets.size(); i ++){\n if(tickets[i]<tickets[k]) res+=tickets[i];\n else res+= (i<=k)?tickets[k]:tickets[k]-1;\n }\n return res;\n }\n};\n\n``` | 6 | 0 | ['C++'] | 3 |
time-needed-to-buy-tickets | Simple C++ code | simple-c-code-by-prosenjitkundu760-1fh2 | If you like the implementation then Please help me by increasing my reputation. By clicking the up arrow on the left of my image.\n\nclass Solution {\npublic:\n | _pros_ | NORMAL | 2022-05-14T10:54:35.847591+00:00 | 2022-05-14T10:54:35.847632+00:00 | 663 | false | # **If you like the implementation then Please help me by increasing my reputation. By clicking the up arrow on the left of my image.**\n```\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& tickets, int k) {\n queue<pair<int,int>>q;\n int time = 0;\n for(int i = 0; i < tickets.size(); i++)\n {\n q.push({tickets[i],i});\n }\n while(!q.empty())\n {\n pair<int,int> tmp = q.front();\n q.pop();\n --tmp.first;\n ++time;\n if(tmp.first == 0 && tmp.second == k)\n {\n break;\n }\n else if(tmp.first != 0)\n {\n q.push({tmp.first,tmp.second});\n }\n }\n return time;\n }\n};\n``` | 6 | 0 | ['Queue'] | 2 |
time-needed-to-buy-tickets | C++ 0ms Explained Easy one pass | c-0ms-explained-easy-one-pass-by-kaustub-6z2p | Three cases possible are,\n\nIf the ticket holders have less tickets to buy than our Kth ticket holder, they will have got all the tickets they wanted before kt | kaustubh07 | NORMAL | 2021-11-14T04:30:48.808748+00:00 | 2021-11-26T20:26:01.073803+00:00 | 718 | false | Three cases possible are,\n\n`If` the ticket holders have less tickets to buy than our Kth ticket holder, they will have got all the tickets they wanted before kth ticket holder gets all its tickets,\n\n`else if` the ticket holders have more ticketsto buy than our Kth ticket holder, and they are ahead in line(position < k) then, they will have bought `tickets[k]` tickets before kth ticket holder gets all the tickets it needs,\n\n`else if` the ticket holders have more tickets to buy than our Kth ticket holder, and they are behind in line(position > k) then, they will have bought 1 ticket less than `tickets[k]` before kth ticket holder gets all the tickets it needs.\n\n```\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& tickets, int k) {\n \n int ticket = tickets[k];\n int res = 0;\n for(int i = 0; i<tickets.size(); i++){\n if(tickets[i] < ticket) res+=tickets[i];\n else if(tickets[i] >= ticket and i <= k) res+=ticket;\n else if(tickets[i] >= ticket and i > k) res+=ticket-1;\n }\n return res;\n }\n};\n``` | 6 | 1 | ['C', 'C++'] | 6 |
time-needed-to-buy-tickets | beats 100% simple solution | beats-100-simple-solution-by-harshjat-t0yl | IntuitionPeople before and at index k will buy up to tickets[k] tickets.
People after index k will buy up to tickets[k] - 1 tickets, since they stop when k fini | harshjat | NORMAL | 2025-03-02T13:38:33.261851+00:00 | 2025-03-02T13:38:33.261851+00:00 | 130 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
People before and at index k will buy up to tickets[k] tickets.
People after index k will buy up to tickets[k] - 1 tickets, since they stop when k finishes.
# Approach
<!-- Describe your approach to solving the problem. -->
Iterate through the entire array (size n).
For each index i:
If i ≤ k: The person buys up to min(tickets[i], tickets[k]) tickets.
If i > k: The person buys up to min(tickets[i], tickets[k] - 1) tickets (since they don't get another turn after k finishes).
Sum up the tickets bought by all individuals to determine the total time taken.
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
O(n)
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
o(1)

# Code
```cpp []
class Solution {
public:
int timeRequiredToBuy(vector<int>& tickets, int k) {
int n= size(tickets);
int count = 0;
for(int i=0;i<n;i++){
if(i<=k){
count+=min(tickets[i],tickets[k]);
}
else{
count+=min(tickets[i],tickets[k]-1);
}
}
return count;
}
};
``` | 5 | 0 | ['C++'] | 0 |
time-needed-to-buy-tickets | easy to understand JS | easy-to-understand-js-by-javad_pk-0fel | 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 | javad_pk | NORMAL | 2024-04-09T09:18:34.395199+00:00 | 2024-04-09T09:18:34.395232+00:00 | 264 | 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```\n/**\n * @param {number[]} tickets\n * @param {number} k\n * @return {number}\n */\nvar timeRequiredToBuy = function(t, k) {\n let s=0,i=0\n while(t[k]!==0){\n if(t[i]>0){\n s++\n t[i]--\n if(t[k]==0) return s\n }\n if(i==t.length-1) i=0\n else i++\n }\n};\n``` | 5 | 0 | ['JavaScript'] | 0 |
time-needed-to-buy-tickets | 💯JAVA Solution Explained in HINDI | java-solution-explained-in-hindi-by-the_-1h19 | https://youtu.be/mAWSTUdCb_s\n\nFor explanation, please watch the above video and do like, share and subscribe the channel. \u2764\uFE0F Also, please do upvote | The_elite | NORMAL | 2024-04-09T06:55:25.076447+00:00 | 2024-04-09T06:55:25.076466+00:00 | 504 | false | https://youtu.be/mAWSTUdCb_s\n\nFor explanation, please watch the above video and do like, share and subscribe the channel. \u2764\uFE0F Also, please do upvote the solution if you liked it.\n\nSubscribe link:- [ReelCoding](https://www.youtube.com/@reelcoding?sub_confirmation=1)\n\nSubscribe Goal:- 400\nCurrent Subscriber:- 303\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int timeRequiredToBuy(int[] tickets, int k) {\n \n int time = 0;\n\n for(int i = 0; i < tickets.length; i++) {\n\n if(i <= k) {\n time += Math.min(tickets[k], tickets[i]);\n }\n else {\n time += Math.min(tickets[k] - 1, tickets[i]);\n }\n }\n return time;\n }\n}\n``` | 5 | 0 | ['Java'] | 0 |
time-needed-to-buy-tickets | 🔥 8 lines of code beat 100% users 🚀 fully explained with example ✅ || Easy to understand 👍 | 8-lines-of-code-beat-100-users-fully-exp-tgo7 | Intuition\n# Python, Python3 and C++ :\n1. Initialization :\n 1. Initialize a variable \'c\' to keep track of the total number of tickets bought.\n 2. Sta | siddharth-kiet | NORMAL | 2024-04-09T06:17:51.049536+00:00 | 2024-04-09T06:17:51.049566+00:00 | 2,491 | false | # Intuition\n# Python, Python3 and C++ :\n1. **Initialization :**\n 1. Initialize a variable **\'c\'** to keep track of the total number of tickets bought.\n 2. Start an infinite loop **(while True)** It checks until the person at position k finishes buying his tickets.\n2. **if tickets[k] == 0: break :** If the person at position **\'k\'** has bought all his tickets, than exit the while loop.\n3. **for i in range(len(tickets)) :** Iterate through each person in the line.\n4. **if tickets[k] == 0: break :** If the person at position k has bought all his tickets, than exit the for loop.\n**Note :** I have use **\'if tickets[k] == 0: break\'** this condition 2 times cause after we get exit from the **for** loop than at the same time we have to take exit from **while infinte loop** otherwise we will get stuck in while loop so we exit both loop at the same time hence we get the value of **\'c\'**.\n5. **if tickets[i]>0 :** Here we check from the start of the array If the person has tickets left to buy and waits until his turn while other peoples in the queue buys the ticket. and we does not count that tickets values which becomes zero thats why we use condition **tickets[i]>0** and if this condition is true we decrease the value of **tickets[i]** by 1 that means 1 ticket is sold(Buys one ticket) and at the same time we increase the value of **\'c\'** by 1 it tells us the exact count aur time taken by the **\'kth\'** person for buying all his tickets.\n6. **return c :** Return the total time taken for the person at position **\'k\'** to finish buying tickets.\n\n**Lets see the example for better understanding :**\n**Example 1 : tickets = [2,3,2], k = 2**\nlets enter the while loop and check the first condition **if tickets[k]==0 :** and **tickets[2]=2** and its not zero so we enter the **for** loop and check the same condition **if tickets[k]==0** it helps to take exit from the for loop but this time this condition is not true so we go to next condition **if tickets[i]>0** and start decreasing the tickets[i] by 1 and increase the **\'c\'** by 1 so after first pass our array becomes **[1,2,1]** and **c=3** as we are inside the while loop so we again check the condition **if tickets[k]==0** means tickets[2]=1 so we enter the for loop again and check same condition and enter the next condition **if tickets[i]>0** now array becomes **[0,1,0]** and **c=6** as soon as the **kth** element becomes 0 we does not have to check further on other elements and our kth element becomes zero and **if tickets[k]==0:** condition becomes true so we take exit from the for loop and for taking exit from the while loop we check the same condition and take exit from the while loop and retrun the value of **c=6**\n\n**I hope you understand the code \uD83D\uDE4F and if you have any query let me know in the comment.**\n**Thanks you all for visiting here.**\n\n# Approach : Brute Force\n\n# Complexity\n- Time complexity: O(n * max(tickets)) n = number of tickets\n\n\n- Space complexity: O(n)\n\n# Code\n``` Python3 []\nclass Solution:\n def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:\n c=0\n while True:\n if tickets[k]==0: break\n for i in range(len(tickets)):\n if tickets[k]==0: break\n if tickets[i]>0:\n tickets[i]-=1\n c+=1\n return c\n```\n``` Python []\nclass Solution(object):\n def timeRequiredToBuy(self, tickets, k):\n """\n :type tickets: List[int]\n :type k: int\n :rtype: int\n """\n c=0\n while True:\n if tickets[k]==0: break\n for i in range(len(tickets)):\n if tickets[k]==0: break\n if tickets[i]>0:\n tickets[i]-=1\n c+=1\n return c\n```\n``` C++ []\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& tickets, int k) {\n int c=0;\n while (true){\n if(tickets[k]==0) \n break;\n for(int i=0;i<tickets.size();i++){\n if(tickets[k]==0)\n break;\n if(tickets[i]>0){\n tickets[i]-=1;\n c+=1;\n }\n }\n }\n return c;\n }\n};\n``` | 5 | 0 | ['Array', 'Queue', 'Simulation', 'Python', 'C++', 'Python3'] | 2 |
time-needed-to-buy-tickets | Beginner Friendly!!!🔥🔥 Beats 100% Simple iterative approach no special data structure used !! ⭐⭐⭐⭐ | beginner-friendly-beats-100-simple-itera-d3ak | \n\n# Intuition\n Describe your first thoughts on how to solve this problem. \nI have tried to do the solution in single loop so divide into two halves one incl | jiteshSingh | NORMAL | 2024-04-09T05:20:22.312133+00:00 | 2024-04-09T05:21:03.641259+00:00 | 168 | false | \n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nI have tried to do the solution in single loop so divide into two halves one including target and earlier ones and the other having remaining ones .\n# Approach\n<!-- Describe your approach to solving the problem. -->\nint target = tickets[k];: This line fetches the price of the ticket at the position k in the queue. This will be the maximum price you\'ll pay.\n\nint ans = 0;: This initializes the variable ans to store the total time required to buy all the tickets.\n\nThe first loop (for(;i<=k;i++)) iterates from the beginning of the queue up to your position k. Inside this loop:\n\nIf the price of the ticket at the current position (tickets[i]) is greater than target, it means you\'ll pay target.\nOtherwise, you pay the actual price of the ticket (tickets[i]).\nThe corresponding time required to buy the ticket is added to ans.\nAfter the first loop, i will be equal to k+1, pointing to the next ticket after your position in the queue.\n\nThe second loop (for(;i<tickets.size();i++)) iterates from the position after k until the end of the queue. Inside this loop:\n\nIf the price of the ticket at the current position (tickets[i]) is greater than or equal to target, it means you\'ll pay target - 1 because you can\'t exceed target.\nOtherwise, you pay the actual price of the ticket (tickets[i]).\nThe corresponding time required to buy the ticket is added to ans.\nFinally, the function returns the total time required (ans).\n\n# Complexity\n- Time complexity:O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& tickets, int k) {\n int target = tickets[k] ; \n int ans = 0 ; \n int i=0;\n for(;i<=k;i++){\n if(tickets[i]>target){\n ans += target ; \n }\n else ans += tickets[i] ; \n }\n for(;i<tickets.size();i++){\n if(tickets[i]>=target){\n ans += target-1 ; \n }\n else ans += tickets[i] ; \n }\n return ans ; \n }\n};\n``` | 5 | 0 | ['C++'] | 3 |
time-needed-to-buy-tickets | Simple While Loop | simple-while-loop-by-tanmay656565-dwze | \n# Code\n\nclass Solution:\n def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:\n time = 0\n i = 0 \n length = len(tickets | tanmay656565 | NORMAL | 2024-04-09T05:18:29.964536+00:00 | 2024-04-09T05:18:29.964572+00:00 | 235 | false | \n# Code\n```\nclass Solution:\n def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:\n time = 0\n i = 0 \n length = len(tickets)\n while tickets[k] != 0 :\n if i == length :\n i = 0 \n if tickets[i] != 0 :\n time += 1\n tickets[i] -= 1\n i += 1\n return time\n\n``` | 5 | 0 | ['Python3'] | 0 |
time-needed-to-buy-tickets | C++ || O(n) and O(1) TIME AND SPACE || Apr 9 2024 Daily | c-on-and-o1-time-and-space-apr-9-2024-da-ubg7 | Intuition\nThe problem seems to require simulating the process of people buying tickets in a queue. Each person buys tickets one by one, and if they run out of | praneelpa | NORMAL | 2024-04-09T00:03:56.204301+00:00 | 2024-04-09T00:03:56.204321+00:00 | 1,246 | false | # Intuition\nThe problem seems to require simulating the process of people buying tickets in a queue. Each person buys tickets one by one, and if they run out of tickets to buy, they leave the line. We need to find out how much time it takes for the person at position k to finish buying tickets.\n\n# Approach\n- We iterate through the people in the queue.\n- For each person, if their position is before or equal to k, they buy the minimum of their required tickets and the tickets that the person at position k wants.\n- If the person\'s position is after k, they buy the minimum of their required tickets and one less than the tickets that the person at position k wants (since the person at position k has already bought some tickets).\n- We accumulate the time taken for each person to buy their tickets.\n\n# Complexity\n- Time complexity:\nThe time complexity of the solution is O(n), where n is the number of people in the queue. We iterate through the queue once to calculate the time taken for each person to buy tickets.\n\n- Space complexity:\nThe space complexity is O(1) because we only use a constant amount of extra space regardless of the input size. The space used for variables such as `ans`, `i`, and `k` is fixed and doesn\'t depend on the number of people in the queue.\n\n\n# Code\n```\nclass Solution {\n public:\n int timeRequiredToBuy(vector<int>& tickets, int k) {\n int ans = 0;\n\n for (int i = 0; i < tickets.size(); ++i)\n if (i <= k)\n ans += min(tickets[i], tickets[k]);\n else\n ans += min(tickets[i], tickets[k] - 1);\n\n return ans;\n }\n};\n``` | 5 | 0 | ['Array', 'Queue', 'Simulation', 'C++'] | 7 |
time-needed-to-buy-tickets | 100% beats O(n) solution without using queue | 100-beats-on-solution-without-using-queu-k2kl | 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 | satyam_1972 | NORMAL | 2023-06-08T19:23:29.498948+00:00 | 2023-06-08T19:23:29.498971+00:00 | 801 | 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 Solution {\npublic:\n int timeRequiredToBuy(vector<int>& tickets, int k) {\n int n=tickets.size();\n int total=tickets[k];\n\n for(int i=0;i<k;i++){\n total+=min(tickets[k],tickets[i]);\n }\n for(int i=k+1;i<n;i++){\n total+=min(tickets[k]-1,tickets[i]);\n }\n return total;\n }\n};\n``` | 5 | 0 | ['C++'] | 1 |
time-needed-to-buy-tickets | Easy Java Solution | easy-java-solution-by-priyankan_23-mtnq | \nclass Solution {\n public int timeRequiredToBuy(int[] tickets, int k) {\n int count=0;\n while(tickets[k]>0){\n for(int i=0;i<tickets. | priyankan_23 | NORMAL | 2022-09-12T15:23:49.715995+00:00 | 2022-09-12T15:23:49.716035+00:00 | 596 | false | ```\nclass Solution {\n public int timeRequiredToBuy(int[] tickets, int k) {\n int count=0;\n while(tickets[k]>0){\n for(int i=0;i<tickets.length;i++){\n if(tickets[i]>0){\n tickets[i]-=1;\n count++;\n }\n if(tickets[k]==0)break;\n }\n }\n return count;\n }\n}\n``` | 5 | 0 | ['Java'] | 2 |
time-needed-to-buy-tickets | ✅[Python] Simple and Clean, beats 77.69%✅ | python-simple-and-clean-beats-7769-by-_t-qtaw | Please upvote if you find this helpful. \u270C\n\n\nThis is an NFT\n\n##### Single Pass Solution\n1. People before k-th person will take mininum of reqd tickets | _Tanmay | NORMAL | 2022-08-27T10:11:03.527730+00:00 | 2023-03-14T19:10:49.666476+00:00 | 634 | false | ### Please upvote if you find this helpful. \u270C\n<img src="https://assets.leetcode.com/users/images/b8e25620-d320-420a-ae09-94c7453bd033_1678818986.7001078.jpeg" alt="Cute Robot - Stable diffusion" width="200"/>\n\n*This is an NFT*\n\n##### **Single Pass Solution**\n1. People before *k-th* person will take mininum of reqd tickets and *k-th* person ticket\n2. People after *k-th* person will take 1 ticket less than, because after oue person takes the ticket the objective will be completed and we do not need to count more time for people **standing after him**\n\n##### **Implementation**\n```\nclass Solution:\n def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:\n num = tickets[k]\n res = 0\n for i in range(k+1):\n res += min(tickets[i],num)\n for i in range(k+1,len(tickets)):\n res += min(tickets[i],num-1)\n return res\n```\n\n\n | 5 | 0 | ['Greedy', 'Python'] | 0 |
time-needed-to-buy-tickets | JAVA Solution, Faster than 100% of all submissions O(n) | java-solution-faster-than-100-of-all-sub-s5js | \n\nclass Solution {\n public int timeRequiredToBuy(int[] tickets, int k) {\n int output = 0;\n int n = tickets.length;\n for (int i = 0;i<n; | fakhreddinechaabani | NORMAL | 2022-02-11T17:41:28.257225+00:00 | 2022-02-11T17:55:40.827795+00:00 | 367 | false | ```\n\nclass Solution {\n public int timeRequiredToBuy(int[] tickets, int k) {\n int output = 0;\n int n = tickets.length;\n for (int i = 0;i<n;i++){\n if(tickets[i] < tickets[k]){\n output += tickets[i];\n }else{\n if(i <= k){\n output += tickets[k];\n }else { \n output += tickets[k] - 1;\n } \n }\n\n }\n return output;\n }\n}\n```\n``` | 5 | 0 | [] | 0 |
time-needed-to-buy-tickets | Time Needed to Buy Tickets - Time and Space Complexity Optimized | time-needed-to-buy-tickets-time-and-spac-x9o7 | \n\n\n# Approach\n Describe your approach to solving the problem. \n1. Intialize a Variable \'ans\' for storing the time needed for buying the tickets\n\n2. Tra | Pranesh_Pandian | NORMAL | 2024-04-09T05:54:23.519786+00:00 | 2024-04-09T05:54:23.519830+00:00 | 115 | false | \n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n**1. Intialize a Variable \'ans\' for storing the time needed for buying the tickets**\n\n**2. Traverse through the entire array ans update the ans with the following conditions**\n \n if(tickets[i]>=tickets[k]){ans+=tickets[k];}\n\nAs we wont take more than tickets[k] rounds to buy tickets as the desired target is tickets[k]\n\nAlso if the k is in the middle of the array we won\'t require the people\'s turn after the tickets[k] in the kth round, so we add a condition as\n \n if(tickets[i]>=tickets[k]){ans+=tickets[k]; if(i>k) ans--;}\n\nby this we can find the optimal time needed\n\n**Example**\n\nLet\'s take the case [2,3,2,4] and k=1\n\nNow by our solution we traverse from 0 to tickets.length-1\n\nIn i=0 -> **tickets[i]=2** which is less than **tickets[k]=3** so the ans is incremented by **tickets[i]=2** so ans becomes **ans=2**\n\nIn i=1 -> **tickets[i]=3** which is equal to **tickets[k]=3** so the ans is incremented by **tickets[k]=3** so ans becomes **ans=5** since the i is not greater than k the ans is left unchanged\n\nIn i=2 -> **tickets[i]=2** which is less than **tickets[k]=3** so the ans is incremented by **tickets[i]=2** so ans becomes **ans=7**\n\nIn i=3 -> **tickets[i]=4** which is greater than **tickets[k]=3** so the ans is incremented by **tickets[k]=3** so ans becomes **ans=10** but the k is greater than i so the ans is decremented by 1\n\n in the case of 2 3 2 4\n 1st round -> 1 2 1 3\n 2nd round -> 0 1 0 2\n 3rd round -> 0 0 | 0 1\n\nas the need of the greater elements after the index k is not needed in the last round so the number of greater elements is decremented to get the optimal time.\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(1)$$\n\n# Code\n\n```java []\nclass Solution {\n public int timeRequiredToBuy(int[] tickets, int k) {\n int ans=0;\n for(int i=0;i<tickets.length;i++){\n if(tickets[i]>=tickets[k]){ans+=tickets[k];if(i>k) ans--;}\n else ans+=tickets[i];\n }\n return ans;\n }\n}\n```\n\n```C++ []\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& tickets, int k) {\n int ans=0;\n for(int i=0;i<tickets.size();i++){\n if (tickets[i]>=tickets[k]){ans+=tickets[k]; if(i>k) ans--;} \n else ans += tickets[i];\n }\n return ans;\n }\n};\n\n```\n```python []\nclass Solution:\n def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:\n ans=0\n for i in range(len(tickets)):\n if tickets[i]>=tickets[k]:\n ans+=tickets[k]\n if i>k:\n ans-=1\n else:\n ans+=tickets[i]\n return ans\n```\n | 4 | 0 | ['Python', 'C++', 'Java', 'Python3'] | 0 |
time-needed-to-buy-tickets | ✅ 🔥Time to buy | Java | O(n) - time O(1) - space | 100% ✅ 🔥 | time-to-buy-java-on-time-o1-space-100-by-0ttw | Hi, \n\nThe rationale behind this approach is that when standing in a queue for tickets, if each person can only purchase one ticket at a time, the person ahead | Surendaar | NORMAL | 2024-04-09T05:14:16.515002+00:00 | 2024-04-09T05:14:16.515033+00:00 | 259 | false | Hi, \n\nThe rationale behind this approach is that when standing in a queue for tickets, if each person can only purchase one ticket at a time, the person ahead of you can obtain a maximum of the same number of tickets you currently hold, while the person behind you can acquire a maximum of the tickets you need minus one.\n\n**Steps**\n* Know how many tickets you need and store it in a variable (**val**).\n* To keep track of time, initialize a variable (**res**) and assign it to 0.\n* Now, iterate through the array:\n\t* If the index of the person is less than or equal to yours, then they can get a maximum of either your number of tickets or the number of tickets they need.\n\t* If the index is greater than yours, then they can get a maximum of either your number of tickets minus one or the number of tickets they need.\n* Add these to the result (**res**) and return the result.\n\n**Time complexity - O(n)\nSpace complexity - O(1)**\n\nHere is the code for the same.. Happy coding..\n\n```\n public int timeRequiredToBuy(int[] tickets, int k) {\n int val = tickets[k], res=0;\n for(int i=0; i<tickets.length; i++){\n if(i<=k){\n res = res+Math.min(tickets[i], val);\n } else{\n res = res+Math.min(tickets[i], val-1);\n }\n }\n return res;\n }\n\t\n\t```\n\tPlease take a second to upvote and motivate others.. | 4 | 0 | ['Math', 'Java'] | 0 |
time-needed-to-buy-tickets | C# Solution for Time Needed to Buy Tickets Problem | c-solution-for-time-needed-to-buy-ticket-a0nm | Intuition\n Describe your first thoughts on how to solve this problem. \nThe intuition behind the approach is to simulate the process of buying tickets, conside | Aman_Raj_Sinha | NORMAL | 2024-04-09T03:59:32.753262+00:00 | 2024-04-09T03:59:32.753293+00:00 | 228 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition behind the approach is to simulate the process of buying tickets, considering that the person at position k can buy only one ticket at a time before going to the back of the line.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe approach iterates through the tickets array:\n\n\u2022\tFor indices less than or equal to k, it adds the minimum of the number of tickets the person at position k wants and the number of tickets the current person wants to buy.\n\u2022\tFor indices greater than k, it adds the minimum of one less than the number of tickets the person at position k wants (to account for the fact that they buy tickets one by one) and the number of tickets the current person wants to buy.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n), where n is the length of the tickets array. We iterate through the array once.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1). The space used is constant, as we only use a few extra variables regardless of the size of the input.\n\n# Code\n```\npublic class Solution {\n public int TimeRequiredToBuy(int[] tickets, int k) {\n int n = tickets.Length;\n int time = 0;\n\n for (int i = 0; i < n; i++) {\n if (i <= k) {\n time += Math.Min(tickets[k], tickets[i]);\n } else {\n time += Math.Min(tickets[k] - 1, tickets[i]);\n }\n }\n\n return time;\n }\n}\n``` | 4 | 0 | ['C#'] | 0 |
time-needed-to-buy-tickets | ✅ Easy Solution in Java | | With explanation🔥 | easy-solution-in-java-with-explanation-b-nsjx | Intuition\n Describe your first thoughts on how to solve this problem. \n- The code aims to find out how much time it would take for a person to buy a certain n | Vasu15 | NORMAL | 2024-04-09T03:20:57.256510+00:00 | 2024-04-09T03:20:57.256538+00:00 | 287 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- The code aims to find out how much time it would take for a person to buy a certain number of tickets (specified by k) given an array tickets where each element represents the number of available tickets at a particular counter.\n- The code iterates through the array in a circular manner, simulating a round-robin approach.\n- At each iteration, it tries to buy tickets from each counter (tickets[i]), decrementing the count of available tickets and counting the total time (c) taken to buy all the required tickets (k).\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Initialization:\n\n - Initialize variables c and i to 0.\n - c will track the total time taken to buy all tickets, and i will be used to iterate through the array of counters.\n2. Iterative Process:\n\n - The code enters a while loop which continues until there are no more tickets left at the specified counter k.\n - Inside the loop, it checks if there are still tickets available at the current counter tickets[k] > 0.\n - It then iterates through each counter using the variable i:\n - If there are tickets available at the current counter tickets[i] > 0, it decrements the count of available tickets and increments the total time c.\n - It then moves to the next counter by incrementing i.\n - If i reaches the end of the array, it resets i to 0 to continue the circular iteration.\n3. Returning the Result:\n\n - Once the while loop exits (indicating no more tickets available at counter k), it returns the total time c taken to buy all the tickets.\n\n# Complexity\n- Time complexity:\n - In the worst-case scenario, the code might iterate through all the counters to buy all the tickets.\n - Let m be the average number of counters needed to buy all the tickets. The time complexity would be O(m).\n\n- Space complexity:\n - The space complexity is O(1) as no additional space is used that grows with the size of the input.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int timeRequiredToBuy(int[] tickets, int k) {\n int c=0 , i=0;\n int n= tickets.length;\n while(tickets[k]>0){\n if(tickets[i]>0){\n tickets[i]--;\n c++;\n }\n i++;\n //System.out.println(c);\n if(i==n){\n i=0;\n }\n }\n return c;\n }\n}\n``` | 4 | 0 | ['Array', 'Queue', 'Simulation', 'Java'] | 0 |
time-needed-to-buy-tickets | easy C++ solution | easy-c-solution-by-prashant_71200-w39l | Intuition\nThe problem seems to be about buying tickets, where the cost of each ticket might vary, and you want to find out how much time it would take to buy a | prashant_71200 | NORMAL | 2024-04-09T03:10:03.382314+00:00 | 2024-04-09T03:10:03.382342+00:00 | 494 | false | # Intuition\nThe problem seems to be about buying tickets, where the cost of each ticket might vary, and you want to find out how much time it would take to buy all the tickets if you start buying from a specific index k.\n# Approach\nThe approach taken in the provided code is to iterate through the array twice:\n\n1) First, iterate from the beginning of the array up to index k (exclusive) and add the minimum of the cost at index k and the cost at each index encountered.\n2) Then, iterate from index k+1 to the end of the array and add the minimum of (tickets[k] - 1) and the cost at each index encountered.\n\nThe total time required to buy all the tickets is then returned.\n# Complexity\n- Time complexity:\nThe algorithm iterates through the array twice, once from the beginning to index k and once from index k+1 to the end. Both iterations are linear, so the time complexity is O(n), where n is the number of elements in the tickets array.\n- Space complexity:\nThe space complexity of the algorithm is O(1) because it uses a constant amount of extra space regardless of the size of the input array.\n# Code\n```\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& tickets, int k) {\n int n=tickets.size();\n int total=tickets[k];\n\n for(int i=0;i<k;i++){\n total+=min(tickets[k],tickets[i]);\n }\n for(int i=k+1;i<n;i++){\n total+=min(tickets[k]-1,tickets[i]);\n }\n return total;\n }\n};\n```\nUPVOTE IF YOU FIND ITS USEFULL | 4 | 0 | ['C++'] | 1 |
time-needed-to-buy-tickets | ✅ Beats 100% | How to think about approch | O(n) time✅ | beats-100-how-to-think-about-approch-on-lj240 | In this i will explain what my thought process was and how i arrived to the solution\n# Intuition\n1. Lets start with the easiest case if only one person in que | nithesh487 | NORMAL | 2024-04-09T02:42:30.257174+00:00 | 2024-04-09T02:46:02.462709+00:00 | 22 | false | In this i will explain what my thought process was and how i arrived to the solution\n# Intuition\n1. Lets start with the easiest case if only one person in queue then answer is tickets[0].\n2. No what if all people are stading infront lets take case where k = tickets.size()-1 i.e., standing int last of queue\n -You can solve this manually once on paper and realize that answer will be sum of min(tickets person in front wants, tickets K wants). \n -Another way of thinking about this is it number of times people in front k will visit is either tickets[k] times since if the value is more than that also k will be gone from the queue and if the value is less than tickets[k] then they will be gone from the queue and visit again\n3. Now what about people behind k. This is simple everyone behind k will come infront of him once k tickets his first tickets so then applying the logic applied before it become sum of min(tickets person in front wants, tickets K wants - 1).\n\n# Approach\ncode is pretty easy so wont explain that\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& arr, int k) {\n int ans = 0;\n for(int i = 0; i < k + 1; i++)\n ans += min(arr[i], arr[k]);\n for(int i = k + 1; i < arr.size(); i++)\n ans += min(arr[i], arr[k]-1);\n \n return ans;\n }\n};\n``` | 4 | 0 | ['C++'] | 0 |
time-needed-to-buy-tickets | C++ Simulation. No math because I suck at math. | c-simulation-no-math-because-i-suck-at-m-ss1o | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nSimulation\n\n# Complexity\n- Time complexity:\n O(n*tickets[k]) \n\n- Sp | midnightsimon | NORMAL | 2024-04-09T01:38:33.232813+00:00 | 2024-04-09T01:38:33.232840+00:00 | 999 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nSimulation\n\n# Complexity\n- Time complexity:\n $$O(n*tickets[k])$$ \n\n- Space complexity:\n $$O(n)$$\n\n# Code\n```\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& wingstopWings, int k) {\n \n using pii = pair<int, int>;\n // {tickets, og_index}\n queue<pii> q;\n int n = wingstopWings.size();\n for(int i = 0; i < n; i++) {\n q.push({wingstopWings[i], i});\n }\n int time = 0;\n while(!q.empty()) {\n auto [num_tickets, og_i] = q.front();\n q.pop();\n num_tickets--;\n time++;\n if(og_i == k && num_tickets == 0) {\n return time;\n }\n if(num_tickets > 0) {\n q.push({num_tickets, og_i});\n }\n }\n return time;\n }\n};\n``` | 4 | 0 | ['Simulation', 'C++'] | 5 |
time-needed-to-buy-tickets | 🔥🔥🔥 Easy Solution and Explanation 🔥🔥🔥 | Python3 | Array | Python | Queue | 2 Approaches | easy-solution-and-explanation-python3-ar-dnet | Intuition\nImagine you\'re in a line to buy concert tickets. Everyone has a different number of tickets they want to buy. You\'re interested in how long it will | KrishSukhani23 | NORMAL | 2024-04-09T00:22:32.360108+00:00 | 2024-04-09T00:22:32.360133+00:00 | 295 | false | # Intuition\nImagine you\'re in a line to buy concert tickets. Everyone has a different number of tickets they want to buy. You\'re interested in how long it will take for you, let\'s say you\'re in position k, to buy all your tickets. We can figure this out without waiting for everyone to buy their tickets one by one!\n\n\n# Approach\nWe take a smart shortcut:\n\n- If someone in front of you wants fewer tickets than you, they\'ll finish before you, so we count all their tickets.\n- If they want more tickets than you, we only count as many tickets as you need because you\'ll be done before they buy all their tickets.\n- For people behind you, it\'s almost the same, but if they want more tickets than you, we count one less because you\'ll finish before their last ticket purchase.\n\n# Complexity\n- Time complexity:\nO(n)\n- Space complexity:\nO(1)\n\n\n# Approach 1 (Optimized and Short)\n```\nclass Solution:\n def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:\n timeElapsed = 0\n \n # Iterate through each person in the queue.\n for i in range(len(tickets)):\n if i <= k:\n # For people before and including k, add the minimum of their ticket count or the k-th person\'s ticket count.\n timeElapsed += min(tickets[i], tickets[k])\n else:\n # For people after k, add the minimum of their ticket count or one less than the k-th person\'s ticket count,\n # since the k-th person will finish before this person\'s last ticket purchase if they have more tickets.\n timeElapsed += min(tickets[i], tickets[k] - 1)\n \n return timeElapsed\n\n#Upvote Appreciated!\n\n```\n\nThis approach is like being a detective in a movie, where you figure out the whole mystery with just a keen observation, saving both time and effort!\n\n\n# Approach 2 (Brute Force)\n\nThis approach takes a straightforward path to solving the problem: it simulates the entire ticket-buying process step by step. The idea is simple: everyone in line buys tickets one by one, and if someone runs out of tickets to buy, they just stop. We keep a count of the total time passed with timeElapsed, which increases by 1 for each ticket bought by anyone in the line.\n\n\n\n```\nclass Solution:\n def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:\n # Initialize timeElapsed to track the total time spent.\n timeElapsed = 0\n\n # Continue the process until the k-th person has bought all their tickets.\n while tickets[k] != 0:\n # Iterate through each person in the queue.\n for i in range(len(tickets)):\n # If the current person has tickets left to buy.\n if tickets[i] != 0:\n # The person buys a ticket, reducing the ticket count by 1.\n tickets[i] -= 1\n # Increment the timeElapsed since a ticket purchase takes 1 second.\n timeElapsed += 1\n \n # If the k-th person has bought all their tickets, return the timeElapsed.\n if i == k and tickets[i] == 0:\n return timeElapsed\n\n#Upvote Appreciated!\n\n```\n\n\n\n | 4 | 0 | ['Array', 'Queue', 'Simulation', 'Python', 'Python3'] | 1 |
time-needed-to-buy-tickets | Two simple solutions in Python3 || Queue DS || Inifinite looping | two-simple-solutions-in-python3-queue-ds-dvny | Intuition\nFollowing to the description of the problem, the task goal is to calculate min amount of time, that K- buyer needs to spend in order to buy tickets.\ | subscriber6436 | NORMAL | 2023-08-30T15:38:14.732000+00:00 | 2024-04-09T07:48:26.685564+00:00 | 519 | false | # Intuition\nFollowing to the description of the problem, the task goal is to calculate **min amount of time**, that `K`- buyer needs to spend in order to buy tickets.\n\nSomehow we need to iterate over all buyers, reduce the current amount of tickets they\'re bying at the moment, shift the current buyer to **the END of a** `queue` and repeat the process.\n\n---\n\n- **Queue DS**\n\nIf you haven\'t already familiar with [Queue DS](https://en.wikipedia.org/wiki/Queue_(abstract_data_type)), just follow the link to know more!\n\n1. change `tickets` variable by initializing a `deque` and **map** `i` and `v` for current buyer, \n2. initialize `ans` variable and `while` loop, that\'ll iterate **infinitely**\n3. pop from `tickets` current buyer\n4. increment total amount `ans` \n5. check, if the current buyer has bought all of the tickets, and return `ans`\n6. otherwise, if he needs to buy **more** tickets, return him to the `tickets` queue\n\n```python\nclass Solution:\n def timeRequiredToBuy(self, tickets: list[int], k: int) -> int:\n tickets = deque([[i, v] for i, v in enumerate(tickets)])\n ans = 0\n\n while True:\n i, v = tickets.popleft()\n ans += 1\n\n if i == k and v - 1 == 0:\n return ans\n \n if v > 1:\n tickets.append([i, v - 1])\n```\n# Complexity\n- Time complexity: **O(n)**, because of iterating infinitely over all `tickets` buyers\n\n- Space complexity: **O(n)**, to map indexes and values for `tickets`\n\n---\n\n- **Inifinite looping**\nThe approach is the same, but we **mutate** the initial values of `tickets`.\n\n# Code\n```\nclass Solution:\n def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:\n i = ans = 0\n\n while True:\n if tickets[i]:\n tickets[i] -= 1\n ans += 1\n if not tickets[i] and k == i:\n return ans\n \n i = (i + 1) % len(tickets)\n\n```\n\n# Complexity\n- Time complexity: **O(n)**, because of iterating infinitely over all `tickets` buyers\n\n- Space complexity: **O(1)**, because we don\'t use extra space.\n | 4 | 0 | ['Array', 'Queue', 'Python3'] | 0 |
time-needed-to-buy-tickets | Easy solution with explanation | easy-solution-with-explanation-by-ods967-0jkf | If you like it, please upvote\n\n# Code\n\n/**\n * @param {number[]} tickets\n * @param {number} k\n * @return {number}\n */\nvar timeRequiredToBuy = function(t | ods967 | NORMAL | 2023-02-08T05:40:12.608631+00:00 | 2023-02-08T05:40:12.608668+00:00 | 843 | false | If you like it, please upvote\n\n# Code\n```\n/**\n * @param {number[]} tickets\n * @param {number} k\n * @return {number}\n */\nvar timeRequiredToBuy = function(tickets, k) {\n // current index\n let i = 0;\n // number of steps\n let steps = 0;\n\n // while tickets[k] > 0\n while (tickets[k]) {\n // we do not need to reset i because it is easier to calculate index in the array\n const index = i % tickets.length;\n if (tickets[index]) {\n // if element is not 0 then decrement the value and increment the number of steps\n tickets[index]--;\n steps++;\n }\n // every time move to next element\n i++;\n }\n\n return steps;\n};\n``` | 4 | 0 | ['JavaScript'] | 0 |
time-needed-to-buy-tickets | Java | Simple code | 100% faster | java-simple-code-100-faster-by-hazemkhal-7f73 | \nclass Solution {\n public int timeRequiredToBuy(int[] tickets, int k) {\n int seconds = 0;\n for(int i = 0; i < tickets.length; i++){\n | HazemKhaled | NORMAL | 2022-09-21T18:35:42.096525+00:00 | 2022-09-21T18:35:42.096563+00:00 | 1,344 | false | ```\nclass Solution {\n public int timeRequiredToBuy(int[] tickets, int k) {\n int seconds = 0;\n for(int i = 0; i < tickets.length; i++){\n if(tickets[i] < tickets[k]) seconds += tickets[i]; // only add the time needed to buy his tickets\n else{\n if(i <= k) seconds += tickets[k]; \n else seconds += tickets[k] - 1; \n }\n }\n return seconds;\n }\n}\n``` | 4 | 0 | ['Java'] | 2 |
time-needed-to-buy-tickets | One Pass C++ || Easy to Understand ⭐⭐ | one-pass-c-easy-to-understand-by-shailes-150i | People infront of our target person will get all their tickets before our target man if they want tickets less than or equal to him. If they want more tickets t | Shailesh0302 | NORMAL | 2022-08-28T12:26:18.765281+00:00 | 2022-08-28T12:26:18.765325+00:00 | 661 | false | People infront of our target person will get all their tickets before our target man if they want tickets less than or equal to him. If they want more tickets than him they will only get tickets equal to him till target man gets all his tickets.\n\nFor people behind target man, they will get all tickets if they want tickets strictly less than him. If they want more than him, they will get one less than tickets target man wants till he gets all his tickets.\n\'\'\'\n \n class Solution {\n public:\n int timeRequiredToBuy(vector<int>& tickets, int k) {\n int n=tickets.size();\n int time=tickets[k];\n for(int i=0;i<tickets.size();i++){\n //Elements infront of target\n //If they are smaller or equal to target value collect them whole \n //If they are greater collect target value\n if(i<k){\n if(tickets[i]<=tickets[k]){\n time+=tickets[i];\n }\n else{\n time+=tickets[k];\n }\n }\n //Elements behind target\n //If they are smaller than target value collect them whole \n //If they are greater collect (target-1) value\n else if(i>k){\n if(tickets[i]<tickets[k]){\n time+=tickets[i];\n }\n else{\n time+=(tickets[k]-1);\n }\n }\n }\n return time;\n }\n};\n\t\t\t \n\t\t\t \n\'\'\' | 4 | 0 | ['C'] | 0 |
time-needed-to-buy-tickets | 0 ms java solution | 0-ms-java-solution-by-arpitpatawat-pmdd | suppose the given array is [2,3,7,5,1,2,7] and k is pointing to element = 5.\nwe need to find that each element is reduced how many times till we get 0 at the i | arpitpatawat | NORMAL | 2022-06-03T03:33:21.078541+00:00 | 2022-06-13T02:36:21.870748+00:00 | 227 | false | suppose the given array is [2,3,7,5,1,2,7] and k is pointing to element = 5.\nwe need to find that each element is reduced how many times till we get 0 at the index 3. The element before 5 will be reduced by = **minimum of (value of ith element, value of kth element)**\n the element before 5 are [2,3,7,5] and these will be reduced to [0,0,2,0] when the kth guy get ticket \n \n\n\nnow element after 5 are [1,2,7] here we have a case, the element 1,2 will be completly reduce to 0 but the element greater than k will reduce to 1 lesser than the kth element (shown below ) because the kth element guy got the ticket and we don\'t need to worry about the leftover.\n\n\n\n**please upvote my solution if u like it \u2764\uFE0F** \n```\nclass Solution {\n public int timeRequiredToBuy(int[] tickets, int k) {\n int count = 0;\n for(int i = 0 ; i < tickets.length; ++i){\n if(i <=k){\n count += Math.min(tickets[i], tickets[k]);\n }\n else\n count += Math.min(tickets[i], tickets[k] - 1);\n }\n return count;\n }\n}\n``` | 4 | 0 | ['Java'] | 0 |
time-needed-to-buy-tickets | Simple C++ solution || 0ms | simple-c-solution-0ms-by-darkhorse20-ugv7 | This is easy to understand solution..\nDo give a like!.\n\n\n\n int timeRequiredToBuy(vector& tickets, int k) {\n int n=tickets.size(),ans=0;\n \n f | DarkHorse20 | NORMAL | 2021-12-23T10:45:18.182096+00:00 | 2021-12-23T10:45:18.182134+00:00 | 129 | false | This is easy to understand solution..\nDo give a like!.\n\n\n\n int timeRequiredToBuy(vector<int>& tickets, int k) {\n int n=tickets.size(),ans=0;\n \n for(int i=0;i<n;i++)\n {\n if(i>k)\n ans+=min(tickets[i],tickets[k]-1);\n else if(i<k)\n ans+=min(tickets[i],tickets[k]);\n else\n ans+=tickets[k];\n \n }\n \n return ans;\n }\n}; | 4 | 0 | [] | 0 |
time-needed-to-buy-tickets | Simulation And Optimisation | Java | C++ | simulation-and-optimisation-java-c-by-la-pr5o | Intuition, approach, and complexity dicussed in video solution in detail\nhttps://youtu.be/UJ8fLOavT7k\n# Code\nApproach 1: Java\n\njava\nclass Solution {\n | Lazy_Potato_ | NORMAL | 2024-04-09T15:28:11.444736+00:00 | 2024-04-09T15:28:11.444765+00:00 | 161 | false | # Intuition, approach, and complexity dicussed in video solution in detail\nhttps://youtu.be/UJ8fLOavT7k\n# Code\nApproach 1: Java\n\n```java\nclass Solution {\n public int timeRequiredToBuy(int[] tickets, int k) {\n int size = tickets.length;\n int timePassed = 0, indx = 0;\n while (tickets[k] > 0) {\n if (tickets[indx] > 0) {\n tickets[indx]--;\n timePassed++;\n }\n indx = (indx + 1) % size;\n }\n return timePassed;\n }\n}\n```\n\nApproach 1: C++\n\n```cpp\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& tickets, int k) {\n int size = tickets.size();\n int timePassed = 0, indx = 0;\n while (tickets[k] > 0) {\n if (tickets[indx] > 0) {\n tickets[indx]--;\n timePassed++;\n }\n indx = (indx + 1) % size;\n }\n return timePassed;\n }\n};\n```\n\nApproach 2: Java\n\n```java\nclass Solution {\n public int timeRequiredToBuy(int[] tickets, int k) {\n int size = tickets.length;\n int timePassed = 0;\n for (int indx = 0; indx < size; indx++) {\n int timeContri = 0;\n if (indx <= k) {\n timeContri = Math.min(tickets[indx], tickets[k]);\n } else {\n timeContri = Math.min(tickets[indx], tickets[k] - 1);\n }\n timePassed += timeContri;\n }\n return timePassed;\n }\n}\n```\n\nApproach 2: C++\n\n```cpp\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& tickets, int k) {\n int size = tickets.size();\n int timePassed = 0;\n for (int indx = 0; indx < size; indx++) {\n int timeContri = 0;\n if (indx <= k) {\n timeContri = min(tickets[indx], tickets[k]);\n } else {\n timeContri = min(tickets[indx], tickets[k] - 1);\n }\n timePassed += timeContri;\n }\n return timePassed;\n }\n};\n```\n\nFeel free to copy and paste these headings into your text editor. | 3 | 0 | ['Array', 'Queue', 'Simulation', 'C++', 'Java'] | 1 |
time-needed-to-buy-tickets | Just easy code | just-easy-code-by-nbekweb-raax | \n\n# Code\n\n/**\n * @param {number[]} tickets\n * @param {number} k\n * @return {number}\n */\nvar timeRequiredToBuy = function(t, k) {\n let s=0,i=0\n | Nbekweb | NORMAL | 2024-04-09T14:54:49.045730+00:00 | 2024-04-09T14:54:49.045753+00:00 | 41 | false | \n\n# Code\n```\n/**\n * @param {number[]} tickets\n * @param {number} k\n * @return {number}\n */\nvar timeRequiredToBuy = function(t, k) {\n let s=0,i=0\n while(t[k]!==0){\n if(t[i]>0){\n s++\n t[i]--\n if(t[k]==0) return s\n }\n if(i==t.length-1) i=0\n else i++\n }\n};\n``` | 3 | 0 | ['JavaScript'] | 3 |
time-needed-to-buy-tickets | Beats 100%, USING RECURSION | beats-100-using-recursion-by-sanchitjado-hqmx | Intuition\nDecrease the tickets counting in array by 1 simultaneously calculate time till the kth index element in array becomes 0.\n\n# Approach\nstep 1- take | sanchitjadon | NORMAL | 2024-04-09T13:19:39.298834+00:00 | 2024-04-09T13:19:39.298859+00:00 | 50 | false | # Intuition\nDecrease the tickets counting in array by 1 simultaneously calculate time till the kth index element in array becomes 0.\n\n# Approach\nstep 1- take time variable as 0.\nstap 2- traverse on tickets array simultaneously\n 1. decrease each elements by 1 and increase time by 1.\n 2. if the kth element becomes 0 then return time.\n 3. use recursive calls of step 2(for multiple traversals) until kth element becomes 0 and also calculate time .\n 4. base condition if tickets[k]==0 return 0(time).\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 Solution {\n public int timeRequiredToBuy(int[] tickets, int k) {\n if(tickets[k]==0){\n return 0;\n }\n int time=0;\n for(int i=0;i<tickets.length;i++){\n if(tickets[k]==0){\n return time;\n }\n if(tickets[i]==0){\n continue;\n }\n if(tickets[i]!=0){\n tickets[i]--;\n time++;\n }\n }\n time+=timeRequiredToBuy(tickets,k);\n return time;\n }\n}\n``` | 3 | 0 | ['Java'] | 2 |
time-needed-to-buy-tickets | C++ and Python3 || Greedy || Simple and Optimal || 0 ms || Beats 100% | c-and-python3-greedy-simple-and-optimal-zxwqx | \n# Code\nC++ []\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& tickets, int k) {\n int ans = 0;\n for (int i = 0; i < tickets | meurudesu | NORMAL | 2024-04-09T11:01:28.970513+00:00 | 2024-04-09T11:01:28.970549+00:00 | 27 | false | > \n# Code\n```C++ []\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& tickets, int k) {\n int ans = 0;\n for (int i = 0; i < tickets.size(); i++) {\n if (i > k) ans += min(tickets[i], tickets[k] - 1);\n else ans += min(tickets[i], tickets[k]);\n }\n return ans;\n }\n};\n```\n```Python3 []\nclass Solution:\n def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:\n ans = 0\n for i in range(len(tickets)):\n if i > k:\n ans += min(tickets[i], tickets[k] - 1)\n else:\n ans += min(tickets[i], tickets[k])\n return ans\n``` | 3 | 0 | ['Array', 'Greedy', 'C++', 'Python3'] | 0 |
time-needed-to-buy-tickets | 100% Beats || Easy C++ || Queue || O(N) | 100-beats-easy-c-queue-on-by-connect2abd-oh4v | Intuition\n1st push all the element into queue if kth element is greater than 1.\npush the element if after decrement it is still greate than 0.\n\n# Approach\n | connect2abdulaziz | NORMAL | 2024-04-09T10:53:36.070776+00:00 | 2024-04-09T10:53:36.070810+00:00 | 121 | false | # Intuition\n1st push all the element into queue if kth element is greater than 1.\npush the element if after decrement it is still greate than 0.\n\n# Approach\ninitilly change the sign of the kth element so that you recognize it in future. than simple queue approach.\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N)\n\n# Code\n```\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& tickets, int k) {\n int i = 0, n = tickets.size(), sec = 0;\n queue<int> que;\n tickets[k] = -tickets[k];\n while(tickets[k] && i < n){\n if(i == k) que.push(++tickets[i]); \n else if(--tickets[i]) que.push(tickets[i]);\n i++; sec++;\n }\n while(!que.empty() && tickets[k]){\n auto top = que.front();\n sec++; que.pop();\n if(top - 1 == 0 ) continue;\n top < 0 ? que.push(++tickets[k]): que.push(--top);\n }\n return sec;\n }\n};\n``` | 3 | 0 | ['Queue', 'C++'] | 1 |
time-needed-to-buy-tickets | ✅ One Line Solution | one-line-solution-by-mikposp-i3qc | Time complexity: O(n). Space complexity: O(1).\n\nclass Solution:\n def timeRequiredToBuy(self, t: List[int], k: int) -> int:\n return sum(min(v,t[k]- | MikPosp | NORMAL | 2024-04-09T09:24:17.242922+00:00 | 2024-04-09T09:24:17.242947+00:00 | 570 | false | Time complexity: $$O(n)$$. Space complexity: $$O(1)$$.\n```\nclass Solution:\n def timeRequiredToBuy(self, t: List[int], k: int) -> int:\n return sum(min(v,t[k]-(i>k)) for i,v in enumerate(t))\n``` | 3 | 0 | ['Array', 'Python', 'Python3'] | 1 |
time-needed-to-buy-tickets | Easy Solution || Well-Explained with Example || Intuitive || Mathematical-Approach || Beats 100% | easy-solution-well-explained-with-exampl-uruf | Intuition\nWe don\'t need to actually subtract the values one-by-one.\nThink of it as a mathematical question and try to find a formula which fits this problem. | tmohit_04 | NORMAL | 2024-04-09T07:18:44.188265+00:00 | 2024-04-09T07:18:44.188302+00:00 | 61 | false | # Intuition\nWe don\'t need to actually subtract the values one-by-one.\nThink of it as a mathematical question and try to find a formula which fits this problem. A dry run will help you the best.\nLet\'s assume that k is somewhere in the middle of array.\ne.g - tickets[ ] = [2,3,6,4,3,6] and k=3\nNow, tickets[k] = 4\nWe will break this in two cases:\n\nCase-I:```i<=k```\nIf the current value, ```tickets[i]```, is less than target value, we will end the whole value by subtracting before ```tickets[k]``` reaches zero.\nFor i=0, ans += tickets[i];\nFor i=1, ans += tickets[i];\nIf it is greater, we will at least take tickets[k] \nFor i=2, ans += tickets[k];\nFor i=3, ans += tickets[k];\n\nCase-II: ```i>k```\nAgain, if current value is less, we will reduce it to 0 before ```tickets[k]``` reaches 0\nso ans += tickets[i]\nNow, here is the CATCH:\nIf current value is greater, we will take 1 second less than usual,\nBecause before we reach current value in the kth iteration, our ```tickets[k]``` would have already become zero. So, we will only take ```tickets[i]``` till (k-1)th iteration\nTherefore, ans += tickets[k]-1;\n\n# Approach\nApproach is as simple as it should be\n1. Initialise your answer variable, ```int ans=0```\n2. Now run a for-loop till tickets.size() \n3. ```if(i<=k) ans += min(tickets[i], tickets[k])```\n4. ```if(i>k) ans += min(tickets[i], ticekts[k]-1)```\n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(1)\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& tickets, int k) {\n int ans=0;\n for(int i=0;i<tickets.size();i++){\n if(i<=k) ans += min(tickets[i] , tickets[k]);\n if(i>k) ans += min(tickets[i] , tickets[k]-1);\n }\n return ans;\n }\n};\n```\n```Python []\nclass Solution:\n def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:\n ans = 0\n for i in range(len(tickets)):\n if i <= k:\n ans += min(tickets[i], tickets[k])\n if i > k:\n ans += min(tickets[i], tickets[k] - 1)\n return ans\n```\n```Java []\nclass Solution {\n public int timeRequiredToBuy(int[] tickets, int k) {\n int ans = 0;\n for (int i = 0; i < tickets.length; i++) {\n if (i <= k) {\n ans += Math.min(tickets[i], tickets[k]);\n }\n if (i > k) {\n ans += Math.min(tickets[i], tickets[k]-1);\n }\n }\n return ans;\n }\n}\n```\n\nThis is my first Solution post. Hope it helped you.\nJust in case if it did, kindly upvote. \uD83D\uDE0A\nHave a nice day mate! | 3 | 0 | ['Math', 'Python', 'C++', 'Java'] | 2 |
time-needed-to-buy-tickets | 🚀 Simple Python Solution | Pointer Approach ✅ | simple-python-solution-pointer-approach-itrc6 | Approach\n Describe your approach to solving the problem. \n- set result count to 0\n- iterate to tickets if currunt is not 0 then increase the res and remove t | jeelgajera | NORMAL | 2024-04-09T06:59:17.010167+00:00 | 2024-04-09T06:59:17.010200+00:00 | 114 | false | # Approach\n<!-- Describe your approach to solving the problem. -->\n- set result count to 0\n- iterate to `tickets` if currunt is not 0 then increase the `res` and remove the 1 ticket from `tickets[i]` else skip the person\n- if the `tickets[k]` is equal to 0 than break the loop and return the `res`\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$, to iterate the persone queue \n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$, store the counts of the tickets are boughts, \n\n# Code\n```\nclass Solution:\n def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:\n res = 0\n i,n = 0, len(tickets)\n while True:\n if i >= n:\n i = 0\n\n if tickets[k] == 0:\n break\n\n if tickets[i] != 0:\n res += 1\n tickets[i] -= 1\n \n i += 1\n \n return res\n``` | 3 | 0 | ['Python', 'Python3'] | 0 |
time-needed-to-buy-tickets | Beats 100% 🔥 || C++ Solution with clean explanation | beats-100-c-solution-with-clean-explanat-qa3p | Intuition\n Describe your first thoughts on how to solve this problem. \n- The problem essentially boils down to simulating the process of people buying tickets | tourism | NORMAL | 2024-04-09T05:31:43.957958+00:00 | 2024-04-09T05:31:43.957988+00:00 | 50 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- The problem essentially boils down to simulating the process of people buying tickets in a queue. We need to find the time taken for a specific person, indexed by k, to finish buying their tickets.\n\n- The key insight is that if a person is behind the person at position k, they will have to wait for the person at position k to finish buying their tickets before they can start buying theirs. Additionally, if a person is ahead of the person at position k, they will continue buying tickets until they reach the same number of tickets as the person at position k, and then they will buy one less ticket in each subsequent cycle.\n\n- With this insight, we can iterate through the line of people, keeping track of the time taken for each person to buy tickets based on their position relative to the person at position k. Finally, we sum up the time taken by each person to find the total time taken for the person at position k to finish buying tickets.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- To solve this problem efficiently, we can simulate the process of people buying tickets. We iterate through the line of people, keeping track of the number of tickets each person wants to buy and the time taken for each person to finish buying tickets.\n\n- We start by initializing a variable ans to 0, which will represent the total time taken. We also initialize a variable t to store the number of tickets the person at position k wants to buy. Then, we iterate through each person in the line:\n\n - If the current person is before or at position k, we add the minimum of their ticket requirement and t to ans, as they have to buy tickets up to the point where the person at position k finishes.\n\n - If the current person is after position k, we add the minimum of their ticket requirement and t-1 to ans, as they have to buy tickets up to the point where the person at position k finishes, and the person at position k buys one ticket less than their requirement.\n\n- Finally, we return the value of ans, which represents the time taken for the person at position k to finish buying tickets.\n\n# Complexity\n**Time complexity:**\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n- $$O(n)$$, where n is the number of people in the line. We iterate through the line of people once.\n\n**Space complexity:**\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n- $$O(1)$$ the program uses only a constant amount of extra space.\n\n\n\n\n# Code\n```\n//Upvote karle bhai\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& tickets, int k) {\n int ans=0,t=tickets[k],n=tickets.size();\n for(int i=0;i<n;i++){\n if(i<=k){\n ans+=min(tickets[i],t);\n }\n else{\n ans+=min(tickets[i],t-1);\n }\n }\n return ans;\n }\n};\n``` | 3 | 0 | ['Array', 'Queue', 'Simulation', 'C++'] | 0 |
time-needed-to-buy-tickets | Simple code without using Builtin functions. | simple-code-without-using-builtin-functi-4ss5 | Complexity\n- Time complexity:\nIf there are n people in the queue and the maximum number of tickets any person has is t, the time complexity is O(n * t).\n\n- | shubhamdevpro | NORMAL | 2024-04-09T05:01:38.045991+00:00 | 2024-04-09T05:01:38.046016+00:00 | 16 | false | # Complexity\n- Time complexity:\nIf there are n people in the queue and the maximum number of tickets any person has is t, the time complexity is $$O(n * t)$$.\n\n- Space complexity:\nSince the dominant factor in memory usage is the tickets array, the overall space complexity of the code is $$O(n)$$, where \'n\' is the size of the input array. This is considered linear space complexity, meaning the space usage grows proportionally with the input size.\n\n# Code\n```\nclass Solution {\n public int timeRequiredToBuy(int[] tickets, int k) {\n int count = 0 ;\n while(tickets[k]!=0 ){\n for(int i=0;i<tickets.length;i++){\n if(tickets[i]>0 && tickets[k]>0){\n tickets[i]-=1;\n count++;\n }\n }\n }\n return count ;\n }\n}\n``` | 3 | 0 | ['Java'] | 3 |
time-needed-to-buy-tickets | Single Pass | Python | single-pass-python-by-pragya_2305-q7s9 | Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(1)\n\n# Code\n\nclass Solution:\n def timeRequiredToBuy(self, tickets: List[int], k: int) -> int | pragya_2305 | NORMAL | 2024-04-09T03:08:26.353749+00:00 | 2024-04-09T03:08:26.353777+00:00 | 243 | false | # Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(1)\n\n# Code\n```\nclass Solution:\n def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:\n ans = 0\n for i in range(k+1):\n ans+=min(tickets[i],tickets[k])\n\n for i in range(k+1,len(tickets)):\n ans+=min(tickets[i],tickets[k]-1)\n\n return ans\n\n \n``` | 3 | 0 | ['Python3'] | 1 |
time-needed-to-buy-tickets | Easiest C++ / Python3 / Java / C / Python / C# -- Solutions beats 100% One Pass Solutions. | easiest-c-python3-java-c-python-c-soluti-pblq | Intuition\n\n\n\n\n\n\nC++ []\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& tickets, int k) {\n int cnt = 0, cn = tickets[k];\n | Edwards310 | NORMAL | 2024-04-09T02:59:07.642824+00:00 | 2024-04-09T02:59:07.642852+00:00 | 19 | false | # Intuition\n\n\n\n\n\n\n```C++ []\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& tickets, int k) {\n int cnt = 0, cn = tickets[k];\n for (int i = 0; i < tickets.size(); i++)\n cnt += min(cn - (i > k), tickets[i]);\n return cnt;\n }\n};\n```\n```python3 []\nclass Solution:\n def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:\n cnt = 0\n while tickets[k] > 0:\n for u in range(len(tickets)):\n if tickets[u] != 0:\n tickets[u] -= 1\n cnt += 1\n if u == k and tickets[k] == 0:\n return cnt\n\n return cnt\n```\n```C# []\npublic class Solution {\n public int TimeRequiredToBuy(int[] tickets, int k) {\n int time = 0;\n for (int i = 0; i < tickets.Length; i++){\n if (i <= k)\n time += Math.Min(tickets[i], tickets[k]);\n else\n time += Math.Min(tickets[i], tickets[k] - 1);\n }\n return time;\n }\n}\n```\n```java []\nclass Solution {\n public int timeRequiredToBuy(int[] tickets, int k) {\n int res = 0;\n while (tickets[k] != 0) {\n for (int i = 0; i < tickets.length; i++) {\n if (tickets[i] > 0 && tickets[k] != 0) {\n tickets[i]--;\n res++;\n }\n }\n }\n return res;\n }\n}\n```\n```python []\nclass Solution(object):\n def timeRequiredToBuy(self, tickets, k):\n """\n :type tickets: List[int]\n :type k: int\n :rtype: int\n """\n time = 0\n\n for x in range(len(tickets)):\n if tickets[x] >= tickets[k]:\n time += tickets[k]\n elif tickets[x] < tickets[k]:\n time += tickets[x]\n\n if x > k and tickets[x] >= tickets[k]:\n time -= 1\n\n return time\n```\n```C []\nint timeRequiredToBuy(int* tickets, int ticketsSize, int k) {\n int cnt = 0, cn = tickets[k];\n for (int i = 0; i < ticketsSize; i++)\n cnt += fmin(cn - (i > k), tickets[i]);\n return cnt;\n}\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(1)\n# Code\n```\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& tickets, int k) {\n int cnt = 0, cn = tickets[k];\n for (int i = 0; i < tickets.size(); i++)\n cnt += min(cn - (i > k), tickets[i]);\n return cnt;\n }\n};\n```\n# Please upvote if it\'s useful\n\n | 3 | 0 | ['Array', 'Queue', 'C', 'Simulation', 'Python', 'C++', 'Java', 'Python3'] | 0 |
time-needed-to-buy-tickets | 100% Runtime ✅💯, O(n) Time Complexity, O(1) Space Complexity ⚡️🔥 | 100-runtime-on-time-complexity-o1-space-b66e4 | Intuition\n Describe your first thoughts on how to solve this problem. \nThere will be as many rounds as the number of tickets kth person wants. The last round | ayushku22 | NORMAL | 2024-04-09T01:25:27.656892+00:00 | 2024-04-09T01:25:27.656921+00:00 | 138 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThere will be as many rounds as the number of tickets kth person wants. The last round will terminate at the kth person and thus the people after the kth one are visited one lesser time. \nThe Person who wants tickets lesser than that of kth person will just be in the rounds as many times he wants the tickets. Others will be as many times kth element will want. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nLet the number of tickets kth person wants be T.\nFor the people before kth person, if he wants more than T tickets, he gets T tickets until kth person gets T tickets. And if he wants less than T tickets, his want will be fulfilled earlier and he will participate the number of times as the number of tickets he wants.\n\nFor the people after kth person, it all will be applied with T-1 tickets as one lesser round will be carried out on them.\n\n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: As we have just introduced ans. So, SC is O(1)\n\n# Code\n```\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& tickets, int k) {\n int ans = 0;\n for(int i=0; i<tickets.size(); i++){\n if(i<=k) ans += min(tickets[i], tickets[k]);\n else ans += min(tickets[i], tickets[k]-1);\n }\n return ans;\n }\n};\n``` | 3 | 0 | ['C++'] | 2 |
time-needed-to-buy-tickets | Clean golang solution | clean-golang-solution-by-klakovskiy-o5ox | Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(1)\n Add your space complexity here, e.g. O(n) \n\n# Co | klakovskiy | NORMAL | 2024-02-13T06:41:08.640869+00:00 | 2024-02-13T06:41:08.640896+00:00 | 155 | false | # Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nfunc timeRequiredToBuy(tickets []int, k int) int {\n result := 0\n c := tickets[k]\n for i, n := range tickets {\n if i == k {\n result += c\n } else if i < k {\n result += min(c, n)\n } else {\n result += min(c-1, n)\n }\n }\n\n return result\n}\n``` | 3 | 0 | ['Go'] | 0 |
time-needed-to-buy-tickets | Python3 queue | python3-queue-by-tkr_6-qpaj | \n\n# Code\n\nclass Solution:\n def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:\n \n n=len(tickets)\n q=deque([i for i i | TKR_6 | NORMAL | 2023-05-04T17:12:53.445765+00:00 | 2023-05-04T17:12:53.445801+00:00 | 765 | false | \n\n# Code\n```\nclass Solution:\n def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:\n \n n=len(tickets)\n q=deque([i for i in range(n)])\n \n time=0\n \n while q:\n for i in range(len(q)):\n\n node=q.popleft()\n tickets[node]-=1\n if tickets[node]>=1:\n q.append(node)\n \n time+=1\n if tickets[k]==0:\n return time\n \n \n \n``` | 3 | 0 | ['Queue', 'Python', 'Python3'] | 0 |
time-needed-to-buy-tickets | [CPP] || Queue || Easiest Solution | cpp-queue-easiest-solution-by-comauro751-v7j3 | \n# Code\n\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& tickets, int k) {\n int time=0;\n queue<int> q;\n int n=ticke | comauro7511 | NORMAL | 2022-12-21T18:08:12.354139+00:00 | 2022-12-21T18:08:12.354183+00:00 | 934 | false | \n# Code\n```\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& tickets, int k) {\n int time=0;\n queue<int> q;\n int n=tickets.size();\n for(int i=0;i<n;i++) q.push(i);\n\n while(true)\n {\n if(tickets[k]==0) break;\n int curr=q.front();\n time++;\n tickets[curr]--;\n q.pop();\n if(tickets[curr]!=0) \n {\n q.push(curr);\n }\n }\n return time;\n }\n};\n``` | 3 | 0 | ['Queue', 'C++'] | 1 |
time-needed-to-buy-tickets | ✅C++ || 2 ways || Bruteforce->Optimal | c-2-ways-bruteforce-optimal-by-abhinav_0-w5as | Method-1 [Brute Force]\n\n\n\nn==t.size()\nT->O(tickets[k] * n) && S->(1)\n\n\tclass Solution {\n\tpublic:\n\t\tint timeRequiredToBuy(vector& t, int k) {\n\t\t\ | abhinav_0107 | NORMAL | 2022-07-08T07:05:03.071468+00:00 | 2022-07-08T07:21:39.820243+00:00 | 693 | false | # Method-1 [Brute Force]\n\n\n\n**n==t.size()\nT->O(tickets[k] * n) && S->(1)**\n\n\tclass Solution {\n\tpublic:\n\t\tint timeRequiredToBuy(vector<int>& t, int k) {\n\t\t\tint time=0;\n\t\t\twhile(1){\n\t\t\t\tfor(int i=0;i<t.size();i++){\n\t\t\t\t\tif(t[i]>0){\n\t\t\t\t\t\tt[i]--;\n\t\t\t\t\t\ttime++;\n\t\t\t\t\t\tif(t[k]==0)return time;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn -1;\n\t\t}\n\t};\n\t\n\t\n# Method-2 [Optimal solution]\t\n\t\n\n\n**In one pass!\nT->O(n) && S->O(1)**\n\n\tclass Solution {\n\tpublic:\n\t\tint timeRequiredToBuy(vector<int>& t, int k) {\n\t\t\tint time=0;\n\t\t\tfor(int i=0;i<t.size();i++){\n\t\t\t\tif(t[i]<t[k])time+=t[i];\n\t\t\t\telse time+=t[k];\n\t\t\t\tif(i>k && t[i]>=t[k])time--;\n\t\t\t}\n\t\t\treturn time;\n\t\t}\n\t}; | 3 | 0 | ['C', 'C++'] | 0 |
time-needed-to-buy-tickets | C++ || queue || cycle | c-queue-cycle-by-aaboiko-ff8k | \nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& tickets, int k) {\n queue<int> q;\n for(int i : tickets) q.push(i);\n i | aaboiko | NORMAL | 2022-06-13T12:51:47.632493+00:00 | 2022-06-13T12:51:47.632525+00:00 | 472 | false | ```\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& tickets, int k) {\n queue<int> q;\n for(int i : tickets) q.push(i);\n int res = 0;\n int p = k;\n \n while(true){\n res++;\n if(q.front()-- > 1) q.push(q.front());\n else if(p == 0) break;\n q.pop();\n if(--p < 0) p = q.size() - 1;\n }\n return res;\n }\n};\n``` | 3 | 0 | ['Queue', 'C'] | 0 |
time-needed-to-buy-tickets | [Python] Simple, readable, easy to understand solution (beats 69%) | python-simple-readable-easy-to-understan-21k2 | The approach is as follows:\n1. Keep track of the number of seconds (this is what will be returned)\n2. As long as the person at k index still has tickets to bu | FedM | NORMAL | 2022-05-28T18:53:37.149028+00:00 | 2022-05-28T18:53:37.149075+00:00 | 686 | false | The approach is as follows:\n1. Keep track of the number of seconds (this is what will be returned)\n2. As long as the person at k index still has tickets to buy:\n\t* Sell tickets to everyone in the line who still has tickets to buy\n\t* Add a second for each ticket sold\n3. Return how many seconds were needed to sell the person at k index all of their tickets\n```\nclass Solution:\n def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:\n num_seconds = 0\n \n while tickets[k] > 0:\n for i in range(len(tickets)):\n if tickets[i] > 0 and tickets[k] > 0:\n tickets[i] -= 1\n num_seconds += 1\n\n return num_seconds\n```\n\n | 3 | 0 | ['Python', 'Python3'] | 2 |
time-needed-to-buy-tickets | C++ || EASY || O(n) | c-easy-on-by-nikhilgupta25-d8tk | Upvote If you like the solution\n\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& tickets, int k) {\n int num=tickets[k],tt=0;\n | NikhilGupta25 | NORMAL | 2022-04-17T20:03:48.716197+00:00 | 2022-04-17T20:03:48.716240+00:00 | 196 | false | ***Upvote If you like the solution***\n```\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& tickets, int k) {\n int num=tickets[k],tt=0;\n for(int i=0;i<tickets.size();i++){\n if(num>tickets[i]){\n tt+=tickets[i];\n }\n else if(num<=tickets[i]){\n tt+=num;\n }\n }\n for(int i=k+1;i<tickets.size();i++){\n if(tickets[i]>=num){\n tt-=1;\n }\n }\n return tt;\n }\n};\n``` | 3 | 0 | ['C', 'C++'] | 0 |
time-needed-to-buy-tickets | Python O(n) time complexity - faster than 97% | python-on-time-complexity-faster-than-97-xrut | \nclass Solution(object):\n def timeRequiredToBuy(self, tickets, k):\n ans = 0\n \n\t\t# people at the front will always get 1 ticket first\n\t | doremikaelatido | NORMAL | 2021-12-05T10:49:50.234590+00:00 | 2021-12-05T10:49:50.234628+00:00 | 456 | false | ```\nclass Solution(object):\n def timeRequiredToBuy(self, tickets, k):\n ans = 0\n \n\t\t# people at the front will always get 1 ticket first\n\t\t# get minimum to know how many times a person will queue and buy before kth person\n for tix in range(k+1):\n ans += min(tickets[tix], tickets[k])\n\n\t\t# contrary to people at the front, \n\t\t# kth person will only go behind everyone *(people initially behind k)* for tickets[k]-1 times \n for tix in range(k+1, len(tickets)):\n ans += min(tickets[tix], tickets[k]-1)\n \n return ans\n``` | 3 | 0 | ['Python'] | 0 |
time-needed-to-buy-tickets | Python One Pass O(1) Solution | python-one-pass-o1-solution-by-harry_vit-24z6 | ```\nclass Solution:\n def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:\n \n x=tickets[k]\n answer=0\n for i in ra | Harry_VIT | NORMAL | 2021-11-30T19:19:40.384128+00:00 | 2021-11-30T19:19:40.384162+00:00 | 436 | false | ```\nclass Solution:\n def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:\n \n x=tickets[k]\n answer=0\n for i in range(0,k+1):\n answer+=min(x,tickets[i])\n \n for i in range(k+1,len(tickets)):\n answer+=min(x-1,tickets[i]) \n \n return answer | 3 | 1 | ['Python', 'Python3'] | 1 |
time-needed-to-buy-tickets | [Python3] 1-line | python3-1-line-by-ye15-2pv9 | Please check out this commit for solutions of weekly 267.\n\n\nclass Solution:\n def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:\n ret | ye15 | NORMAL | 2021-11-14T04:02:57.850659+00:00 | 2021-11-14T04:09:37.081718+00:00 | 347 | false | Please check out this [commit](https://github.com/gaosanyong/leetcode/commit/8d693371fa97ea3b0717d02448c77201b15e5d12) for solutions of weekly 267.\n\n```\nclass Solution:\n def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:\n return sum(min(tickets[k]-int(i>k), x) for i, x in enumerate(tickets))\n```\n\n```\nclass Solution:\n def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:\n ans = behind = 0 \n for i, x in enumerate(tickets): \n if i > k: behind = 1\n if x < tickets[k] - behind: ans += x\n else: ans += tickets[k] - behind\n return ans \n``` | 3 | 0 | ['Python3'] | 0 |
time-needed-to-buy-tickets | 2073 Time Needed to Buy Tickets CPP | 2073-time-needed-to-buy-tickets-cpp-by-t-b49k | Intuition\n Describe your first thoughts on how to solve this problem. \nThe time it takes to go around once with all the tickets is n. Until a ticket reaches z | tanmaybhujade | NORMAL | 2024-04-18T05:26:04.527052+00:00 | 2024-04-18T05:26:04.527091+00:00 | 5 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe time it takes to go around once with all the tickets is n. Until a ticket reaches zero, it will continue to be consumed by n.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nYou can consume tickets at once by calculating the minimum value and multiplying it by n. Since k may be 0, 1 can be left and processed as the minimum value.\n\nThen, you can repeat it until the kth becomes 0 while consuming one sequentially.\n\n# Complexity\n- Time complexity : O(n)\n- Space complexity : O(1) \n\n# Code\n```\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& tickets, int k) {\n int n = tickets.size();\n int ans = 0;\n while (1) {\n int min = *min_element(tickets.begin(), tickets.end());\n if (min != 0 and min+1 < tickets[k]) {\n for (int i = 0; i < n; ++i) {\n tickets[i] -= min;\n }\n ans += n * min;\n } else {\n break;\n }\n }\n int i = 0;\n while (tickets[k]) {\n if (tickets[i]) {\n tickets[i]--;\n ans++;\n }\n i = (i+1)%n;\n }\n return ans;\n }\n};\n``` | 2 | 0 | ['Array', 'Queue', 'Simulation', 'C++'] | 0 |
time-needed-to-buy-tickets | The worst case | the-worst-case-by-nurliaidin-del9 | 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 | Nurliaidin | NORMAL | 2024-04-10T09:39:30.119851+00:00 | 2024-04-10T09:39:30.119879+00:00 | 24 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n``` javascript []\n/**\n * @param {number[]} tickets\n * @param {number} k\n * @return {number}\n */\nvar timeRequiredToBuy = function(tickets, k) {\n let timer = 0;\n while(tickets[k] > 0) {\n timer++;\n tickets[0]--;\n \n if(k==0 && tickets[k]==0) break;\n\n let a = tickets.shift();\n if(a > 0) tickets.push(a);\n\n if(k==0) k = tickets.length-1;\n else k--;\n \n }\n return timer;\n};\n```\n``` cpp []\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& tickets, int k) {\n int timer = 0;\n while(tickets[k] > 0) {\n timer++;\n\n tickets[0]--;\n \n if(k==0 && tickets[k]==0) break;\n\n int a = tickets[0];\n tickets.erase(tickets.begin());\n if(a > 0) tickets.push_back(a);\n\n if(k==0) k = tickets.size()-1;\n else k--;\n }\n return timer;\n }\n};\n``` | 2 | 0 | ['C++', 'JavaScript'] | 0 |
time-needed-to-buy-tickets | Using queue | using-queue-by-starc_01-i2ip | Approach\n1.We have to return the time when the kth index of tickets are completely sold.\n2.So, from this it is clear that we should have the info about the in | starc_01 | NORMAL | 2024-04-09T17:04:56.518991+00:00 | 2024-04-09T17:04:56.519017+00:00 | 51 | false | # Approach\n1.We have to return the time when the kth index of tickets are completely sold.\n2.So, from this it is clear that we should have the info about the index also. So, we will be using pair<int, int>.\n3.Run a loop and store in queue {tickets[i], i}.\n4.Run a loop until queue is empty and pick the ticket, index and remove them.\n since tickets are initially > 0, so ticket - 1 and ans + 1.\n if(ticket > 0) push it to queue.\n now if ticket is completely sold and and the index == k, that is the time we need to return. So break it\n# Complexity\n- Time complexity: O(N)\n\n- Space complexity: I have used queue so S.C. -> O(N)\n\n# Code\n```\nclass Solution {\npublic:\n // Since we need to find the time taken to buy the tickets of specific index\n // we should have info about index also so that whenever the kth index tickets are completely\n // that is the time we need to return\n int timeRequiredToBuy(vector<int>& tickets, int k) {\n\n queue<pair<int, int>> q;\n for(int i = 0; i < tickets.size(); i++){\n q.push({tickets[i], i});\n }\n int ans = 0;\n while(!q.empty()){\n // take out the index and tickets\n int ticket = q.front().first;\n int ind = q.front().second;\n // now remove it\n q.pop();\n\n ticket--;\n ans++;\n // if there are remaining tickets\n if(ticket > 0) q.push({ticket, ind});\n // when the given index tickets are completely sold then break the loop\n if(ind == k && ticket == 0) break;\n }\n return ans;\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
time-needed-to-buy-tickets | ✅✨Check this out!!!✨Easiest solution possible! Beginner friendly!✨✅ | check-this-outeasiest-solution-possible-2lqqd | UPVOTE IF YOU LIKE IT :)\n\n# Code\n\nclass Solution:\n def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:\n c=0\n i=0\n wh | Qatyayani | NORMAL | 2024-04-09T14:23:31.208273+00:00 | 2024-04-09T14:23:31.208304+00:00 | 19 | false | # UPVOTE IF YOU LIKE IT :)\n\n# Code\n```\nclass Solution:\n def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:\n c=0\n i=0\n while(i<len(tickets)):\n if tickets[k]==0:\n return c\n if tickets[i]!=0:\n tickets[i]-=1\n c=c+1\n i+=1\n if i==len(tickets):\n i=0\n return c\n``` | 2 | 0 | ['Python3'] | 1 |
time-needed-to-buy-tickets | 🟢Beats 100.00% of users with Java, Easy Solution with Explanation | beats-10000-of-users-with-java-easy-solu-o0ak | Keep growing \uD83D\uDE0A\n\n\n---\n\n# Complexity\n\n- Time complexity: O(n)\n\n- Space complexity: O(1)\n\n---\n\n# Problem\n\n## Real-world scenario\n\nImagi | rahultripathi17 | NORMAL | 2024-04-09T13:56:22.895458+00:00 | 2024-04-09T14:00:38.593415+00:00 | 152 | false | ##### Keep growing \uD83D\uDE0A\n\n\n---\n\n# Complexity\n\n- Time complexity: O(n)\n\n- Space complexity: O(1)\n\n---\n\n# Problem\n\n## Real-world scenario\n\nImagine there\'s a long queue at a ticket counter for a popular concert. The queue consists of n people, where the person at the front of the line (0th person) is the first to buy tickets, and the person at the back of the line (n - 1) is the last.\n\nEach person in the queue has a specific number of tickets they want to buy, indicated by the array tickets of length n, where tickets[i] represents the number of tickets the ith person wants to buy.\n\nAt this ticket counter, each person takes exactly 1 second to purchase a single ticket. After purchasing a ticket, the person goes to the end of the line instantaneously to buy more tickets if needed. If a person has bought all the tickets they wanted, they will leave the queue.\n\nYour task is to determine how much time it will take for the person at position k (0-indexed) in the queue to finish buying all their tickets.\n\nSo, in this scenario, you\'re essentially calculating the time it takes for a specific person in the queue to complete purchasing all the tickets they want.\n\n---\n\n# Approach Explanation\n\n### Calculating Time Required to Buy Tickets\n- The function `timeRequiredToBuy` takes in an array `ticketsArray` representing the number of tickets available at each position, and an integer `position` representing the initial position of the person.\n- It aims to calculate the total time required for a person starting from the given position to buy tickets at each position based on the availability of tickets.\n- The function initializes variables `numberOfPeople`, `currentIndex`, and `timeTaken`.\n - `numberOfPeople` stores the total number of positions in the array.\n - `currentIndex` starts at the given `position`.\n - `timeTaken` stores the total time taken to buy tickets.\n- The function uses a while loop to iterate from the given position towards the start of the array.\n - In each iteration, it adds the minimum of the number of available tickets at the current position and the original position (where the person started) to the `timeTaken`.\n - This simulates the process of buying tickets while moving towards the start of the array.\n- After completing the loop towards the start, the function adjusts the ticket count at the original position by decrementing it by 1.\n- Then, it uses another while loop to iterate from the position towards the end of the array.\n - Similar to the previous loop, it adds the minimum of the number of available tickets at the current position and the original position to the `timeTaken`.\n - This simulates the process of buying tickets while moving towards the end of the array.\n- Finally, the function returns the `timeTaken`, representing the total time required to buy tickets from the given position.\n\n### Complexity Analysis\n- Time Complexity: The algorithm runs in O(n) time, where n is the length of the `ticketsArray`. This is because it iterates through the array twice.\n- Space Complexity: The algorithm uses O(1) additional space, as it only requires a few extra variables regardless of the size of the input array.\n\n---\n\n# Pseudocode\n\n```Javascript []\nStart\nInitialize \'numberOfPeople\' to the length of \'ticketsArray\'\nInitialize \'currentIndex\' to \'position\'\nInitialize \'timeTaken\' to 0\n\nWhile \'currentIndex\' is greater than or equal to 0\n Increment \'timeTaken\' by the minimum of \'ticketsArray[position]\' and \'ticketsArray[currentIndex]\'\n Decrement \'currentIndex\' by 1\nEnd\n\nSet \'currentIndex\' to \'position + 1\'\nDecrement the value at index \'position\' in \'ticketsArray\'\n\nWhile \'currentIndex\' is less than \'numberOfPeople\'\n Increment \'timeTaken\' by the minimum of \'ticketsArray[position]\' and \'ticketsArray[currentIndex]\'\n Increment \'currentIndex\' by 1\nEnd\n\nReturn \'timeTaken\'\nEnd\n```\n\n# Code\n\n```java []\nclass Solution {\n public int timeRequiredToBuy(int[] ticketsArray, int position) {\n int numberOfPeople = ticketsArray.length;\n int currentIndex = position;\n int timeTaken = 0;\n \n while (currentIndex >= 0) {\n timeTaken += Math.min(ticketsArray[position], ticketsArray[currentIndex]);\n --currentIndex;\n }\n \n currentIndex = position + 1;\n --ticketsArray[position];\n \n while (currentIndex < numberOfPeople) {\n timeTaken += Math.min(ticketsArray[position], ticketsArray[currentIndex]);\n ++currentIndex;\n }\n \n return timeTaken;\n }\n}\n```\n----\n> \n# *If you have any question, feel free to ask. If you found my solution helpful, Please UPVOTE !* \uD83D\uDE0A | 2 | 0 | ['Array', 'Queue', 'Simulation', 'Java'] | 0 |
time-needed-to-buy-tickets | Most Optimal || Easy Math Simulation || Java solution | most-optimal-easy-math-simulation-java-s-hh0q | Code\n\nclass Solution {\n public int timeRequiredToBuy(int[] tickets, int k) {\n int time = 0, person = tickets[k];\n int size = tickets.lengt | leo_messi10 | NORMAL | 2024-04-09T13:49:54.208414+00:00 | 2024-04-09T13:49:54.208449+00:00 | 13 | false | # Code\n```\nclass Solution {\n public int timeRequiredToBuy(int[] tickets, int k) {\n int time = 0, person = tickets[k];\n int size = tickets.length;\n\n for (int i = 0; i < size; i++) {\n if (person <= tickets[i]) {\n if (i <= k) {\n time += person;\n } else {\n time += person - 1;\n }\n } else {\n time += tickets[i];\n }\n }\n\n return time;\n }\n}\n``` | 2 | 0 | ['Array', 'Simulation', 'Java'] | 1 |
time-needed-to-buy-tickets | Simple logic🔥🔥🔥|| Very Easy Solution 🔥🔥🔥|| Beat 100% users🔥✅✅🔥 | simple-logic-very-easy-solution-beat-100-aqnj | Intuition\nThe problem seems to be related to purchasing tickets from a particular position in a queue. The goal is to determine the total time required to buy | Pratik_Shelke | NORMAL | 2024-04-09T13:30:05.724857+00:00 | 2024-04-09T13:30:05.724908+00:00 | 7 | false | # Intuition\nThe problem seems to be related to purchasing tickets from a particular position in a queue. The goal is to determine the total time required to buy all the tickets, given the number of tickets available at each position in the queue\n\n# Approach\nThe approach used in the provided code is to iterate through the queue, considering each position. For each position, it calculates the time required to buy the tickets based on the number of tickets available at that position and at position k. It uses Math.min() to select the minimum between the tickets available at the current position and at position k, then accumulates this time in the variable second. The loop continues until all positions in the queue are visited.\n\n# Complexity\n- Time complexity:\n $$O(n)$$ \n\n- Space complexity:\n$$O(1r)$$ \n\n# Code\n```\nclass Solution {\n public int timeRequiredToBuy(int[] tickets, int k) {\n int second=0;\n for(int i=0;i<tickets.length;i++)\n {\n if(i<=k)\n {\n second=second+Math.min(tickets[i],tickets[k]);\n }\n else\n {\n second=second+Math.min(tickets[i],tickets[k]-1);\n }\n }\n return second;\n \n }\n}\n``` | 2 | 0 | ['Java'] | 2 |
time-needed-to-buy-tickets | Beats 100%🔥|| easy JAVA Solution✅ | beats-100-easy-java-solution-by-priyansh-b56n | Code\n\nclass Solution {\n public int timeRequiredToBuy(int[] nums, int k) {\n int ans=0,val=nums[k];\n for(int i=0;i<=k;i++) ans+=Math.min(val | priyanshu1078 | NORMAL | 2024-04-09T13:14:51.128426+00:00 | 2024-04-09T13:14:51.128456+00:00 | 7 | false | # Code\n```\nclass Solution {\n public int timeRequiredToBuy(int[] nums, int k) {\n int ans=0,val=nums[k];\n for(int i=0;i<=k;i++) ans+=Math.min(val,nums[i]);\n for(int i=k+1;i<nums.length;i++){\n if(nums[i]<val) ans+=nums[i];\n else ans+=(val-1);\n }\n return ans;\n }\n}\n``` | 2 | 0 | ['Java'] | 0 |
time-needed-to-buy-tickets | Simple greedy soln | simple-greedy-soln-by-techtinkerer-md7j | \n\n# Complexity\n- Time complexity:O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity:O(1)\n Add your space complexity here, e.g. O(n) \n\n | TechTinkerer | NORMAL | 2024-04-09T12:24:26.712790+00:00 | 2024-04-09T12:24:26.712829+00:00 | 14 | false | \n\n# Complexity\n- Time complexity:O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& tickets, int k) {\n int t=tickets[k];\n\n int ans=0;\n\n int n=tickets.size();\n\n for(int i=0;i<n;i++){\n if(i<k){\n if(tickets[i]<=t){\n ans+=tickets[i];\n }\n else{\n ans+=t; \n }\n }\n else if(i==k)\n ans+=t;\n else{\n if(tickets[i]<t){\n ans+=tickets[i];\n }\n else{\n ans+=t-1; \n }\n }\n }\n\n return ans;\n }\n};\n``` | 2 | 0 | ['Greedy', 'Queue', 'C++'] | 0 |
time-needed-to-buy-tickets | why leetcode why || easy solution with full explanation. | why-leetcode-why-easy-solution-with-full-u4um | Intuition\n Describe your first thoughts on how to solve this problem. \n# pls upvote guys....\n# Approach\n Describe your approach to solving the problem. \n\n | Abhishekkant135 | NORMAL | 2024-04-09T12:21:55.477310+00:00 | 2024-04-09T12:21:55.477339+00:00 | 434 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n# pls upvote guys....\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n\n**Steps:**\n\n1. **Initialization:**\n - `int ans = 0`: Initializes a variable `ans` to store the total number of rounds (time) required to buy the ticket.\n\n2. **Looping Until Target Ticket Purchase:**\n - The `while` loop continues as long as the target ticket (`tickets[k]`) has a value greater than 0 (not purchased yet).\n - **Iterating Through All Tickets:**\n - The inner `for` loop iterates through each ticket in the `tickets` array using index `i`.\n - **Checking Target Ticket Purchase:**\n - `if (tickets[k] == 0)`: This condition checks if the target ticket (`tickets[k]`) has already been purchased (value becomes 0) in a previous iteration. If so, it signifies the loop can terminate, and the function can return the total time (`ans`).\n - **Buying a Ticket (Except Target):**\n - `if (tickets[i] > 0)`: This condition checks if the current ticket (`tickets[i]`) has a value greater than 0 (not purchased yet).\n - `ans++`: Increments `ans` by 1 to account for one round (time unit) as you buy this ticket (or someone else in the queue buys a ticket).\n - `tickets[i]--`: Decrements the value of `tickets[i]` by 1 to simulate the purchase of that ticket.\n\n3. **Returning the Result:**\n - After the loop completes (when the target ticket `tickets[k]` is purchased), the function returns the final value of `ans`, which represents the total time required to buy the target ticket.\n\n\n\n\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n- In the worst case, where the target ticket is at the end of the queue (`k` is large), the code might need to iterate through all tickets in each round until the target ticket is purchased. This can lead to a time complexity of O(n * tickets[k]), where n is the length of the `tickets` array.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int timeRequiredToBuy(int[] tickets, int k) {\n int ans=0;\n while(tickets[k]>0){\n for(int i=0;i<tickets.length;i++){\n if(tickets[k]==0){\n return ans;\n }\n if(tickets[i]>0){\n ans++;\n tickets[i]--;\n }\n \n }\n }\n return ans;\n }\n}\n``` | 2 | 0 | ['Array', 'Simulation', 'Java'] | 1 |
time-needed-to-buy-tickets | easy code in c++ | easy-code-in-c-by-shobhit_panuily-ucud | \n\n# Brute force\n\n# Code\n\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& tickets, int k) {\n int count=0,i=0,n=tickets.size();\n | Shobhit_panuily | NORMAL | 2024-04-09T12:21:34.106539+00:00 | 2024-04-09T12:21:34.106566+00:00 | 15 | false | \n\n# Brute force\n\n# Code\n```\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& tickets, int k) {\n int count=0,i=0,n=tickets.size();\n while(tickets[k]!=0) {\n if(tickets[i]!=0) {\n tickets[i]--;\n count++;\n }\n i++;\n i=i%n;\n }\n return count;\n }\n};\n```\n# Optimized\n# Complexity\n- Time complexity:$$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n# Code\n```\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& tickets, int k) {\n int count=0,n=tickets.size();\n int kVal=tickets[k];\n for(int i=0;i<n;i++) {\n if(i<=k) {\n count += min(tickets[i],kVal);\n }\n else {\n count+= min(tickets[i],kVal-1);\n }\n }\n return count;\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
time-needed-to-buy-tickets | Easy solution || Beats 100.00% of users with C++ || 🔥 | easy-solution-beats-10000-of-users-with-jgg0i | \n\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& tickets, int k) {\n int n = tickets.size(),count=0;\n if((k==0) &&(tickets[k | bbanerjee1002 | NORMAL | 2024-04-09T11:53:09.392373+00:00 | 2024-04-09T11:53:09.392430+00:00 | 15 | false | \n```\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& tickets, int k) {\n int n = tickets.size(),count=0;\n if((k==0) &&(tickets[k]==1 || tickets[k]==0)) return tickets[k];\n while(true){\n for(int i=0;i<n;i++){\n if(tickets[k]==0) return count;\n if(tickets[i]>0) tickets[i]--,count++;\n }\n \n }\n return -1;\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
time-needed-to-buy-tickets | 100% Beast Code || Java Solution || 6 Lines Optimal Code | 100-beast-code-java-solution-6-lines-opt-ndn2 | 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 | RtLavKush7 | NORMAL | 2024-04-09T10:03:16.140776+00:00 | 2024-04-09T10:03:16.140800+00:00 | 4 | 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 Solution {\n public int timeRequiredToBuy(int[] tickets, int k) {\n int value =tickets[k];\n int seconds=0;\n for(int i=0;i<tickets.length;i++){\n int max=(i<=k) ? value: value-1;\n seconds+=(tickets[i]>max) ? max: tickets[i];\n } \n return seconds;\n }\n}\n``` | 2 | 0 | ['Java'] | 0 |
time-needed-to-buy-tickets | different way PYTHON | different-way-python-by-justingeorge-4yfu | 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 | justingeorge | NORMAL | 2024-04-09T09:32:16.068579+00:00 | 2024-04-09T09:32:16.068609+00:00 | 76 | 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 Solution:\n def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:\n\n new=[]\n kk=tickets[k]\n x=0\n for i in range(len(tickets)):\n if tickets[i]<=kk:\n new.append(tickets[i])\n if i > k and tickets[i]>=tickets[k]:\n x+=1\n more=len(tickets)-len(new)\n \n return sum(new)+(more*kk)-x\n \n``` | 2 | 0 | ['Python3'] | 0 |
time-needed-to-buy-tickets | C++ solution||Beginner friendly solution | c-solutionbeginner-friendly-solution-by-euhcz | Approach\n\n1. Initialize count to 0. This variable will keep track of the total number of tickets bought.\n2. Start a loop where pass represents the number of | Tanishqa_bansal | NORMAL | 2024-04-09T09:06:30.167317+00:00 | 2024-04-09T09:10:33.030229+00:00 | 24 | false | # Approach\n\n1. Initialize `count` to **0**. This variable will keep track of the total number of tickets bought.\n2. Start a loop where `pass` **represents the number of passes made to buy tickets**. This loop continues until the kth person has recieved the number of tickets wanted i.e. `tickets[k]` **becomes zero**.\n3. Inside the outer loop, there\'s another loop that iterates over tickets array (indexed by i).\n4. For each value in tickets array, if it has available tickets (`tickets[i] != 0`), **increment the count** to reflect the purchase of one ticket and **decrease the count of available tickets** for that type by one (`tickets[i] = tickets[i] - 1`).\n5. Check if the number of available tickets for the specified person k **has become zero**. If it has, `break` out of the inner loop.\n6. Repeat steps 3-5 until the number of tickets required by person **k becomes zero**.\n7. Finally, `return` the **total count** of tickets bought (`count`).\n\n# Complexity\n- Time complexity:\nO(n^2)\n**Reason:** The code contains a nested loop where the outer loop runs until `tickets[k]` becomes 0 and the inner loop iterates over all elements in the tickets vector. This results in a quadratic time complexity.\n\n- Space complexity:\nO(1)\n**Reason:** The space complexity of this solution is **O(1)** because we are using a constant amount of extra space regardless of the size of the input.\n\n\n\n\n\n# Code\n```\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& tickets, int k) {\n int count = 0;\n for (int pass = 0; tickets[k] != 0; pass++) {\n for (int i = 0; i < tickets.size(); i++) {\n if (tickets[i] != 0) {\n count++;\n tickets[i] = tickets[i] - 1;\n }\n if (tickets[k] == 0) {\n break;\n }\n }\n }\n return count;\n }\n};\n``` | 2 | 0 | ['Array', 'C++'] | 0 |
time-needed-to-buy-tickets | Easiest Solution without using Queue || C++ || Beginner Approach | easiest-solution-without-using-queue-c-b-5brb | \n\n\n# Code\n\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& tickets, int k) {\n int n=tickets.size();\n int sum=0;\n\n | sanon2025 | NORMAL | 2024-04-09T08:49:55.008288+00:00 | 2024-04-09T08:49:55.008323+00:00 | 33 | false | \n\n\n# Code\n```\nclass Solution {\npublic:\n int timeRequiredToBuy(vector<int>& tickets, int k) {\n int n=tickets.size();\n int sum=0;\n\n for(int i=0;i<n;i++){\n if(tickets[i]<=tickets[k]){\n sum=sum+tickets[i];\n }\n else if(tickets[i]>tickets[k]){\n sum=sum+tickets[k];\n }\n }\n for(int i=k+1;i<n;i++){\n if(tickets[i]>=tickets[k]){\n sum=sum-1;\n }\n }\n return sum;\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
time-needed-to-buy-tickets | Scala FP: 1 pass foldLeft no simulation | scala-fp-1-pass-foldleft-no-simulation-b-nfi2 | Code\n\nobject Solution {\n def timeRequiredToBuy(tickets: Array[Int], k: Int): Int =\n tickets.indices.foldLeft(0)((sum, n) => sum + tickets(n).min(if (n > | SerhiyShaman | NORMAL | 2024-04-09T08:43:37.020663+00:00 | 2024-04-09T08:43:37.020694+00:00 | 10 | false | # Code\n```\nobject Solution {\n def timeRequiredToBuy(tickets: Array[Int], k: Int): Int =\n tickets.indices.foldLeft(0)((sum, n) => sum + tickets(n).min(if (n > k) tickets(k) - 1 else tickets(k)))\n}\n``` | 2 | 0 | ['Scala'] | 0 |
time-needed-to-buy-tickets | Python | Easy | python-easy-by-khosiyat-6neu | see the Successfully Accepted Submission\n\n# Code\n\nclass Solution:\n def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:\n n = len(tick | Khosiyat | NORMAL | 2024-04-09T07:21:59.426972+00:00 | 2024-04-09T07:21:59.427009+00:00 | 150 | false | [see the Successfully Accepted Submission](https://leetcode.com/problems/time-needed-to-buy-tickets/submissions/1227409140/?source=submission-ac)\n\n# Code\n```\nclass Solution:\n def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:\n n = len(tickets)\n time = 0\n \n # Simulate the process\n while tickets[k] > 0:\n for i in range(n):\n if tickets[i] > 0:\n tickets[i] -= 1\n time += 1\n if i == k and tickets[i] == 0:\n return time\n return time\n \n```\n\n | 2 | 0 | ['Python3'] | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.