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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
longest-unequal-adjacent-groups-subsequence-ii | Longest subsequence adjacent groups subsequence || Time complexity O(n * m^2) || using recursion | longest-subsequence-adjacent-groups-subs-blat | 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 | prajwal13r | NORMAL | 2023-12-09T11:25:14.447018+00:00 | 2023-12-09T11:25:14.447045+00:00 | 5 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n * m^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n * m)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\nm is average length of words of a specific length\n# Code\n```\nclass Solution:\n def getWordsInLongestSubsequence(self, n: int, words: List[str], groups: List[int]) -> List[str]:\n def hamming(w1, w2):\n return len([x for x in range(len(w1)) if w1[x]!=w2[x]]) == 1\n\n d = {}\n resd = {}\n for x in range(len(words)):\n l = len(words[x])\n if l in d:\n for xy in d[l]:\n if (xy[0]!=groups[x]) and hamming(xy[1], words[x]):\n if xy in resd:\n resd[xy] += [(groups[x], words[x])]\n else:\n resd[xy] = [(groups[x], words[x])]\n d[l] += [(groups[x], words[x])]\n else:\n d[l] = [(groups[x], words[x])]\n resd[(groups[x], words[x])] = []\n\n @cache\n def rec(i):\n ans = []\n if i in resd:\n for x in resd[i]:\n t = [x[1]] + rec(x)\n if len(t) > len(ans):\n ans = t\n return ans\n\n return max([ [x[1]] + rec(x) for x in resd.keys() ], key=len)\n\n\n``` | 0 | 0 | ['Hash Table', 'Recursion', 'Python3'] | 0 |
longest-unequal-adjacent-groups-subsequence-ii | Python Medium | python-medium-by-lucasschnee-rqbq | \nclass Solution:\n def getWordsInLongestSubsequence(self, n: int, words: List[str], groups: List[int]) -> List[str]:\n N = len(words)\n\n \n | lucasschnee | NORMAL | 2023-11-23T01:06:12.314791+00:00 | 2023-11-23T01:06:12.314809+00:00 | 4 | false | ```\nclass Solution:\n def getWordsInLongestSubsequence(self, n: int, words: List[str], groups: List[int]) -> List[str]:\n N = len(words)\n\n \n best = 0\n\n def good(l, r):\n counter = 0\n for i in range(len(words[l])):\n if words[l][i] != words[r][i]:\n counter += 1\n\n if counter == 2:\n return False\n\n return True\n\n \n\n best = [1] * N\n prev = [None] * N\n r = -1\n biggest = -1\n\n\n for index in range(N):\n curBest = 1\n pr = -1\n\n for j in range(index):\n if len(words[j]) == len(words[index]) and good(index, j) and groups[index] != groups[j]:\n if best[j] + 1 > curBest:\n curBest = best[j] + 1\n pr = j\n\n best[index] = curBest\n prev[index] = pr\n if best[index] > biggest:\n biggest = best[index]\n r = index\n\n\n ans = []\n\n while r != -1:\n ans.append(words[r])\n r = prev[r]\n\n\n return ans[::-1]\n\n\n\n \n``` | 0 | 0 | ['Python3'] | 0 |
longest-unequal-adjacent-groups-subsequence-ii | Easy Python Solution | easy-python-solution-by-sb012-a19f | Code\n\nclass Solution:\n def getWordsInLongestSubsequence(self, n: int, words: List[str], groups: List[int]) -> List[str]:\n\n def wordCondition(w1, | sb012 | NORMAL | 2023-11-14T20:02:48.957652+00:00 | 2023-11-14T20:02:48.957680+00:00 | 7 | false | # Code\n```\nclass Solution:\n def getWordsInLongestSubsequence(self, n: int, words: List[str], groups: List[int]) -> List[str]:\n\n def wordCondition(w1, w2):\n if len(w1) != len(w2): return False\n if sum(a != b for a, b in zip(w1, w2)) == 1: return True\n return False\n\n index = [[i] for i in range(n)]\n\n for i in range(1, len(index)):\n vals = []\n for j in range(i):\n if groups[j] != groups[i] and wordCondition(words[j], words[i]):\n vals.append(index[j] + index[i])\n if vals: index[i] = max(vals, key=len)\n\n index.sort(key = len)\n\n return [words[i] for i in index[-1]]\n``` | 0 | 0 | ['Python3'] | 0 |
longest-unequal-adjacent-groups-subsequence-ii | DP+HashMap to remember all previous words with the same length | dphashmap-to-remember-all-previous-words-1e3r | Intuition\nTry to remember past results and only search the relevant previous subsequences.\n\n# Approach\nThe current length and last words of each subsequence | flyfish | NORMAL | 2023-11-08T03:02:09.235784+00:00 | 2023-11-08T03:04:51.220167+00:00 | 3 | false | # Intuition\nTry to remember past results and only search the relevant previous subsequences.\n\n# Approach\nThe current length and last words of each subsequence should be recorded, not only the length.\n\nBackfill last words to generate a reverse list or use addLast.\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 List<String> getWordsInLongestSubsequence(int n, String[] words, int[] groups) {\n int max=1;\n int end=0;\n int[] dp = new int[n];\n int[] last = new int[n];\n Map<Integer, List<Integer>> subs = new HashMap<>();\n\n dp[0]=1;\n last[0]=-1;\n List<Integer> temp=new ArrayList<Integer>();\n temp.add(0);\n subs.put(words[0].length(),temp);\n for(int i=1; i<n; i++) {\n int l=words[i].length();\n dp[i]=1;\n last[i]=-1;\n if(subs.containsKey(l)) {\n temp=subs.get(l);\n for(int j:temp){\n if(groups[i]!=groups[j] &&distance(words,i,j)==1) {\n if(dp[i]<dp[j]+1){\n dp[i]=dp[j]+1;\n last[i]=j;\n } \n }\n }\n temp.add(i);\n subs.put(l,temp);\n } else {\n temp=new ArrayList<Integer>();\n temp.add(i);\n subs.put(l,temp);\n }\n if(dp[i]>max){\n max=dp[i];\n end=i;\n }\n }\n LinkedList<String> res = new LinkedList<String> ();\n \n while(end!=-1){\n res.addFirst(words[end]);\n end=last[end];\n }\n \n return res;\n }\n\n private int distance(String[] words, int i, int j){\n //input validations\n\n if(words[i].length()==words[j].length()) {\n int d=0;\n for(int k=0; k<words[i].length();k++) {\n if(words[i].charAt(k)!=words[j].charAt(k)){\n d++;\n }\n }\n return d;\n }\n return -1;\n }\n\n}\n``` | 0 | 0 | ['Java'] | 0 |
longest-unequal-adjacent-groups-subsequence-ii | Longest Unequal Adjacent Groups Subsequence II | longest-unequal-adjacent-groups-subseque-ex40 | 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 | Vk_2005_mr | NORMAL | 2023-11-02T19:30:57.917084+00:00 | 2023-11-02T19:30:57.917109+00:00 | 6 | 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 getWordsInLongestSubsequence(self, n: int, words: List[str], groups: List[int]) -> List[str]:\n # Precompute the hamming distance between any two words - O(n^2)\n # Stored in a grid where hamming[i][j] = hamming(words[i], words[j])\n # Put -1 in place of unequal length words\n hamming = [[0] * n for i in range(n)] # n x n grid of zeros\n\n for i, word1 in enumerate(words):\n for j, word2 in enumerate(words[i + 1:], start=i + 1):\n if len(word1) != len(word2):\n hamming[i][j] = -1\n continue\n\n # Compute hamming distance\n hamming_dist = 0\n for char1, char2 in zip(word1, word2):\n hamming_dist += char1 != char2\n if hamming_dist > 1:\n break\n hamming[i][j] = hamming[j][i] = hamming_dist\n\n dp = [1] * n # dp[i] is the longest subsequence possible ending at words[i]\n prev = [-1] * n # Keep track of the sequence of words\n\n for word_idx in range(n):\n for prev_word_idx in range(word_idx):\n if hamming[word_idx][prev_word_idx] != 1:\n continue\n if groups[word_idx] == groups[prev_word_idx]:\n continue\n\n # If the longest subseqence ending at words[i] is greater than\n # the subsequence we\'re looking at, use the one ending at words[i]\n # and add 1 for the current word\n if dp[word_idx] <= dp[prev_word_idx]:\n dp[word_idx] = dp[prev_word_idx] + 1\n prev[word_idx] = prev_word_idx\n \n # Compute argmax of dp\n _, argmax = max((dp[i], i) for i in range(n))\n\n # Starting at argmax step backwards through prev to reconstruct the sequence\n longest_sub = []\n while argmax != -1:\n longest_sub.append(words[argmax])\n argmax = prev[argmax]\n\n return reversed(longest_sub)\n``` | 0 | 0 | ['Python3'] | 0 |
longest-unequal-adjacent-groups-subsequence-ii | 🔥 C++ Solution || Top - Down DP approach || Faster and Easy to understand | c-solution-top-down-dp-approach-faster-a-oxhq | \n\n# Code\n\nclass Solution {\npublic:\n int hammingDistance(string& s1,string& s2){\n int n = s1.size();\n\n int d = 0;\n for(int i=0; | ravi_verma786 | NORMAL | 2023-11-01T11:00:20.354709+00:00 | 2023-11-01T11:00:20.354733+00:00 | 4 | false | \n\n# Code\n```\nclass Solution {\npublic:\n int hammingDistance(string& s1,string& s2){\n int n = s1.size();\n\n int d = 0;\n for(int i=0;i<n;i++){\n d += (s1[i] != s2[i]);\n\n if(d > 1) break;\n }\n\n return d;\n }\n\n vector<string> getWordsInLongestSubsequence(int n, vector<string>& words, vector<int>& groups) {\n vector<pair<int,int>> dp(n,{1,-1}); // {dis,prev}\n int maxIndex = 0,maxi = 0;\n\n for(int i=1;i<n;i++){\n for(int j=i-1;j>=0;j--){\n if(words[i].size() == words[j].size() && groups[i] != groups[j] && hammingDistance(words[i],words[j]) == 1){\n if(1 + dp[j].first > dp[i].first){\n dp[i] = {1 + dp[j].first,j};\n }\n\n if(dp[i].first > maxi){\n maxi = dp[i].first;\n maxIndex = i;\n }\n }\n }\n }\n\n vector<string> ans;\n while(maxIndex >= 0){\n ans.push_back(words[maxIndex]);\n maxIndex = dp[maxIndex].second;\n }\n\n reverse(ans.begin(),ans.end());\n \n return ans;\n }\n};\n``` | 0 | 0 | ['String', 'Dynamic Programming', 'C++'] | 0 |
longest-unequal-adjacent-groups-subsequence-ii | DP with optimal answer storage. | dp-with-optimal-answer-storage-by-rahul_-82w9 | 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 | rahul_bhaiya | NORMAL | 2023-10-30T10:38:37.058278+00:00 | 2023-10-30T10:38:37.058298+00:00 | 3 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n bool canBeAdj[1001][1001];\n bool hammDist(string s, string p)\n {\n int n = s.size();\n if(n!=p.size())\n {\n return false;\n }\n int count =0;\n for(int i=0;i<n;i++)\n {\n if(s[i]!=p[i])\n {\n count++;\n if(count>1)\n {\n return false;\n }\n }\n }\n if(count==1)\n {\n return true;\n }\n return false;\n }\n\n vector<short> getAns(vector<string> &words, int ind,int lastTaken,vector<vector<vector<short>>> & dp){\n if(ind>=words.size())\n {\n return {};\n }\n\n if(dp[ind][lastTaken+1].size()>0)\n {\n return dp[ind][lastTaken+1];\n }\n \n vector<short> tempNotTake = getAns(words,ind+1, lastTaken,dp);\n vector<short> tempTake={};\n\n if(lastTaken==-1 || canBeAdj[lastTaken][ind]==true)\n {\n tempTake = getAns(words,ind+1, ind,dp);\n\n tempTake.push_back((short)ind);\n\n }\n if(tempNotTake.size()>tempTake.size())\n {\n return dp[ind][lastTaken+1] = tempNotTake;\n }\n return dp[ind][lastTaken+1] = tempTake;\n\n\n \n\n }\npublic:\n vector<string> getWordsInLongestSubsequence(int n, vector<string>& words, vector<int>& groups) {\n memset(canBeAdj,false,sizeof(canBeAdj));\n // memset(dp,make_pair(false,""),sizeof(dp));\n vector<vector<vector<short>>> dp(n,vector<vector<short>>(n+1));\n \n for(int i=0;i<n;i++)\n {\n for(int j=i+1;j<n;j++)\n {\n if(groups[i]!=groups[j] && hammDist(words[i],words[j]))\n {\n canBeAdj[i][j]=true;\n }\n }\n }\n\n \n vector<short> res = getAns(words,0,-1,dp);\n sort(res.begin(),res.end());\n\n \n\n\n vector<string> v;\n for(int i=0;i<res.size();i++)\n {\n v.push_back(words[res[i]]);\n }\n\n return v;\n\n \n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
longest-unequal-adjacent-groups-subsequence-ii | Using dp O(n^2) solution | using-dp-on2-solution-by-zaid_2034-hr7w | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nsimple dp\n\n# Complexity\n- Time complexity:\nO(n^2)\n- Space complexity | Zaid_2034 | NORMAL | 2023-10-26T12:17:04.974606+00:00 | 2023-10-26T12:17:04.974627+00:00 | 4 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nsimple dp\n\n# Complexity\n- Time complexity:\nO(n^2)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n bool hamm(string a,string b){\n if(a.length()!=b.length())return false;\n int count=0;\n for(int i=0;i<a.length();i++){\n if(a[i]!=b[i])count++;\n }\n if(count==1)return true;\n return false; \n } \n vector<string> getWordsInLongestSubsequence(int n, vector<string>& words, vector<int>& groups) {\n vector<int> dp(n,1);\n vector<int> hash(n);\n for(int i=0;i<n;i++){\n hash[i]=i;\n }\n int prev=-1;\n int maxIndex=0;\n int maxi=INT_MIN;\n for(int i=0;i<n;i++){\n for(int j=0;j<i;j++){\n if(groups[i]!=groups[j] && hamm(words[i],words[j]) && 1+dp[j]>dp[i]){\n dp[i]=dp[j]+1;\n hash[i]=j;\n } \n }\n if(dp[i]>maxi){\n maxi=dp[i];\n maxIndex=i;\n }\n }\n vector<string> ans;\n ans.push_back(words[maxIndex]);\n while(hash[maxIndex]!=maxIndex){\n ans.push_back(words[hash[maxIndex]]);\n maxIndex=hash[maxIndex];\n } \n reverse(ans.begin(),ans.end());\n return ans;\n \n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
longest-unequal-adjacent-groups-subsequence-ii | DP (LIS) problem | dp-lis-problem-by-ar_it_is-utob | 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 | ar_it_is | NORMAL | 2023-10-26T10:23:15.740176+00:00 | 2023-10-26T10:23:15.740206+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 {\npublic:\nint hamm(string &A,string &B){\n int cnt =0;\n for(int i =0;i<A.size();i++){\n if(A[i]!=B[i]){\n cnt++;\n }\n }\n return cnt;\n}\n vector<string> getWordsInLongestSubsequence(int n, vector<string>& w, vector<int>& g) {\n\n vector<int>dp(n,1);\n vector<int>lis(n,-1);\n int ans =1;\n int last =-1;\n\n for(int i =1;i<n;i++){\n for(int j =0;j<i;j++){\n if(w[j].size()==w[i].size()){\n if(hamm(w[j],w[i])==1&&g[i]!=g[j]){\n if(dp[i]<dp[j]+1){\n dp[i]=dp[j]+1;\n lis[i]=j;\n }\n if(dp[i]>ans){\n ans=dp[i];\n last=i;\n }\n\n\n }\n }\n }\n }\n vector<string>f;\n if(last==-1){\n f.push_back(w[0]);\n return f;\n }\n \n while(last!=-1){\n f.push_back(w[last]);\n last=lis[last];\n }\n \n reverse(f.begin(),f.end());\n return f;\n }\n};\n``` | 0 | 0 | ['Dynamic Programming', 'C++'] | 0 |
longest-unequal-adjacent-groups-subsequence-ii | Simple (LIS Approach) | simple-lis-approach-by-ajaybunty5847-3cxd | Intuition\nFollow the LIS Approach and then store the indices of the longest subsequence in prev array backtrack the prev array and store it in a list and rever | Ajaybunty5847 | NORMAL | 2023-10-26T06:32:52.680708+00:00 | 2023-10-26T06:32:52.680740+00:00 | 2 | false | # Intuition\nFollow the LIS Approach and then store the indices of the longest subsequence in $$prev$$ array backtrack the $$prev$$ array and store it in a list and reverse the list and return it.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nIf we know how to print the LIS (Longest Increasing Subsequence) then this would be an easy problem just with some checks.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n*n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n- Space complexity: $$O(n + n) = O(n)$$ \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public List<String> getWordsInLongestSubsequence(int n, String[] words, int[] groups) {\n int[] dp = new int[n];\n Arrays.fill(dp,1);\n int[] prev = new int[n];\n int max = 0;\n int maxIndex = 0;\n\n for(int i = 0;i < n;i++){\n prev[i] = i;\n for(int j = 0;j < i;j++){\n String a = "" + words[i];\n String b = "" + words[j];\n if(groups[i] != groups[j]){\n if(check(a,b)){\n if(dp[i] < 1 + dp[j]){\n dp[i] = 1 + dp[j];\n prev[i] = j;\n }\n }\n }\n }\n if(dp[i] > max){\n max = dp[i];\n maxIndex = i;\n }\n }\n\n List<String> ans = new ArrayList<>();\n ans.add(words[maxIndex]);\n while(maxIndex != prev[maxIndex]){\n maxIndex = prev[maxIndex];\n ans.add(words[maxIndex]);\n }\n\n int si = 0;\n int ei = ans.size() - 1;\n while(si <= ei){\n String temp = "" + ans.get(si);\n ans.set(si,ans.get(ei));\n ans.set(ei,temp);\n si++;\n ei--;\n }\n return ans;\n }\n\n boolean check(String a, String b){\n int n = a.length();\n int m = b.length();\n if(n != m){\n return false;\n }\n int cnt = 0;\n for(int i = 0;i < m;i++){\n if(a.charAt(i) != b.charAt(i)){\n cnt++;\n }\n if(cnt > 1){\n return false;\n }\n }\n return true;\n }\n\n}\n``` | 0 | 0 | ['Java'] | 0 |
longest-unequal-adjacent-groups-subsequence-ii | Essentially LIS | DP | essentially-lis-dp-by-cold_coffee-7sgh | Intuition\n Describe your first thoughts on how to solve this problem. \nKeep track of longest subsequence fulfillling group and distance conditions. A parent a | cold_coffee | NORMAL | 2023-10-24T22:10:11.831792+00:00 | 2023-10-24T22:10:11.831824+00:00 | 2 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nKeep track of longest subsequence fulfillling group and distance conditions. A parent array is maintained to construct\nthe solution once longest subsequence is determined.\nSo essentially a LIS problem disguised as this convoluted monstrosity.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(10 * n^2)$$ \n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n# Code\n```\nclass Solution {\npublic:\n\n bool dist(string& a, string& b) {\n if(a.size() != b.size()) return 0;\n int dist = 0;\n for(int i=0; i<a.size(); ++i) {\n if(a[i] != b[i]) dist++;\n if(dist > 1) return 0;\n }\n return 1;\n }\n\n vector<string> getWordsInLongestSubsequence(int n, vector<string>& words, vector<int>& groups) {\n \n vector<int> p(n), cnt(n, 1);\n for(int i=0; i<n; ++i) p[i] = i;\n\n for(int i=1; i<n; ++i) {\n for(int j=0; j<i; ++j) {\n if(groups[i] != groups[j] && dist(words[i], words[j])) {\n if(cnt[j] + 1 > cnt[i])\n cnt[i] = cnt[j] + 1, p[i] = j;\n }\n }\n }\n\n int j = max_element(cnt.begin(), cnt.end()) - cnt.begin();\n\n vector<string> ans;\n while(p[j] != j) ans.push_back(words[j]), j = p[j];\n ans.push_back(words[j]);\n reverse(ans.begin(), ans.end());\n\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
longest-unequal-adjacent-groups-subsequence-ii | Brutal force but very efficient | brutal-force-but-very-efficient-by-fredr-dmft | 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 | Fredrick_LI | NORMAL | 2023-10-24T09:39:43.027760+00:00 | 2023-10-24T09:39:43.027777+00:00 | 6 | 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 getWordsInLongestSubsequence(self, n: int, words: List[str], groups: List[int]) -> List[str]:\n last = [-1] * n\n dic = {}\n l = 0\n for i in range(n): \n w,g = words[i],groups[i]\n temp = 0\n for j in range(len(w)):\n w1 = w[:j] + \'.\' + w[j+1:]\n if w1 in dic:\n for t,k in dic[w1]:\n if groups[k] != g and words[k] != w and t > temp:\n temp = t\n last[i] = k\n temp += 1\n for j in range(len(w)):\n w1 = w[:j] + \'.\' + w[j+1:]\n if w1 in dic:\n for m in range(len(dic[w1])):\n flag = False\n t,k = dic[w1][m]\n if groups[k] == g and words[k] == w:\n dic[w1][m] = (temp,i)\n flag = True\n break\n if not flag:\n dic[w1].append((temp,i))\n dic[w1].sort()\n if len(dic[w1]) > 4:\n dic[w1].pop(0)\n else:\n dic[w1] = [(temp,i)]\n if temp > l:\n l = temp\n p = i\n ans = []\n while p != -1:\n ans.append(words[p])\n p = last[p]\n return ans[::-1]\n\n\n\n\n\n``` | 0 | 0 | ['Python3'] | 0 |
longest-unequal-adjacent-groups-subsequence-ii | Backwards DP | backwards-dp-by-guobao2-76dn | Intuition\nThe trick is to sort the words by length. Since it has corresponding groups I create a new array of pairs.\n\n# Complexity\n- Time complexity:\nO(nlo | guobao2 | NORMAL | 2023-10-24T01:55:56.140020+00:00 | 2023-10-24T03:53:26.969804+00:00 | 2 | false | # Intuition\nThe trick is to sort the words by length. Since it has corresponding groups I create a new array of pairs.\n\n# Complexity\n- Time complexity:\nO(nlogn)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nrecord Pair(String word, int group) implements Comparable<Pair> {\n\n @Override\n public int compareTo(Pair other) {\n return this.word.length() - other.word.length();\n }\n}\n\nclass Solution {\n List<String>[] dpWords;\n\n public List<String> getWordsInLongestSubsequence(int n, String[] words, int[] groups) {\n Pair[] pairs = new Pair[n];\n for (int i = 0; i < n; i++) {\n pairs[i] = new Pair(words[i], groups[i]);\n }\n\n Arrays.sort(pairs);\n dpWords = (List<String>[]) new List<?>[n];\n dpWords[n - 1] = new ArrayList<>();\n dpWords[n - 1].add(pairs[n - 1].word());\n int maxLen = 0, best = 0;\n for (int i = n - 2; i > -1; i--) {\n dpWords[i] = link(pairs, i);\n if (dpWords[i].size() > maxLen) {\n maxLen = dpWords[i].size();\n best = i;\n }\n }\n return dpWords[best];\n }\n\n List<String> link(Pair[] pairs, int i) {\n String word = pairs[i].word();\n int group = pairs[i].group();\n int best = i, maxLen = 0;\n List<String> r = new ArrayList<>();\n r.add(word);\n for (int j = i + 1; j < pairs.length; j++) {\n String word2 = pairs[j].word();\n int group2 = pairs[j].group();\n if (word.length() < word2.length()) {\n break;\n }\n if (!diffByOne(word, word2) || group == group2) {\n continue;\n }\n if (maxLen < dpWords[j].size()) {\n maxLen = dpWords[j].size();\n best = j;\n }\n }\n if (best == i) {\n return r;\n }\n r.addAll(dpWords[best]);\n return r;\n }\n\n boolean diffByOne(String w1, String w2) {\n int r = 0;\n for (int i = 0; i < w1.length(); i++) {\n if (w1.charAt(i) != w2.charAt(i)) {\n r += 1;\n if (r > 1) {\n return false;\n }\n }\n }\n return r == 1;\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
longest-unequal-adjacent-groups-subsequence-ii | LIS || Memo + DP Solution | lis-memo-dp-solution-by-shaurya950-5ys5 | 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 | shaurya950 | NORMAL | 2023-10-22T03:50:09.055508+00:00 | 2023-10-22T03:50:09.055527+00:00 | 12 | 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 getWordsInLongestSubsequence(self, n: int, words: List[str], groups: List[int]) -> List[str]:\n \n self.cache = {}\n self.ans = []\n self.max_len = 0\n for i in range(len(words)):\n self.helper(i, words, groups)\n for key in self.cache:\n if len(self.cache[key]) > self.max_len:\n self.max_len = len(self.cache[key])\n self.ans = self.cache[key]\n return self.ans\n\n\n def calculate_hamming_distance(self, w1, w2):\n\n count = 0\n\n for i in range(len(w1)):\n if w1[i] != w2[i]:\n count += 1\n\n return count == 1\n\n\n def helper(self, index, words, groups):\n\n if index >= len(words):\n return []\n\n if index in self.cache:\n return self.cache[index]\n\n curr_word = words[index]\n ans = []\n for i in range(index + 1, len(words)):\n if len(words[i]) == len(curr_word) and self.calculate_hamming_distance(words[i], curr_word) and groups[index] != groups[i]:\n curr_len = self.helper(i, words, groups)\n if len(curr_len) > len(ans):\n ans = curr_len\n\n\n self.cache[index] = [curr_word] + ans\n return self.cache[index]\n``` | 0 | 0 | ['Python3'] | 0 |
longest-unequal-adjacent-groups-subsequence-ii | Python | DP | O(n^2) | python-dp-on2-by-aryonbe-sjcj | Code\n\nclass Solution:\n def getWordsInLongestSubsequence(self, n: int, words: List[str], groups: List[int]) -> List[str]:\n def dist(x, y):\n | aryonbe | NORMAL | 2023-10-21T09:17:06.136471+00:00 | 2023-10-21T09:19:44.579217+00:00 | 6 | false | # Code\n```\nclass Solution:\n def getWordsInLongestSubsequence(self, n: int, words: List[str], groups: List[int]) -> List[str]:\n def dist(x, y):\n if len(x) != len(y): return False \n return sum([x[i] != y[i] for i in range(len(x))]) == 1\n n = len(words)\n dp = [1]*n\n prev = [-1]*n\n for i in range(1,n):\n for j in range(i):\n if groups[i] != groups[j] and dist(words[i], words[j]):\n if dp[i] < dp[j] + 1:\n dp[i] = dp[j] + 1\n prev[i] = j\n j = dp.index(max(dp))\n res = []\n while j != -1:\n res.append(words[j])\n j = prev[j]\n return reversed(res)\n\n``` | 0 | 0 | ['Python3'] | 0 |
longest-unequal-adjacent-groups-subsequence-ii | Python from O(n^2) space complexity to O(n) using Dynamic Programming | python-from-on2-space-complexity-to-on-u-0qvc | Intuition\n Describe your first thoughts on how to solve this problem. \nI saw there were subproblems with the amount of choices we had per step. So I thought d | robert961 | NORMAL | 2023-10-21T00:13:45.644268+00:00 | 2023-10-21T00:13:45.644285+00:00 | 5 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nI saw there were subproblems with the amount of choices we had per step. So I thought dynamic programming using a decision tree. I either pick the word or don\'t pick the word. I orginally thought about using the current index and previous index in my DP. Using those indexes with groups and words I could see if the words had one letter off and the group scores were different. If correct then I would append them.The longest list of words would be my solution. I wrote my bottom solution this way(commented code).\n\nShout out to @abhiskey_2nub. I used some neat tricks from his solution to make my code look cleaner. \n# Approach\n<!-- Describe your approach to solving the problem. -->\nAfter coding up the bottom solution, I realized that both choices to pick the current element or to not pick the current element rely on index + 1. So I only always needed the last row of DP, thus it could be solved in O(n). I would just need to exhuast all the choices in that row by using a for loop, the length of all the words. Thus O(n).\n\nI have to use another for loop to examine all starting points in words incase there is a word that doesn\'t connect with any other word in the next row. Thus returning without exmaining all the possible combinations. Adding a for loop makes it exhuastive. \n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n^2)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n) on the first code, O(n^2) on the second code\n# Code\n```\nclass Solution:\n def getWordsInLongestSubsequence(self, n: int, words: List[str], groups: List[int]) -> List[str]:\n # O(n^2) runtime and O(n) Space\n dp = defaultdict(list)\n def dfs(prev):\n if (prev) in dp:\n return dp[prev]\n temp = []\n for curr in range(prev +1, n):\n cond1 = groups[prev] != groups[curr] \n cond2 = len(words[prev]) == len(words[curr])\n cond3 = sum(a!=b for a, b in zip(words[prev], words[curr]))== 1\n if cond1 and cond2 and cond3:\n temp = max(dfs(curr), temp, key = len)\n dp[prev] = [words[prev]] + temp\n return dp[prev]\n return max([dfs(i) for i in range(n)], key = len)\n """\n O(n^2) Space and Runtime\n dp = defaultdict(list)\n\n def dfs(prev, idx):\n if idx == n:\n return [words[prev]]\n if (prev, idx) in dp:\n return dp[(prev, idx)]\n cond1 = groups[prev] != groups[idx] \n cond2 = len(words[prev]) == len(words[idx])\n cond3 = sum(a!=b for a, b in zip(words[prev], words[idx]))== 1\n if cond1 and cond2 and cond3:\n dp[(prev, idx)] = [words[prev]] + dfs(idx, idx+1)\n dp[(prev, idx)] = max(dfs(prev, idx+1), dp[(prev, idx)], key = len)\n return dp[(prev, idx)]\n return max([dfs(i,i) for i in range(n)], key = len)\n \n """\n \n``` | 0 | 0 | ['Python3'] | 0 |
longest-unequal-adjacent-groups-subsequence-ii | C++ || EASY || CLEAN || RECURSIVE DP || MEMOIZATION | c-easy-clean-recursive-dp-memoization-by-cmz2 | \n\n# Code\n\nclass Solution {\npublic:\n vector<int> t(int i,map<int,vector<int>> &dp,int n,vector<string> &a,vector<int> &g)\n {\n if(dp.count(i) | Gauravgeekp | NORMAL | 2023-10-20T09:37:30.746735+00:00 | 2023-10-20T09:37:30.746760+00:00 | 11 | false | \n\n# Code\n```\nclass Solution {\npublic:\n vector<int> t(int i,map<int,vector<int>> &dp,int n,vector<string> &a,vector<int> &g)\n {\n if(dp.count(i)>0) return dp[i];\n\n vector<int> r;\n for(int j=i+1;j<n;j++)\n {\n bool b=1;\n int c=0;\n if(a[i].size()!=a[j].size()) \n b=0;\n\n for(int k=0;k<a[i].size();k++)\n if(a[i][k]!=a[j][k])\n c++;\n\n if(c>1 || c==0) b=0;\n\n if(g[i]!=g[j] && b)\n if(r.size()<=t(j,dp,n,a,g).size())\n r=t(j,dp,n,a,g);\n } \n dp[i]=r;\n dp[i].push_back(i);\n return dp[i];\n } \n\n vector<string> getWordsInLongestSubsequence(int n, vector<string>& w, vector<int>& g) {\n map<int,vector<int>> dp;\n vector<int> a;\n for(int i=0;i<n;i++)\n {\n vector<int> r=t(i,dp,n,w,g);\n if(a.size()<=r.size())\n a=r;\n }\n sort(a.begin(),a.end());\n vector<string> ans;\n \n for(auto i : a)\n ans.push_back(w[i]);\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
longest-unequal-adjacent-groups-subsequence-ii | [Python3] Length-wise DP | python3-length-wise-dp-by-cava-dp84 | \nclass Solution:\n def getWordsInLongestSubsequence(self, n: int, words: List[str], groups: List[int]) -> List[str]:\n length_groups = [[] for _ in r | cava | NORMAL | 2023-10-20T06:27:48.066674+00:00 | 2023-10-20T06:27:48.066697+00:00 | 4 | false | ```\nclass Solution:\n def getWordsInLongestSubsequence(self, n: int, words: List[str], groups: List[int]) -> List[str]:\n length_groups = [[] for _ in range(11)]\n for i, w in enumerate(words): length_groups[len(w)].append((w, groups[i]))\n def calHamming(w1, w2): return sum(1 for c1, c2 in zip(w1, w2) if c1 != c2)\n def getLongestSubHamming(wgs):\n n = len(wgs)\n dp = [[wgs[i][0]] for i in range(n)]\n for i in range(1, n):\n for j in range(i):\n if calHamming(wgs[i][0], wgs[j][0]) != 1 or wgs[i][1] == wgs[j][1]: continue\n if len(dp[j]) + 1 > len(dp[i]): dp[i] = dp[j] + [wgs[i][0]]\n return max(dp, key=lambda x: len(x), default=\'\')\n return max([getLongestSubHamming(wgs) for wgs in length_groups], key=lambda x: len(x))\n``` | 0 | 0 | ['Python3'] | 0 |
longest-unequal-adjacent-groups-subsequence-ii | Java Simple Solution | TC - O(N^2) | SC - O(N) | java-simple-solution-tc-on2-sc-on-by-omk-270k | \n\n# Complexity\n- Time complexity: O(N^2)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(N)\n Add your space complexity here, e.g. O(n) | Omkar_Alase | NORMAL | 2023-10-20T05:34:08.970528+00:00 | 2023-10-20T05:34:08.970558+00:00 | 8 | false | \n\n# Complexity\n- Time complexity: O(N^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n private boolean check(String word1,String word2){\n if(word1.length() != word2.length()) return false;\n int n = word1.length();\n int cnt = 0;\n for(int i = 0;i < n;i++){\n if(word1.charAt(i) != word2.charAt(i)){\n cnt++;\n }\n }\n\n return cnt == 1;\n }\n public List<String> getWordsInLongestSubsequence(int n, String[] words, int[] groups) {\n int[][] tracker = new int[2][n];\n List<String> ans = new ArrayList<>();\n Arrays.fill(tracker[0],0);\n Arrays.fill(tracker[1],-1);\n tracker[1][0] = -1;\n int startIndex = 0;\n int size = 0;\n for(int i = 0;i < n;i++){\n int[] temp = {0,-1};\n for(int j = i - 1;j >= 0;j--){\n boolean flag = check(words[i],words[j]) && (groups[i] != groups[j]);\n if(flag){\n if(tracker[0][j] > temp[0]){\n temp[0] = tracker[0][j];\n temp[1] = j;\n }\n }\n }\n\n tracker[0][i] = temp[0] + 1;\n tracker[1][i] = temp[1];\n\n if(tracker[0][i] > size){\n size = tracker[0][i];\n startIndex = i;\n }\n }\n while(startIndex != -1){\n ans.add(words[startIndex]);\n startIndex = tracker[1][startIndex];\n }\n Collections.reverse(ans);\n return ans;\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
longest-unequal-adjacent-groups-subsequence-ii | LIS Variation | lis-variation-by-subhash_pabbineedi-j6ec | Intuition\nhttps://www.youtube.com/watch?v=IFfYfonAFGc&ab_channel=takeUforward\n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n | subhash_pabbineedi | NORMAL | 2023-10-18T19:39:58.916436+00:00 | 2023-10-18T19:39:58.916463+00:00 | 7 | false | # Intuition\nhttps://www.youtube.com/watch?v=IFfYfonAFGc&ab_channel=takeUforward\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 check_ham(string word1,string word2)\n {\n if(word1.size()!=word2.size())\n {\n return -1;\n }\n int len = 0;\n int n = word1.size();\n for(int i = 0;i<n;i++)\n {\n if(word1[i]!=word2[i])\n {\n len++;\n }\n }\n return len;\n }\n // vector<string> ans;\n // int maxi = 0;\n // void solve(int i,int prev,int n,vector<string>& ds,vector<string>& words, vector<int>& group)\n // {\n // if(i == n)\n // {\n // if(ds.size()>maxi)\n // {\n // ans = ds;\n // maxi = ds.size();\n // }\n // return;\n // }\n // //base cases\n // int pick = 0;\n // if((prev == -1)||(group[i]!=group[prev])&&(check_ham(words[i],words[prev])))\n // {\n // ds.push_back(words[i]);\n // solve(i+1,i,n,ds,words,group);\n // ds.pop_back();\n // }\n // solve(i+1,prev,n,ds,words,group);\n \n // }\n vector<string> getWordsInLongestSubsequence(int n, vector<string>& words, vector<int>& groups) {\n \n // int prev = 0;\n // vector<int> temp;\n // temp.push_back(0);\n // for(int i = 1;i<n;i++)\n // {\n // if(groups[i]!=groups[prev] && words[i].size() == words[prev].size())\n // {\n // if(check_ham(words[i],words[prev]) == 1)\n // {\n // temp.push_back(i);\n // prev = i;\n // }\n // }\n // }\n // vector<string> ans;\n // for(int i = 0;i<temp.size();i++)\n // {\n // ans.push_back(words[temp[i]]);\n // }\n // return ans;\n // vector<string> ds;\n // solve(0,-1,n,ds,words,groups);\n // return ans;\n vector<int> dp(n,1);\n vector<int> hash(n,1);\n for(int i = 0;i<n;i++)\n {\n hash[i] = i;\n for(int j = 0;j<i;j++)\n {\n if(groups[i]!=groups[j]&&(check_ham(words[i],words[j]) == 1)&&(1+dp[j])>dp[i])\n {\n dp[i] = 1+dp[j];\n hash[i] = j;\n }\n }\n }\n int ans = -1;\n int lastIndex = -1;\n for(int i = 0;i<n;i++)\n {\n if(dp[i] >= ans)\n {\n ans = dp[i];\n lastIndex = i;\n }\n }\n \n vector<string> temp;\n temp.push_back(words[lastIndex]);\n\n while(hash[lastIndex]!=lastIndex)\n {\n lastIndex = hash[lastIndex];\n temp.push_back(words[lastIndex]);\n }\n reverse(temp.begin(),temp.end());\n return temp;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
longest-unequal-adjacent-groups-subsequence-ii | Top down 2 d DP | top-down-2-d-dp-by-hail-cali-x280 | Intuition\n Describe your first thoughts on how to solve this problem. \n\nIt is Take and Not Take questions\n\nit\'s constraints is O((16)^2 * 10) == O(m^2 * | hail-cali | NORMAL | 2023-10-18T12:47:03.942304+00:00 | 2023-10-18T12:47:03.942328+00:00 | 15 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nIt is `Take and Not Take` questions\n\nit\'s constraints is O((16)^2 * 10) == O(m^2 * n) .\n\nTrying to calculate all `pairs (i, j)` which is ( i< j) and met constraints.\n\nChoose longest subarray and attach one by one. \n\n\n\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`O(m^2 * n)`\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n`O(m*m)` \n\n# Code\n```\nclass Solution:\n def getWordsInLongestSubsequence(self, n: int, words: List[str], groups: List[int]) -> List[str]:\n \n @cache\n def dp(i, prev):\n # you can use memo[i][prev] insteed, \n # just save reseult with memo\n # return memo[i][prev] if memo[i][prev] != init_value ;\n\n # end of array, return empty list\n if i == n:\n return []\n \n # calculate pair (next, prev)\n not_take = dp(i+1, prev)\n\n # prouning if constraints not met.\n if len(words[prev])!= len(words[i]) or groups[i] == groups[prev] :\n return not_take\n \n # calculate hamming dinstance.\n d = 0\n for a, b in zip(words[i], words[prev]):\n if d > 1:\n return not_take\n if a != b:\n d += 1\n\n # if constraints met, combine two subarray.\n take = []\n if d == 1:\n take = [words[i]] + dp(i+1, i)\n\n # return longest subarray\n if len(take) <= len(not_take):\n return not_take\n return take\n \n\n res = []\n for i in range(n-1, -1, -1):\n\n # make pair all (i, i+1) and combine them.\n subarray = [words[i]] + dp(i+1, i) \n \n # find longest subarray \n if len(subarray) >= len(res):\n res = subarray\n\n return res\n\n\n\n``` | 0 | 0 | ['Python3'] | 0 |
longest-unequal-adjacent-groups-subsequence-ii | EASY SOLTUION || ITREATIVE METHOD | easy-soltuion-itreative-method-by-bineet-phe7 | Intuition\n Describe your first thoughts on how to solve this problem. \nTHIS PROBLEM IS RELATED TO STANDERED PROBLEM LONGEST INCREASING SUBSEQUENCE WE HAVE TO | bineetkathait1111 | NORMAL | 2023-10-17T18:58:24.129696+00:00 | 2023-10-17T18:58:24.129723+00:00 | 4 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTHIS PROBLEM IS RELATED TO STANDERED PROBLEM LONGEST INCREASING SUBSEQUENCE WE HAVE TO THINK LIKE THAT\n# Approach\n<!-- Describe your approach to solving the problem. -->\nAT CURRENT INDEX WE HAVE TO FIND THE LONGEST INCREASING SUBSEQUENCE FROM LEFT TO RIGHT WHICH SATISFY THE GIVEN CONDITIONS\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N^2)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N)\n# Code\n```\nclass Solution {\npublic:\nbool check(string &a,string &b)\n {\n int n=a.size()-1,m=b.size()-1;\n if(n!=m)\n return 0;\n int c=0;\n while(n>=0)\n {\n if(a[n]!=b[n])\n c++;\n n--;\n }\n return c==1;\n}\n\n vector<string> getWordsInLongestSubsequence(int n, vector<string>& words, vector<int>& groups) {\n vector<int>index(n+1,-1);\n vector<int>len(n+1,1);\n int maxlength=1 , maxindex=0;\n for(int i=0; i<n; i++){\n for(int j=i-1; j>=0; j--){\n string s1=words[i] , s2=words[j];\n if(groups[i]!=groups[j]){\n if(check(s1,s2)){\n if(len[j]+1>len[i]){\n len[i]=1+len[j];\n index[i]=j;\n if(len[i]>maxlength){\n maxlength=len[i];\n maxindex=i;\n }\n }\n }\n }\n }\n }\n vector<string>ans;\n ans.push_back(words[maxindex]);\n while(index[maxindex]!=-1){\n ans.push_back(words[index[maxindex]]);\n maxindex=index[maxindex];\n }\n reverse(ans.begin(),ans.end());\n return ans;\n }\n};\n``` | 0 | 0 | ['Array', 'String', 'C++'] | 0 |
longest-unequal-adjacent-groups-subsequence-ii | C++ Solution || Similar to printing LIS | c-solution-similar-to-printing-lis-by-va-ot06 | \nclass Solution {\npublic:\n bool check(string s,string t){\n int i,c=0;\n for(i=0;i<s.size();i++){\n if(s[i]!=t[i]){\n | vanapallikavyasri | NORMAL | 2023-10-17T16:35:36.075087+00:00 | 2023-10-17T16:35:36.075119+00:00 | 3 | false | ```\nclass Solution {\npublic:\n bool check(string s,string t){\n int i,c=0;\n for(i=0;i<s.size();i++){\n if(s[i]!=t[i]){\n c++;\n }\n }\n return c==1;\n }\n vector<string> getWordsInLongestSubsequence(int n, vector<string>& w, vector<int>& g) {\n int i,j,res=0;\n vector<int>hash(n);\n vector<int>dp(n,1);\n for(i=0;i<n;i++){\n hash[i]=i;\n for(j=0;j<i;j++){\n if(g[i]!=g[j] && w[i].size()==w[j].size() && check(w[i],w[j])){\n if(dp[i]<dp[j]+1){\n dp[i]=dp[j]+1;\n hash[i]=j;\n }\n }\n }\n \n }\n int p=-1;\n for(i=0;i<dp.size();i++){\n if(dp[i]>res){\n p=i;\n res=dp[i];\n }\n }\n vector<string>v;\n v.push_back(w[p]);\n \n while(hash[p]!=p){\n p=hash[p];\n v.push_back(w[p]);\n \n \n }\n reverse(v.begin(),v.end());\n return v;\n \n \n \n }\n};\n``` | 0 | 0 | [] | 0 |
longest-unequal-adjacent-groups-subsequence-ii | C++ - Dynamic Programming | c-dynamic-programming-by-mumrocks-dv6q | Intuition\nKeep track of max sequence formed at index. Max subsequence at index i is found by performing group id check and checking hamming distance between al | MumRocks | NORMAL | 2023-10-17T16:05:43.489014+00:00 | 2023-10-17T16:05:43.489040+00:00 | 4 | false | # Intuition\nKeep track of max sequence formed at index. Max subsequence at index i is found by performing group id check and checking hamming distance between all previous elements. \n\n\n\n# Code\n```\nclass Solution {\n bool IsHammingDistanceOne(const string& f, const string& s){\n int hc=0;\n if (f.size()!=s.size()) return false;\n for (int i=0;i<f.size()&&hc!=2;i++) hc += (f[i]!=s[i]);\n return hc==1;\n }\npublic:\n vector<string> getWordsInLongestSubsequence(int n, vector<string>& words, vector<int>& groups) {\n int sz = words.size();\n vector<int> parent(sz,-1);\n vector<int> rank(sz,1);\n int t=1;\n for (int i=1;i<sz;i++){\n t=1;\n for (int j=i-1;j>=0;j--){\n if (groups[i]==groups[j]) continue;\n if (IsHammingDistanceOne(words[i],words[j])){\n if (rank[i]<rank[j]+1){\n rank[i]=rank[j]+1;\n parent[i]=j;\n }\n }\n }\n }\n int maxRank=0,maxRankIndex=-1;\n for (int i=0;i<sz;i++){\n if (rank[i]>maxRank) maxRank=rank[i],maxRankIndex=i;\n }\n vector<string> ans;\n while (maxRankIndex!=-1){\n ans.push_back(words[maxRankIndex]);\n maxRankIndex = parent[maxRankIndex];\n }\n reverse(ans.begin(),ans.end());\n return ans;\n }\n \n};\n``` | 0 | 0 | ['C++'] | 0 |
find-the-student-that-will-replace-the-chalk | O(n) solution beats 100 % in all languages | on-solution-beats-100-in-all-languages-b-r34m | Intuition\n \nTo start, let\'s first understand what the question is really asking we have a classroom of students each with a specific chalk requirement. The t | Solution_Assist | NORMAL | 2024-09-01T18:59:22.734835+00:00 | 2024-09-02T17:25:34.659108+00:00 | 31,100 | false | ## Intuition\n \nTo start, let\'s first understand what the question is really asking we have a classroom of students each with a specific chalk requirement. The teacher goes around the room and starts giving chalk to the students until they run out. Our job is to find out which student will be the one to say, "Hey, we need more chalk!" \n>- Cyclic Nature: The teacher starts again from the first student after the last one creating a cyclic pattern which basically means we need to consider how the chalk is distributed in multiple rounds, not just one.\n>- Chalk Consumption: Each student has a different chalk consumption rate (chalk[i]). If a student\'s required chalk exceeds the remaining chalk that student needs to replace the chalk which is the problem\'s stopping condition.\n\nAt first this can appear like a straightforward simulation problem where we could just go through the motions subtracting chalk as we go until we hit a negative number But no the constraints tell us that we could have up to 10^5 students and up to 10^9 pieces of chalk. If we tried to simulate this naively we might end up going around the classroom thousands or even millions of times before running out of chalk. \n\nWell now since we know we\'re going to be repeating the same pattern of chalk distribution over and over as each time the teacher completes a round they will return to the first student and if we can calculate the total amount of chalk required for one full round then we can use this information to "skip" through the unnecessary repetitions and focus on the point where the chalk actually runs out so we will use modular arithmetic i.e If we can figure out how much chalk is used in one complete round of the classroom, we can use the modulus operator to fast-forward through most of the repetitions. Try to understand that the total amount of chalk used in one complete cycle (from student 0 to student n-1) is fixed. so if k (the total chalk available) is greater than this sum we don\'t need to simulate every round Instead we can reduce the problem size by considering the remainder of k after subtracting full cycles this is where modular arithmetic is important instead of simulating each student\'s use of chalk over multiple rounds we can calculate how much chalk remains after several full cycles, focusing only on the "partial" cycle that causes the chalk to run out.\n\nLet\'s think about this with a simpler example. Say we have 3 students who need 2, 3, and 4 pieces of chalk respectively. If we start with 20 pieces of chalk, how many complete rounds can we make? We\'d use 2 + 3 + 4 = 9 chalk per round so we can complete 2 full rounds (using 18 chalk) with 2 pieces left over. Those leftover 2 pieces are what we really care about as they determine where in the third round we\'ll run out. Let\'s talk about calculating the total chalk used in one round. By summing up all the values in our chalk array, we get this important information. Then, using the modulus operator with our initial chalk amount, we can immediately get to the round where we\'ll run out.\n\nBut remember, we\'re not just looking for the round where we run out we also need to know exactly which student will be the one to run out. This means we can\'t just do a single modulus operation and say we got the results. We need to actually simulate that final partial round. That is why lets talk about a single pass through the array to simulate the final round, we start from the first student and we go student by student and begin subtracting their chalk requirement from the remaining chalk(the result of our modulus operation). Continue this process until you find the first student whose requirement exceeds the remaining chalk. The moment we can\'t meet a student\'s requirement this student will be the one who will say, "Hey, we need more chalk!" \n\nNow, you might be thinking why even bother with the modulus operation at all Why cant we just simulate from the beginning well We use the modulus to quickly bypass all the complete rounds, then switch to simulation for the final important round. This gives us both speed and accuracy. By using the modulus we\'re essentially "wrapping" our chalk distribution around the classroom it\'s as if we\'re working with a circular array where the end connects back to the beginning. This circular nature mirrors the problem description perfectly, the teacher starts over at student 0 after reaching the end.\n\nLet\'s talk about some edge cases for ex if we have exactly enough chalk for a whole number of rounds In this case, our modulus operation will give us 0 and we\'ll return 0 (the first student) as our answer. This makes sense - if we have exactly enough chalk we\'ll run out just as we\'re about to start a new round, another case to consider is when one student uses significantly more chalk than the others for ex if we have [1, 1, 1000] as our chalk array in this case our modulus operation becomes important without it we might waste a lot of time simulating the first two students over and over before finally hitting the third, this solution also handles the case where we have a very large amount of initial chalk efficiently. Even if we start with billions of pieces of chalk, our modulus operation cuts that down to a manageable number right away.\n\nAnother thing is we willbe using long for the totla chalk sum and a doubt you might have is why we use a long for this but keep using int for the remaining chalk well this is a subtle but important point as the total sum could potentially exceed the range of an int if we have many students using a lot of chalk. But after the modulus operation we\'re guaranteed to have a value less than the sum which fits safely in an int.\n\nThe approach also has the advantage of being very space-efficient. We just have a few variables to keep track of our sums and remainders. This means our space complexity is O(1), which is as good as it gets and in terms of time complexity, we will be making two passes through the array once to calculate the total, and once to simulate the final round this will give us a linear time complexity of O(n), where n is the number of students. Considering that we could potentially be dealing with billions of pieces of chalk, reducing this to a linear operation is a significant optimization.\n\n## Approach\n#### 1. Recognizing the Cycle\n\nThe distribution of chalk forms a repeating cycle. If we have enough chalk for multiple complete cycles, we don\'t need to simulate each one individually. So we will use modular arithmetic to "fast-forward" through complete cycles.\n\n#### 2. Calculating Total Chalk per Cycle\n\nBy summing the chalk requirements of all students, we can find out how much chalk is needed for one complete cycle. This sum is important for our modular arithmetic approach.\n\n#### 3. Using Modular Arithmetic\n\nOnce we know the total chalk per cycle, we can use the modulus operator to find out how much chalk remains after all complete cycles. This remainder is what we\'ll focus on in our final calculation.\n\n#### 4. Simulating the Final (Partial) Cycle\n\nWith the remaining chalk after complete cycles, we simulate the distribution one last time to find the student who will run out.\n\n#### Pseudo-code\n\n\n```\nfunction chalkReplacer(chalk[], initialChalk):\n totalChalkNeeded = 0\n for each studentChalk in chalk:\n totalChalkNeeded += studentChalk\n \n remainingChalk = initialChalk % totalChalkNeeded\n \n for studentIndex from 0 to length(chalk) - 1:\n if remainingChalk < chalk[studentIndex]:\n return studentIndex\n remainingChalk -= chalk[studentIndex]\n \n return 0\n```\n\n### Step 1: Calculate Total Chalk per Cycle\n\n```\ntotalChalkNeeded = 0\nfor each studentChalk in chalk:\n totalChalkNeeded += studentChalk\n```\n\nIn this step, we sum up the chalk requirements of all students. This gives us the total amount of chalk needed for one complete cycle through all students.\n\n**Because** \n- It allows us to treat the problem as a series of complete cycles plus a partial cycle.\n- We can use this sum to determine how many complete cycles we can make with the initial chalk.\n\n\nIf we have `n` students, and `chalk[i]` represents the chalk needed by the i-th student, then:\n\n```\ntotalChalkNeeded = chalk[0] + chalk[1] + ... + chalk[n-1]\n```\n\nThis sum represents one complete "revolution" of chalk distribution.\n\n### Step 2: Apply Modular Arithmetic\n\n```\nremainingChalk = initialChalk % totalChalkNeeded\n```\n\n We use the modulus operator to determine how much chalk remains after all complete cycles.\n\n**Because**\n- If `initialChalk` is less than `totalChalkNeeded`, the result is just `initialChalk`.\n- If `initialChalk` is greater than `totalChalkNeeded`, the result tells us how much chalk is left after the last complete cycle.\n\n\nLet\'s say `initialChalk = 100` and `totalChalkNeeded = 30`. We can express this as:\n\n```\n100 = 3 * 30 + 10\n```\n\nThis means we can complete 3 full cycles, and we\'re left with 10 pieces of chalk to distribute in the partial cycle. The modulus operation `100 % 30 = 10` gives us this remainder directly, allowing us to skip simulating the three complete cycles.\n\n### Step 3: Simulate the Final (Partial) Cycle\n\n```\nfor studentIndex from 0 to length(chalk) - 1:\n if remainingChalk < chalk[studentIndex]:\n return studentIndex\n remainingChalk -= chalk[studentIndex]\n```\n\nNow that we\'ve skipped all complete cycles, we simulate the distribution of the remaining chalk.\n\n**Because**\n- We iterate through the students in order.\n- For each student, we check if we have enough chalk to meet their requirement.\n- If we don\'t have enough, we\'ve found our answer: this student will need to replace the chalk.\n- If we do have enough, we subtract their requirement and move to the next student.\n\n**Why do we need this step?**\nThe modulus operation tells us how much chalk is left, but not which student will run out. This final simulation is necessary to pinpoint the exact student.\n\n### Step 4: Handle Edge Cases\n\n```\nreturn 0\n```\n\nThis final return statement handles an important edge case: when we have exactly enough chalk for a whole number of complete cycles.\n\n**Why is this necessary?**\n- If `initialChalk` is a multiple of `totalChalkNeeded`, the modulus operation will return 0.\n- In this case, we\'ve used all the chalk exactly as we finish a cycle.\n- The next student to need chalk (which would be the first student) is the one who will ask for more.\n\n### Complexity Analysis\n\n#### Time Complexity: O(n)\n\n- We make two passes through the `chalk` array:\n 1. To calculate `totalChalkNeeded`\n 2. To simulate the final partial cycle\n- Each pass is O(n), where n is the number of students.\n- The modulus operation is O(1).\n- Therefore, the overall time complexity is O(n).\n\n\nEven if we have billions of pieces of chalk, we only need to iterate through the students twice. The modulus operation allows us to "skip" all the complete cycles in constant time.\n\n#### Space Complexity: O(1)\n\n- We only use a few variables (`totalChalkNeeded`, `remainingChalk`, `studentIndex`) regardless of the input size.\n- We don\'t create any data structures that grow with the input.\n- Therefore, the space complexity is constant, or O(1).\n\n## Handling Large Numbers\n\nIn the actual implementation, we need to be careful about integer overflow. The sum of all chalk requirements could exceed the maximum value of a 32-bit integer.\n\n```\n// Use a long (64-bit integer) for totalChalkNeeded\nlong totalChalkNeeded = 0\nfor each studentChalk in chalk:\n totalChalkNeeded += studentChalk\n\n// Cast back to int after modulus operation\nint remainingChalk = (int)(initialChalk % totalChalkNeeded)\n```\n\n**Why is this necessary?**\n- If we have many students or large chalk requirements, `totalChalkNeeded` could exceed 2^31 - 1 (max value for a 32-bit int).\n- Using a 64-bit integer (long) for this calculation prevents overflow.\n- After the modulus operation, the result is guaranteed to be less than `totalChalkNeeded`, so it\'s safe to cast back to an int.\n\n\n### CODE\n\n```Python []\nclass Solution:\n def chalkReplacer(self, chalk: List[int], initialChalkPieces: int) -> int:\n totalChalkNeeded = sum(chalk)\n remainingChalk = initialChalkPieces % totalChalkNeeded\n \n for studentIndex, studentChalkUse in enumerate(chalk):\n if remainingChalk < studentChalkUse:\n return studentIndex\n remainingChalk -= studentChalkUse\n \n return 0\n\n\n\n\ndef kdsmain():\n input_data = sys.stdin.read().strip()\n lines = input_data.splitlines()\n \n num_test_cases = len(lines) // 2\n results = []\n\n for i in range(num_test_cases):\n chalk = json.loads(lines[i*2])\n initialChalkPieces = int(lines[i*2 + 1])\n \n result = Solution().chalkReplacer(chalk, initialChalkPieces)\n results.append(str(result))\n\n with open(\'user.out\', \'w\') as f:\n for result in results:\n f.write(f"{result}\\n")\n\nif __name__ == "__main__":\n kdsmain()\n exit(0)\n\n\n```\n```Java []\n\nclass Solution {\n public int chalkReplacer(int[] chalk, int initialChalkPieces) {\n long totalChalkNeeded = 0;\n for (int studentChalkUse : chalk) {\n totalChalkNeeded += studentChalkUse;\n }\n \n int remainingChalk = (int)(initialChalkPieces % totalChalkNeeded);\n \n for (int studentIndex = 0; studentIndex < chalk.length; studentIndex++) {\n if (remainingChalk < chalk[studentIndex]) {\n return studentIndex;\n }\n remainingChalk -= chalk[studentIndex];\n }\n \n return 0; \n }\n}\n\n```\n```C++ []\nclass Solution {\npublic:\n int chalkReplacer(vector<int>& chalk, int initialChalkPieces) {\n long long totalChalkNeeded = 0;\n for (int studentChalkUse : chalk) {\n totalChalkNeeded += studentChalkUse;\n }\n \n int remainingChalk = initialChalkPieces % totalChalkNeeded;\n \n for (int studentIndex = 0; studentIndex < chalk.size(); studentIndex++) {\n if (remainingChalk < chalk[studentIndex]) {\n return studentIndex;\n }\n remainingChalk -= chalk[studentIndex];\n }\n \n return 0;\n }\n};\nstatic const int kds = []() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n cout.tie(nullptr);\n return 0;\n}();\n\n```\n```C# []\n\npublic class Solution {\n public int ChalkReplacer(int[] chalk, int k) {\n long totalChalkNeeded = 0;\n foreach (int studentChalkUse in chalk) {\n totalChalkNeeded += studentChalkUse;\n }\n \n int remainingChalk = (int)(k % totalChalkNeeded);\n \n for (int studentIndex = 0; studentIndex < chalk.Length; studentIndex++) {\n if (remainingChalk < chalk[studentIndex]) {\n return studentIndex;\n }\n remainingChalk -= chalk[studentIndex];\n }\n \n return 0;\n }\n}\n\n```\n\n```Go []\n\nfunc chalkReplacer(chalk []int, initialChalkPieces int) int {\n totalChalkNeeded := 0\n for _, studentChalkUse := range chalk {\n totalChalkNeeded += studentChalkUse\n }\n \n remainingChalk := initialChalkPieces % totalChalkNeeded\n \n for studentIndex, studentChalkUse := range chalk {\n if remainingChalk < studentChalkUse {\n return studentIndex\n }\n remainingChalk -= studentChalkUse\n }\n \n return 0\n}\n\n```\n```kotlin []\nclass Solution {\n fun chalkReplacer(chalk: IntArray, k: Int): Int {\n val totalChalkNeeded = chalk.map { it.toLong() }.sum()\n \n var remainingChalk = (k % totalChalkNeeded).toInt()\n \n for (studentIndex in chalk.indices) {\n if (remainingChalk < chalk[studentIndex]) {\n return studentIndex\n }\n remainingChalk -= chalk[studentIndex]\n }\n \n return 0\n }\n}\n\n```\n```Rust []\nimpl Solution {\n pub fn chalk_replacer(chalk: Vec<i32>, initial_chalk_pieces: i32) -> i32 {\n let total_chalk_needed: i64 = chalk.iter().map(|&x| x as i64).sum();\n let mut remaining_chalk = (initial_chalk_pieces as i64 % total_chalk_needed) as i32;\n \n for (student_index, &student_chalk_use) in chalk.iter().enumerate() {\n if remaining_chalk < student_chalk_use {\n return student_index as i32;\n }\n remaining_chalk -= student_chalk_use;\n }\n \n 0\n }\n}\n\n\n```\n\n```TypeScript []\nfunction chalkReplacer(chalk: number[], k: number): number {\n const totalChalkNeeded = chalk.reduce((sum, studentChalkUse) => sum + BigInt(studentChalkUse), 0n);\n \n let remainingChalk = Number(BigInt(k) % totalChalkNeeded);\n \n for (let studentIndex = 0; studentIndex < chalk.length; studentIndex++) {\n if (remainingChalk < chalk[studentIndex]) {\n return studentIndex;\n }\n remainingChalk -= chalk[studentIndex];\n }\n \n return 0;\n}\n\n\n```\n```JavaScript []\n\n/**\n * @param {number[]} chalk\n * @param {number} initialChalkPieces\n * @return {number}\n */\nvar chalkReplacer = function(chalk, initialChalkPieces) {\n let totalChalkNeeded = chalk.reduce((sum, studentChalkUse) => sum + studentChalkUse, 0);\n let remainingChalk = initialChalkPieces % totalChalkNeeded;\n \n for (let studentIndex = 0; studentIndex < chalk.length; studentIndex++) {\n if (remainingChalk < chalk[studentIndex]) {\n return studentIndex;\n }\n remainingChalk -= chalk[studentIndex];\n }\n \n return 0;\n};\n\n``` | 70 | 1 | ['Simulation', 'Prefix Sum', 'C++', 'Java', 'Go', 'TypeScript', 'Python3', 'Rust', 'JavaScript', 'C#'] | 13 |
find-the-student-that-will-replace-the-chalk | Two Tricks | two-tricks-by-votrubac-lmk9 | Trick 1: k can be too big, so skip full circles by only considering k % sum(chalk). \nTrick 2: sum(chalk) array can exceed INT_MAX, use long (0l) to accumulate. | votrubac | NORMAL | 2021-06-12T16:49:47.809232+00:00 | 2021-06-12T18:55:34.958511+00:00 | 7,681 | false | Trick 1: `k` can be too big, so skip full circles by only considering `k % sum(chalk)`. \nTrick 2: `sum(chalk)` array can exceed `INT_MAX`, use `long` (`0l`) to accumulate.\n\n**C++**\n```cpp\nint chalkReplacer(vector<int>& chalk, int k) {\n k %= accumulate(begin(chalk), end(chalk), 0l);\n for (int i = 0; i < chalk.size(); ++i)\n if ((k -= chalk[i]) < 0)\n return i;\n return 0;\n}\n``` | 70 | 0 | ['C'] | 15 |
find-the-student-that-will-replace-the-chalk | Python 1-line | python-1-line-by-lee215-jh2p | Solution 1\nTime O(n)\nSpace O(1)\npy\n def chalkReplacer(self, A, k):\n k %= sum(A)\n for i, a in enumerate(A):\n if k < a:\n | lee215 | NORMAL | 2021-06-12T16:04:34.680743+00:00 | 2021-06-12T16:04:34.680767+00:00 | 4,136 | false | # **Solution 1**\nTime O(n)\nSpace O(1)\n```py\n def chalkReplacer(self, A, k):\n k %= sum(A)\n for i, a in enumerate(A):\n if k < a:\n return i\n k -= a\n return 0\n```\n# **Solution 2**\nTime O(n)\nSpace O(n)\n```py\n def chalkReplacer(self, A, k):\n return bisect.bisect(list(accumulate(A)), k % sum(A))\n```\n | 46 | 7 | [] | 12 |
find-the-student-that-will-replace-the-chalk | ✅Easy and Clean Code (C++ / Java)✅ | easy-and-clean-code-c-java-by-sourav_n06-rk66 | Here\u2019s a refined version of the explanation:\n\n### Intuition\nThe problem is about determining which student will be the one to use up the last piece of c | sourav_n06 | NORMAL | 2024-09-02T03:20:35.680568+00:00 | 2024-09-02T03:20:35.680587+00:00 | 6,034 | false | Here\u2019s a refined version of the explanation:\n\n### Intuition\nThe problem is about determining which student will be the one to use up the last piece of chalk. Since the chalk usage pattern is repetitive, if `k` (the initial amount of chalk) is larger than the total chalk used in one complete cycle, we can simplify the problem by reducing `k` to a smaller equivalent value within the cycle. This allows us to efficiently find the student who will deplete the remaining chalk.\n\n### Approach\n1. **Calculate the Total Chalk Used per Cycle**: First, compute the sum of all elements in the `chalk` array using `accumulate`. This gives us the total chalk used by all students in one full cycle.\n2. **Reduce `k` Within One Cycle**: If `k` exceeds the total chalk sum, reduce it by performing `k %= accSum`. This step reduces `k` to an equivalent value within the bounds of a single cycle, making the problem manageable.\n3. **Identify the Responsible Student**: Iterate through the `chalk` array, subtracting each student\u2019s chalk usage from `k`. The first student whose chalk requirement is greater than the remaining `k` is the one who will use up the last piece of chalk.\n\n### Complexity\n- **Time complexity**: The time complexity is $$O(n)$$, where `n` is the number of students (size of the `chalk` array). We perform one pass to compute the total chalk sum and another to find the responsible student.\n \n- **Space complexity**: The space complexity is $$O(1)$$ because we only use a constant amount of extra space, regardless of the input size.\n# Code\n```cpp []\nclass Solution {\npublic:\n int chalkReplacer(vector<int>& chalk, int k) {\n long long accSum = accumulate(chalk.begin(), chalk.end(), 0LL);\n k %= accSum; \n\n for (int i = 0; i < chalk.size(); ++i) {\n if (chalk[i] > k) {\n return i; \n }\n k -= chalk[i];\n }\n return -1; \n }\n};\n```\n```Java []\nclass Solution {\n public int chalkReplacer(int[] chalk, int k) {\n long accSum = 0;\n for (int c : chalk) accSum += c;\n\n k %= accSum;\n\n for (int i = 0; i < chalk.length; i++) {\n if (chalk[i] > k) return i;\n k -= chalk[i];\n }\n return -1; \n }\n}\n```\n\n | 23 | 0 | ['Array', 'Simulation', 'Prefix Sum', 'C++', 'Java'] | 4 |
find-the-student-that-will-replace-the-chalk | Prefix Sum + Binary Search||45 ms Beats 98.17% | prefix-sum-binary-search45-ms-beats-9817-03ly | Intuition\n Describe your first thoughts on how to solve this problem. \nUse Prefix sum to count sum[i] of pieces of chalks used up to student[i]\nIf k>sum[n-1] | anwendeng | NORMAL | 2024-09-02T01:02:42.627113+00:00 | 2024-09-02T02:19:36.958963+00:00 | 8,287 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUse Prefix sum to count sum[i] of pieces of chalks used up to student[i]\nIf k>sum[n-1]=total sum of chalk, then use modulo arithmetic & binary search.\n\nBoth C++, Python are made.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. construct the prefix sum in `sum` (0-based)\n2. `k%=sum[n-1]`\n3. the answer is `upper_bound(sum.begin(), sum.end(), k)-sum.begin()`\n4. Python code is made which reuses chalk as prefix sum; C++ cannot do it because of overflowing as INT\n5. Python code uses `bisect_right` which is smilar as C++ `std::upper_bound` \n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n# Code||45 ms Beats 98.17%\n```cpp []\nclass Solution {\npublic:\n static int chalkReplacer(vector<int>& chalk, int k) {\n const int n=chalk.size();\n vector<long long> sum(n, chalk[0]);// prefix sum 0-indexed \n for(int i=1; i<n; i++){\n sum[i]=sum[i-1]+chalk[i];\n // cout<<i<<"->"<<sum[i]<<endl;\n }\n k%=sum[n-1];\n // cout<<"k="<<k<<endl;\n\n return upper_bound(sum.begin(), sum.end(), k)-sum.begin();\n }\n};\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 []\nclass Solution:\n def chalkReplacer(self, chalk: List[int], k: int) -> int:\n for i in range(1, len(chalk)):\n chalk[i]+=chalk[i-1]\n k%=chalk[-1]\n return bisect.bisect_right(chalk, k)\n \n``` | 23 | 1 | ['Binary Search', 'Prefix Sum', 'C++', 'Python3'] | 14 |
find-the-student-that-will-replace-the-chalk | [ C++,Python ] Detailed explanation with solution | cpython-detailed-explanation-with-soluti-vev8 | \n# Approach\n\nBruteforce approach is that we simulate this process and \nsince k can be large enough and moving one by one until chalk ends can be a bad idea | itz_pankaj | NORMAL | 2021-06-12T16:02:07.646871+00:00 | 2021-06-13T06:22:48.758881+00:00 | 2,357 | false | \n# Approach\n\nBruteforce approach is that we simulate this process and \nsince k can be large enough and moving one by one until chalk ends can be a bad idea and we have to iterate chalk array multiple times\n\n# Improved version\n \nWhat we do is that we take we take sum of all chalk requires by students and our k becomes k%sum\nby doing this we improve our simulation and we don\'t have to do all those iterations that we are doing in bruteforce approach \nNow we know that in this iteration we get our result surely \nNow we iterate through each chalk require by student and subtract its value from k \nand whenever our k becomes less than 0 that would be our result \n\n\n# Complexity \n\nTime : O(n) here n is length of chalk array \nSpace : O(1)\n\n\n# C++ Soulution\n```\nclass Solution {\npublic:\n int chalkReplacer(vector<int>& chalk, int k) {\n \n size_t sum=0;\n for(auto &x: chalk)\n sum+=x; // getting sum of all chalk values\n \n k = k%sum; // modifyig k so that we dont have to do that much iterations\n \n for(int i=0;i<chalk.size();i++) \n { if( k-chalk[i] < 0) return i;\n else\n k-=chalk[i];\n }\n return chalk.size()-1;\n }\n};\n\n```\n# Python\n```\ndef chalkReplacer(self, chalk: List[int], k: int) -> int:\n\n\tk %= sum(chalk)\n\n\tfor i in range(len(chalk)):\n\t\tif chalk[i]>k:\n\t\t\treturn i\n\t\tk -= chalk[i]\n```\n# Upvote this if this solution is helpful | 23 | 3 | [] | 8 |
find-the-student-that-will-replace-the-chalk | ✔️ PYTHON || EXPLANATION || BINARY SEARCH | python-explanation-binary-search-by-kara-itye | UPVOTE IF HELPFUL\nFind prefix sum first arr [ i ] += arr [ i - 1 ]\n\nThen update k as k = k % arr [ last_element ]\n\nThis will give the last number of chalks | karan_8082 | NORMAL | 2022-06-07T05:04:58.698694+00:00 | 2022-06-07T05:04:58.698734+00:00 | 993 | false | **UPVOTE IF HELPFUL**\nFind prefix sum first **arr [ i ] += arr [ i - 1 ]**\n\nThen update k as **k = k % arr [ last_element ]**\n\nThis will give the last number of chalks left for the last cycle to run.\n\nNow using binary search find the element where chalk are consumed , more specifically , the index with smallest prefix sum greater than k.\n\n```\nclass Solution:\n def chalkReplacer(self, chalk: List[int], k: int) -> int:\n \n for i in range(1,len(chalk)):\n chalk[i]+=chalk[i-1]\n \n k = k % chalk[-1]\n \n l=0\n h=len(chalk)\n \n while (l<h):\n m=(l+h)//2\n \n if chalk[m]==k:\n return m+1\n elif chalk[m]<k:\n l=m+1\n else:\n h=m\n return l\n```\n\n | 17 | 0 | ['Binary Tree', 'Prefix Sum'] | 15 |
find-the-student-that-will-replace-the-chalk | [Java/Python 3] Two passes O(n) codes. | javapython-3-two-passes-on-codes-by-rock-6ron | Java\n1st pass used to avoid possible int overflow.\n\njava\n public int chalkReplacer(int[] chalk, int k) {\n int sum = 0;\n for (int i = 0; i | rock | NORMAL | 2021-06-12T16:11:16.690971+00:00 | 2024-09-03T13:13:51.884271+00:00 | 1,241 | false | **Java**\n1st pass used to avoid possible int overflow.\n\n```java\n public int chalkReplacer(int[] chalk, int k) {\n int sum = 0;\n for (int i = 0; i < chalk.length; ++i) {\n sum += chalk[i];\n k -= chalk[i];\n if (k < 0) {\n return i;\n }\n }\n k %= sum; \n for (int i = 0; i < chalk.length; ++i) {\n k -= chalk[i];\n if (k < 0) {\n return i;\n }\n }\n return -1;\n }\n```\n**Python 3**\n```python\n def chalkReplacer(self, chalk: List[int], k: int) -> int:\n k %= sum(chalk)\n for i, c in enumerate(chalk):\n k -= c\n if k < 0:\n return i\n``` | 14 | 3 | [] | 6 |
find-the-student-that-will-replace-the-chalk | BASIC MATHS ✅✅69_BEATS_100%✅✅🔥Easy Solution🔥With Explanation🔥 | basic-maths-69_beats_100easy-solutionwit-a3hw | Intuition\n Describe your first thoughts on how to solve this problem. \nwe need to find out where the chalk runs out \nwe need to find the remainder of the cha | srinivas_bodduru | NORMAL | 2024-09-02T02:32:57.533016+00:00 | 2024-09-02T02:32:57.533049+00:00 | 4,153 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nwe need to find out where the chalk runs out \nwe need to find the remainder of the chalk with the total chalk needed by the studnets to remove unwanted cycles \n# Approach\n<!-- Describe your approach to solving the problem. -->\nwe eill find the total chalk needed by the students in one round and then will divide the total chalk by the needed chalk per one full cycle of students then we will get a remainder\n\nwe will get a for loop travelling to each student and seeing on whom the chalk is emptying and returning his index \nthats it\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\n# Code\n```javascript []\nvar chalkReplacer = function(chalk, k) {\n let sum=0\n for(let x of chalk)sum+=x\n let rem=k%sum\n for(let i=0;i<chalk.length;i++){\n rem-=chalk[i]\n if(rem<0)return i\n }\n};\n```\n```python []\ndef chalk_replacer(chalk, k):\n total = sum(chalk)\n rem = k % total\n for i, value in enumerate(chalk):\n rem -= value\n if rem < 0:\n return i\n return -1 \n```\n```c []\n#include <stdio.h>\n\nint chalkReplacer(int* chalk, int chalkSize, int k) {\n int sum = 0;\n for (int i = 0; i < chalkSize; i++) {\n sum += chalk[i];\n }\n int rem = k % sum;\n for (int i = 0; i < chalkSize; i++) {\n rem -= chalk[i];\n if (rem < 0) {\n return i;\n }\n }\n return -1; // Default return if no index is found (though theoretically should never happen)\n}\n\nint main() {\n int chalk[] = {5, 1, 5};\n int k = 22;\n int chalkSize = sizeof(chalk) / sizeof(chalk[0]);\n printf("%d\\n", chalkReplacer(chalk, chalkSize, k)); // Output: 0\n return 0;\n}\n\n```\n``` java []\npublic class ChalkReplacer {\n public static int chalkReplacer(int[] chalk, int k) {\n int sum = 0;\n for (int x : chalk) {\n sum += x;\n }\n int rem = k % sum;\n for (int i = 0; i < chalk.length; i++) {\n rem -= chalk[i];\n if (rem < 0) {\n return i;\n }\n }\n return -1; // Default return if no index is found (though theoretically should never happen)\n }\n\n public static void main(String[] args) {\n int[] chalk = {5, 1, 5};\n int k = 22;\n System.out.println(chalkReplacer(chalk, k)); // Output: 0\n }\n}\n\n```\n | 13 | 2 | ['Array', 'C', 'Simulation', 'Prefix Sum', 'Python', 'C++', 'Python3', 'JavaScript'] | 9 |
find-the-student-that-will-replace-the-chalk | ✔Java Solution using binary Search with Explanation💯 | java-solution-using-binary-search-with-e-wwnz | we will make a prefix sum of the chalk array....and we can optimize the given k as simply jumping to last iteration.\nlike k = 25, and sum = 10, iteration will | harshu175 | NORMAL | 2021-06-12T16:07:22.688723+00:00 | 2021-06-22T21:41:41.600187+00:00 | 1,778 | false | we will make a prefix sum of the chalk array....and we can optimize the given k as simply jumping to last iteration.\nlike k = 25, and sum = 10, iteration will be like 25 -> 15 -> 5\nthis can be very long number but if we directly take mod of k % sum..we will be at our last iteration.\nNow, here comes the role of prefix sum array\nwe will apply a binary search on it with k we have formed. \n```\nclass Solution {\n public int chalkReplacer(int[] chalk, int s) {\n long k = s;\n long[] prefix = new long[chalk.length];\n prefix[0] = chalk[0];\n for(int i = 1; i < chalk.length; i++){\n prefix[i] = chalk[i] + prefix[i-1];\n }\n \n if(prefix[chalk.length-1] <= k){\n k = k % prefix[chalk.length-1];\n }\n if(k == 0)return 0;\n \n int i = 0;\n int j = chalk.length-1;\n \n while(i <= j){\n int mid = i + (j-i)/2;\n \n if(k - prefix[mid] == 0)return mid+1;\n else if(k - prefix[mid] < 0){\n j = mid - 1;\n }else{\n i = mid + 1;\n }\n }\n return i;\n }\n}\n``` | 12 | 1 | ['Binary Tree', 'Java'] | 5 |
find-the-student-that-will-replace-the-chalk | Easy and Simple Approach ✅ | Loop-approach ✅ | cpp ✅ | easy-and-simple-approach-loop-approach-c-g8mm | Intuition\n Describe your first thoughts on how to solve this problem. \nWe can just get the sum of all the chalk elements and mod them with the k so we get to | parijatb_03 | NORMAL | 2024-09-02T03:53:21.904189+00:00 | 2024-09-02T03:53:21.904215+00:00 | 1,168 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n*We can just get the sum of all the chalk elements and mod them with the k so we get to know how many remains and update value of k as this remainder. Now we simple iterate the chalk array one more time this time we sure there will be no circular traversals anymore as we have already did mod previously. In this iteration we simply do as is given in the question i.e. decrease the k value till chalk[i](index i) <= k then return i;*\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)$$ -->\nsingle loop used so tc is **O(N)**, N is length of chalk array.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nconstant sc as no extra data structure used so sc is **O(1)**.\n# Code\n```cpp []\nclass Solution {\npublic:\n int chalkReplacer(vector<int>& chalk, int k) {\n long long total = accumulate(begin(chalk),end(chalk),0LL);\n k %= total;\n for(int i=0;i<chalk.size();i++){\n if(chalk[i]>k){\n return i;\n }else{\n k-=chalk[i];\n }\n }\n return -1;\n }\n};\n```\n\n\n | 9 | 0 | ['C++'] | 3 |
find-the-student-that-will-replace-the-chalk | Simple Java || C++ Code ☠️ | simple-java-c-code-by-abhinandannaik1717-0sz6 | Code\njava []\nclass Solution {\n public int chalkReplacer(int[] chalk, int k) {\n int n = chalk.length;\n long sum = 0;\n int i=0;\n | abhinandannaik1717 | NORMAL | 2024-09-02T16:41:38.174629+00:00 | 2024-09-02T16:41:38.174654+00:00 | 112 | false | # Code\n```java []\nclass Solution {\n public int chalkReplacer(int[] chalk, int k) {\n int n = chalk.length;\n long sum = 0;\n int i=0;\n for(i=0;i<n;i++){\n sum+=chalk[i];\n }\n if(k>=sum){\n k = k%(int)sum;\n }\n for(i=0;i<n;i++){\n if(k<chalk[i]){\n break;\n }\n k-=chalk[i];\n }\n return i;\n }\n}\n```\n``` C++ []\nclass Solution {\npublic:\n int chalkReplacer(vector<int>& chalk, int k) {\n int n = chalk.size();\n long long sum = 0;\n int i=0;\n for(i=0;i<n;i++){\n sum+=chalk[i];\n }\n if(k>=sum){\n k = k%sum;\n }\n for(i=0;i<n;i++){\n if(k<chalk[i]){\n break;\n }\n k-=chalk[i];\n }\n return i;\n }\n};\n```\n\n\n### Explanation\n\n1. **Calculate Total Chalk Needed for One Full Round:**\n ```java\n long sum = 0;\n for (i = 0; i < n; i++) {\n sum += chalk[i];\n }\n ```\n - **Purpose:** Compute the total amount of chalk required for one complete cycle of all students.\n - **Explanation:** The `sum` variable accumulates the chalk usage for each student from the `chalk` array. After this loop, `sum` represents the total chalk needed for one full round where each student uses their respective amount of chalk.\n\n2. **Optimize for Large `k` Values:**\n ```java\n if (k >= sum) {\n k = k % (int)sum;\n }\n ```\n - **Purpose:** Reduce the number of chalk pieces to a value within a single full round.\n - **Explanation:** If `k` is greater than or equal to `sum`, it means that multiple full rounds of chalk usage can be completed before considering the remainder. Using modulo operation, `k` is reduced to the remainder after dividing by `sum`, which represents the actual remaining chalk pieces after completing as many full rounds as possible.\n\n3. **Determine the Student Who Will Need to Replace the Chalk:**\n ```java\n for (i = 0; i < n; i++) {\n if (k < chalk[i]) {\n break;\n }\n k -= chalk[i];\n }\n ```\n - **Purpose:** Find the student who will be given a problem when the chalk runs out.\n - **Explanation:**\n - **Iteration:** Loop through each student.\n - **Condition Check:** Check if the remaining chalk (`k`) is less than the amount needed by the current student (`chalk[i]`).\n - **If True:** If `k < chalk[i]`, this means the current student (`i`) will encounter insufficient chalk and needs to replace it. The loop breaks, and `i` is the index of the student who needs to replace the chalk.\n - **If False:** If there is enough chalk, subtract the chalk used by the current student from `k` and move to the next student.\n\n4. **Return the Index of the Student:**\n ```java\n return i;\n ```\n - **Purpose:** Provide the index of the student who will have to replace the chalk.\n - **Explanation:** After the loop breaks, `i` will hold the index of the student who encounters insufficient chalk.\n\n### Example Walkthrough\n\nSuppose `chalk = [5, 1, 5]` and `k = 22`:\n\n1. **Calculate Total Chalk Needed:**\n - Total `sum = 5 + 1 + 5 = 11`\n\n2. **Optimize `k`:**\n - `k = 22 % 11 = 0` (no full rounds remaining)\n\n3. **Determine the Student to Replace Chalk:**\n - Start with `k = 0` and iterate:\n - Student 0 needs 5 pieces of chalk. Since `0 < 5`, student 0 will be the one to replace the chalk.\n\n4. **Return the Index:**\n - The function returns `0`.\n\n### Complexity\n\n- **Time Complexity:** \\(O(n)\\) - One pass to calculate the total chalk needed and another pass to determine the student.\n- **Space Complexity:** \\(O(1)\\) - Uses a constant amount of extra space beyond the input.\n\n\n\n | 8 | 0 | ['Array', 'Simulation', 'C++', 'Java'] | 0 |
find-the-student-that-will-replace-the-chalk | C++ | Easy to understand | O(n) | c-easy-to-understand-on-by-di_b-y50x | \nclass Solution {\npublic:\n int chalkReplacer(vector<int>& chalk, int k) {\n long sum = 0;\n for(int i =0; i < chalk.size(); ++i)\n | di_b | NORMAL | 2021-06-12T16:02:29.451899+00:00 | 2021-06-12T17:19:09.673286+00:00 | 448 | false | ```\nclass Solution {\npublic:\n int chalkReplacer(vector<int>& chalk, int k) {\n long sum = 0;\n for(int i =0; i < chalk.size(); ++i)\n sum += chalk[i];\n k = k%sum;\n for(int i =0; i < chalk.size(); ++i)\n {\n if(k < chalk[i])\n return i;\n k -=chalk[i];\n }\n return 0;\n }\n};\n``` | 8 | 6 | [] | 1 |
find-the-student-that-will-replace-the-chalk | Easy Solution | easy-solution-by-viratkohli-xyyl | 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 | viratkohli_ | NORMAL | 2024-09-02T02:50:38.489671+00:00 | 2024-09-02T02:50:38.489689+00:00 | 481 | 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```cpp []\nclass Solution {\npublic:\n int chalkReplacer(vector<int>& chalk, int k) {\n long long sum = 0;\n for(int i = 0; i<chalk.size(); i++){\n sum += chalk[i];\n }\n\n k %= sum;\n\n for(int i = 0; i<chalk.size(); i++){\n if(chalk[i]>k){\n return i;\n }\n else{\n k -= chalk[i]; \n }\n }\n return -1;\n }\n};\n``` | 7 | 0 | ['C++'] | 1 |
find-the-student-that-will-replace-the-chalk | ✅ One Line Solution | one-line-solution-by-mikposp-t43q | (Disclaimer: this is not an example to follow in a real project - it is written for fun and training mostly)\n\n# Code #1\nTime complexity: O(n). Space complexi | MikPosp | NORMAL | 2024-09-02T07:50:00.872915+00:00 | 2024-09-04T06:34:48.047205+00:00 | 461 | false | (Disclaimer: this is not an example to follow in a real project - it is written for fun and training mostly)\n\n# Code #1\nTime complexity: $$O(n)$$. Space complexity: $$O(n)$$.\n```\nclass Solution:\n def chalkReplacer(self, a: List[int], k: int) -> int:\n return bisect_left(p:=[*accumulate(a)],k%p[-1])\n```\n[Ref](https://leetcode.com/problems/find-the-student-that-will-replace-the-chalk/discuss/1267376/Python-1-line)\n\n# Code #2\nTime complexity: $$O(n)$$. Space complexity: $$O(1)$$.\n```\nclass Solution:\n def chalkReplacer(self, a: List[int], k: int) -> int:\n return (k:=k%sum(a)) and next(i for i,p in enumerate(accumulate(a)) if p>k)\n```\n\n(Disclaimer 2: code above is just a product of fantasy packed into one line, it is not claimed to be \'true\' oneliners - please, remind about drawbacks only if you know how to make it better) | 6 | 1 | ['Array', 'Binary Search', 'Simulation', 'Prefix Sum', 'Python', 'Python3'] | 1 |
find-the-student-that-will-replace-the-chalk | C++ ✅ ✅ easy to understand o(n) prefixSUM || BS. | c-easy-to-understand-on-prefixsum-bs-by-dtlim | \nclass Solution {\npublic:\n int chalkReplacer(vector<int>& c, int k) {\n long n = c.size(), sum, left;\n vector<long> pref(n); // creating n | dynamo_518 | NORMAL | 2024-09-02T05:07:08.052984+00:00 | 2024-09-02T06:54:32.305698+00:00 | 767 | false | ```\nclass Solution {\npublic:\n int chalkReplacer(vector<int>& c, int k) {\n long n = c.size(), sum, left;\n vector<long> pref(n); // creating new prefix sum vector due to overflow else not requried \n pref[0] = c[0];\n for(int i = 1;i<n;i++) pref[i] = pref[i-1] + c[i];\n sum = pref[n-1];\n if(k%sum == 0) return 0;\n left = k - (k/sum)*sum;\n return upper_bound(pref.begin(), pref.end(), left) - pref.begin();\n }\n};\n``` | 6 | 0 | ['Binary Search', 'C', 'Prefix Sum'] | 3 |
find-the-student-that-will-replace-the-chalk | ✅Find the Student that will Replace the Chalk ✅ || Easy thought process in CPP🔥🔥 | find-the-student-that-will-replace-the-c-c68j | Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem asks us to find which student will be the first to run out of chalk given a | Ashis2024 | NORMAL | 2024-09-02T04:38:49.623190+00:00 | 2024-09-02T04:38:49.623216+00:00 | 488 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem asks us to find which student will be the first to run out of chalk given a large number of units (k). Each student uses a certain amount of chalk, and this process repeats cyclically. If k is large, it\'s inefficient to simulate every single use of chalk. Instead, we can reduce the problem by recognizing that once k exceeds the total chalk needed for one complete cycle of all students, we can focus on the remainder after reducing k by the total chalk needed for one cycle. This remainder tells us how much chalk is left after all full cycles, allowing us to efficiently determine which student will run out of chalk first.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1.\tCalculate Total Chalk Needed for One Cycle:\n\u2022\tFirst, we compute the total amount of chalk required for all students in one full cycle (i.e., sum = chalk[0] + chalk[1] + ... + chalk[n-1]).\n2.\tReduce k Using Modulus Operation:\n\u2022\tSince chalk consumption repeats in cycles, reduce k by taking k % sum. This gives us the remainder of chalk left after all possible full cycles are completed.\n3.\tDetermine the Student:\n\u2022\tIterate through the chalk array and subtract the chalk each student would use from k. The first time k becomes less than the chalk needed by a student, that student is the one who will run out of chalk first.\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```cpp []\nclass Solution {\npublic:\n int chalkReplacer(vector<int>& chalk, int k) {\n int n = chalk.size();\n long long sum = 0;\n // calculate total chalk needed for one cycle\n for (int i = 0; i < n; i++) {\n sum += chalk[i];\n }\n // reduce k modulo sum\n k = k % sum;\n // loop to find which student require chalk\n for (int i = 0; i < n; i++) {\n if (k < chalk[i]) {\n return i;\n }\n k -= chalk[i];\n }\n return -1;\n }\n};\n```\n\n | 6 | 0 | ['C++'] | 1 |
find-the-student-that-will-replace-the-chalk | C++ || SERIOUSLY? IT REQUIRED BINARY SEARCH OR PREFIX SUM? | c-seriously-it-required-binary-search-or-7g08 | ```\nclass Solution {\npublic:\n int chalkReplacer(vector& chalk, int k) {\n long long sum =0;\n for(int ele : chalk){\n sum = sum + | Easy_coder | NORMAL | 2022-03-12T15:51:16.300766+00:00 | 2022-03-12T15:51:16.300793+00:00 | 697 | false | ```\nclass Solution {\npublic:\n int chalkReplacer(vector<int>& chalk, int k) {\n long long sum =0;\n for(int ele : chalk){\n sum = sum + (long long)ele;\n }\n k = ((long long)k) % sum;\n int i =0;\n while( i < chalk.size()){\n // cout<<k<<" ";\n if(chalk[i] > k) return i;\n k = k - (long long) chalk[i];\n i++;\n }\n return 0;\n }\n}; | 6 | 0 | ['C'] | 2 |
find-the-student-that-will-replace-the-chalk | Python || Prefix Sum and Binary Search || O(n) time O(n) space | python-prefix-sum-and-binary-search-on-t-qmh5 | \nclass Solution:\n def chalkReplacer(self, chalk: List[int], k: int) -> int:\n prefix_sum = [0 for i in range(len(chalk))]\n prefix_sum[0] = c | s_m_d_29 | NORMAL | 2021-12-05T06:41:44.879738+00:00 | 2021-12-05T06:41:44.879774+00:00 | 834 | false | ```\nclass Solution:\n def chalkReplacer(self, chalk: List[int], k: int) -> int:\n prefix_sum = [0 for i in range(len(chalk))]\n prefix_sum[0] = chalk[0]\n for i in range(1,len(chalk)):\n prefix_sum[i] = prefix_sum[i-1] + chalk[i]\n remainder = k % prefix_sum[-1]\n \n #apply binary search on prefix_sum array, target = remainder \n start = 0\n end = len(prefix_sum) - 1\n while start <= end:\n mid = start + (end - start) // 2\n if remainder == prefix_sum[mid]:\n return mid + 1\n elif remainder < prefix_sum[mid]:\n end = mid - 1\n else:\n start = mid + 1\n return start \n``` | 6 | 0 | ['Binary Search', 'Prefix Sum', 'Python', 'Python3'] | 2 |
find-the-student-that-will-replace-the-chalk | Simple Java | simple-java-by-scala62-mve8 | \nclass Solution {\n public int chalkReplacer(int[] chalk, int k) {\n long sum = 0;\n for (int c : chalk) {\n sum += c; \n }\ | scala62 | NORMAL | 2021-06-12T16:01:29.804682+00:00 | 2021-06-12T16:01:29.804719+00:00 | 657 | false | ```\nclass Solution {\n public int chalkReplacer(int[] chalk, int k) {\n long sum = 0;\n for (int c : chalk) {\n sum += c; \n }\n k = (int)((long)k % sum);\n int count = 0;\n while (k > 0) {\n k -= chalk[count++];\n }\n return k == 0 ? count : count - 1;\n }\n}\n``` | 6 | 1 | [] | 0 |
find-the-student-that-will-replace-the-chalk | Beats 90% Runtime 2ms || Best Java Solution || Intuition & Approach Explained | beats-90-runtime-2ms-best-java-solution-h8i2w | Intuition\nThe problem asks to find out which student will run out of chalk first when distributing k units of chalk according to the amounts specified in the c | raghavagarwal28 | NORMAL | 2024-09-02T16:30:14.753126+00:00 | 2024-09-09T07:30:09.692896+00:00 | 128 | false | # Intuition\nThe problem asks to find out which student will run out of chalk first when distributing k units of chalk according to the amounts specified in the chalk array. The naive approach might involve repeatedly iterating through the chalk array and subtracting the values from k until k is less than the amount required by a student. However, this could be inefficient if k is large. To optimize, we realize that after distributing chalk in complete rounds (where each student gets chalk once), the remaining chalk (k) will behave the same as if it were the remainder when k is divided by the total amount of chalk used in one full round. This remainder can then be used to determine which student runs out of chalk in a single pass.\n\n# Approach\nCalculate the Total Chalk Used in One Full Round:\n\nFirst, iterate through the chalk array and calculate the sum of all elements (sum). This represents the total chalk needed to complete one full round where each student gets chalk once.\nReduce k Using the Modulo Operation:\n\nThe problem of distributing k chalk can be reduced by finding k % sum. This gives the remaining chalk after completing as many full rounds as possible. Effectively, we now need to determine which student will run out of this remaining chalk.\nFind the Student Who Runs Out of Chalk:\n\nWith the remaining chalk (rem), iterate through the chalk array again. For each student, check if rem is less than the chalk needed by the student. If so, that student is the one who will run out of chalk first, and their index is returned.\n\n# Complexity\n- Time complexity:\nThe time complexity of this solution is \uD835\uDC42(\uD835\uDC5B)\nO(n), where n is the length of the chalk array. This is because we iterate through the chalk array twice: once to calculate the total sum and once to find the student who runs out of chalk.\n\n- Space complexity:\nThe space complexity is \uD835\uDC42(1)\nO(1) because we are only using a constant amount of extra space (sum and rem variables) regardless of the input size.\n\n\n\n# Code\n```java []\nclass Solution {\n public int chalkReplacer(int[] chalk, int k) {\n int rem = k;\n long sum = 0;\n\n for(int i=0; i<chalk.length; i++){\n sum += chalk[i];\n }\n rem %= sum;\n for(int i=0; i<chalk.length; i++){\n if(rem<chalk[i]){\n return i;\n }else{\n rem -= chalk[i];\n }\n }\n return 0;\n }\n}\n``` | 5 | 0 | ['Array', 'Simulation', 'Java'] | 4 |
find-the-student-that-will-replace-the-chalk | Simple and Easy CPP Code!💯✅☮️ | simple-and-easy-cpp-code-by-siddharth_si-ovw7 | \n\n# Code\ncpp []\nclass Solution {\npublic:\n int chalkReplacer(vector<int>& chalk, int k) {\n int c = 0;\n long long sum=0;\n for(int | siddharth_sid_k | NORMAL | 2024-09-02T14:45:08.331538+00:00 | 2024-09-02T14:45:08.331578+00:00 | 80 | false | \n\n# Code\n```cpp []\nclass Solution {\npublic:\n int chalkReplacer(vector<int>& chalk, int k) {\n int c = 0;\n long long sum=0;\n for(int i=0;i<chalk.size();i++)\n {\n sum+=chalk[i];\n }\n k=k%sum;\n for (int i = 0; i < chalk.size() ;i++) {\n if (k < chalk[i]) {\n c = i;\n return c;\n }\n k = k - chalk[i];\n }\n return c;\n }\n};\n```\n\n### Intuition:\nThe problem requires us to determine which student will run out of chalk after a certain number of units (`k`) have been distributed in a cyclic manner. Instead of repeatedly looping through the entire chalk array until `k` is exhausted, we can optimize by first calculating the total chalk needed for one complete round. By reducing `k` using the modulo operation, we effectively limit our search to the equivalent position within one round of chalk distribution, significantly improving efficiency.\n\n### Approach:\n1. **Calculate the Total Chalk Sum**: \n - First, calculate the total amount of chalk required for one complete round by summing up all the values in the `chalk` array.\n \n2. **Reduce `k` Using Modulo**:\n - Since the distribution of chalk is cyclic, we can reduce `k` to `k % totalChalk`. This step ensures that `k` is minimized to the equivalent amount of chalk that needs to be distributed within a single round, eliminating unnecessary full cycles.\n\n3. **Find the Student**:\n - Loop through the chalk array and keep subtracting each student\'s chalk requirement from `k`. The first student whose chalk requirement exceeds the remaining `k` is the one who will run out of chalk.\n\n### Complexity Analysis:\n- **Time Complexity**: \n - The time complexity is `O(n)`, where `n` is the number of students (or the size of the `chalk` array). This is because we traverse the `chalk` array twice: once for calculating the sum and once for finding the student who will replace the chalk.\n\n- **Space Complexity**:\n - The space complexity is `O(1)`, as we are using only a few extra variables (`sum`, `c`, `k`) regardless of the size of the input.\n\n | 5 | 0 | ['C++'] | 0 |
find-the-student-that-will-replace-the-chalk | Calculate Remaining Chalk Using Modulus Operation | Java | C++ | [Video Solution] | calculate-remaining-chalk-using-modulus-hum6d | Intuition, approach, and complexity discussed in video solution in detail\nhttps://youtu.be/dX8IWRDMUb0\n# Code\njava []\nclass Solution {\n public int chalk | Lazy_Potato_ | NORMAL | 2024-09-02T05:45:34.550875+00:00 | 2024-09-02T05:45:34.550903+00:00 | 918 | false | # Intuition, approach, and complexity discussed in video solution in detail\nhttps://youtu.be/dX8IWRDMUb0\n# Code\n``` java []\nclass Solution {\n public int chalkReplacer(int[] chalk, int k) {\n long totalChkNeed = 0l;\n for(var chkNeed : chalk){\n totalChkNeed += chkNeed;\n }\n long chlkRem = k * 1l;\n chlkRem %= totalChkNeed;\n for(int indx = 0; indx < chalk.length; indx++){\n long chkNeed = chalk[indx] * 1l;\n if(chlkRem - chkNeed >= 0){\n chlkRem -= chkNeed;\n }else{\n return indx;\n }\n }\n return -1;\n }\n}\n```\n```cpp []\nclass Solution {\npublic:\n int chalkReplacer(vector<int>& chalk, int k) {\n long long totalChkNeed = 0ll;\n for(auto & chkNeed : chalk){\n totalChkNeed += chkNeed;\n }\n long long chlkRem = k * 1ll;\n chlkRem %= totalChkNeed;\n for(int indx = 0; indx < chalk.size(); indx++){\n long long chkNeed = chalk[indx] * 1ll;\n if(chlkRem - chkNeed >= 0){\n chlkRem -= chkNeed;\n }else{\n return indx;\n }\n }\n return -1;\n }\n};\n``` | 5 | 0 | ['Array', 'Simulation', 'C++', 'Java'] | 2 |
find-the-student-that-will-replace-the-chalk | Only Solution You'll Need || Simulation || Explained line-by-line (Python) | only-solution-youll-need-simulation-expl-jxj9 | Intuition\n Describe your first thoughts on how to solve this problem. \nYou have a list of integers, chalk, where chalk[i] represents the amount of chalk the i | anand_shukla1312 | NORMAL | 2024-09-02T04:40:02.422161+00:00 | 2024-09-02T04:40:51.268517+00:00 | 66 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nYou have a list of integers, `chalk`, where `chalk[i]` represents the amount of chalk the `i-th` student uses before passing it to the next student. The process starts with`k` pieces of `chalk`. The students use chalk cyclically, and once the `chalk` runs out, the student who cannot use their required amount is identified.\n\n---\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- **Modulus Operation**: Calculate the total amount of chalk needed for one complete cycle (i.e., the sum of all elements in the `chalk` list). If the total chalk required for one cycle is more than k, then `k % sum(chalk)` will give us the effective chalk remaining after many complete cycles.\n\n- **Simulate the Process**: With the remaining chalk, iterate through the list of students and subtract the amount each student needs. If the `chalk` runs out before a student can get their required amount, return that student\'s index.\n\n---\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---\n\n\n# Code\n```python3 []\nclass Solution:\n def chalkReplacer(self, chalk: List[int], k: int) -> int:\n ans = k % sum(chalk) \n for i in range(len(chalk)):\n ans -= chalk[i]\n if ans < 0:\n return i\n \n\n```\n---\n\n\n | 5 | 0 | ['Array', 'Math', 'Simulation', 'Python3'] | 0 |
find-the-student-that-will-replace-the-chalk | Python Easy Solution | python-easy-solution-by-lokeshsk1-ct2q | \ndef chalkReplacer(self, chalk: List[int], k: int) -> int:\n\n\tk %= sum(chalk)\n\n\tfor i in range(len(chalk)):\n\t\tif chalk[i]>k:\n\t\t\treturn i\n\t\tk -= | lokeshsk1 | NORMAL | 2021-06-12T16:25:23.115817+00:00 | 2021-06-12T16:25:36.490547+00:00 | 496 | false | ```\ndef chalkReplacer(self, chalk: List[int], k: int) -> int:\n\n\tk %= sum(chalk)\n\n\tfor i in range(len(chalk)):\n\t\tif chalk[i]>k:\n\t\t\treturn i\n\t\tk -= chalk[i]\n```\n | 5 | 0 | ['Python', 'Python3'] | 4 |
find-the-student-that-will-replace-the-chalk | ✅💯🔥Simple Code📌🚀| 🔥✔️Easy to understand🎯 | 🎓🧠Beginner friendly🔥| O(n) Time Complexity💀💯 | simple-code-easy-to-understand-beginner-cefb0 | Tuntun Mosi ko Pranam\nSolution tuntun mosi ki photo ke baad hai. Scroll Down\n\n# Code\njava []\nclass Solution {\n public int chalkReplacer(int[] chalks, i | atishayj4in | NORMAL | 2024-09-11T17:40:01.440746+00:00 | 2024-09-11T17:40:01.440785+00:00 | 67 | false | # Tuntun Mosi ko Pranam\nSolution tuntun mosi ki photo ke baad hai. Scroll Down\n\n# Code\n```java []\nclass Solution {\n public int chalkReplacer(int[] chalks, int k) {\n long sum=0;\n for(int i=0; i<chalks.length; i++){\n sum+=chalks[i];\n }\n k%=sum;\n int i=0;\n for(i=0; i<chalks.length; i++){\n if(k>=chalks[i]){\n k-=chalks[i];\n }else{\n break;\n }\n }\n return i;\n }\n}\n```\n | 4 | 0 | ['Array', 'Binary Search', 'C', 'Simulation', 'Prefix Sum', 'Python', 'C++', 'Java', 'JavaScript'] | 1 |
find-the-student-that-will-replace-the-chalk | Simple Linear time Solution | 99% Beats | Java | simple-linear-time-solution-99-beats-jav-ytcw | \n# Code\njava []\nclass Solution {\n public int chalkReplacer(int[] chalk, int k) {\n int sum = 0;\n for(int i = 0; i < chalk.length; i++) {\n | eshwaraprasad | NORMAL | 2024-09-02T07:10:04.871883+00:00 | 2024-09-02T07:10:04.871902+00:00 | 168 | false | \n# Code\n```java []\nclass Solution {\n public int chalkReplacer(int[] chalk, int k) {\n int sum = 0;\n for(int i = 0; i < chalk.length; i++) {\n sum += chalk[i];\n if (sum > k) return i;\n }\n\n k %= sum;\n\n for(int i = 0; i < chalk.length; i++) {\n if(chalk[i] > k) return i;\n k -= chalk[i];\n }\n \n return -1;\n }\n}\n``` | 4 | 0 | ['Java'] | 0 |
find-the-student-that-will-replace-the-chalk | Easy C++ solution using mod(for beginners) || Beats 80% | easy-c-solution-using-modfor-beginners-b-p5od | \n\n# Approach\nModulo Optimization:\nYou compute the sum of all chalk usages, then reduce k by taking k % sum. This step ensures that t is minimized and within | Vamp101 | NORMAL | 2024-09-02T05:40:54.986512+00:00 | 2024-09-02T05:40:54.986561+00:00 | 199 | false | \n\n# Approach\nModulo Optimization:\nYou compute the sum of all chalk usages, then reduce k by taking k % sum. This step ensures that t is minimized and within the range of one complete cycle through the chalk array, eliminating unnecessary full cycles.\n\nLoop Through Students:\nThe loop iterates through each student to see if t (the remaining chalk) is less than the chalk the student will use (chalk[i]). If true, that student will be the one who cannot continue, so you return the index i.\nt -= chalk[i]; is used to subtract the chalk for the current student from the remaining chalk.\n\nCorrect Handling of Data Types:\nUse 0LL in accumulate to ensure that the sum is calculated as a long long, avoiding any potential overflow issues when dealing with large sums.\n\n# Complexity\n- Time complexity:\nThe time complexity is O(n) due to the initial accumulation of the chalk array and then another O(n) for the iteration to find the student. This makes the overall time complexity O(n).\n\n- Space complexity:\nThe space complexity is O(1) as no extra space is used beyond a few variables.\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int chalkReplacer(vector<int>& chalk, int k) {\n int n = chalk.size();\n long long sum = accumulate(chalk.begin(), chalk.end(), 0LL); \n int t = k % sum; \n for (int i = 0; i < n; ++i) {\n if (t < chalk[i]) {\n return i; \n }\n t -= chalk[i]; \n }\n\n\n return -1;\n}\n\n};\n``` | 4 | 0 | ['Array', 'Simulation', 'C++'] | 2 |
find-the-student-that-will-replace-the-chalk | Binary Search approach optimal | java | binary-search-approach-optimal-java-by-p-6hnl | \n# Approach\n Describe your approach to solving the problem. \nOptimal approach using binary search\n# Complexity\n- Time complexity:O(n+logn)=O(n)\n Add your | pala_04 | NORMAL | 2024-09-02T04:09:52.334000+00:00 | 2024-09-02T04:09:52.334035+00:00 | 598 | false | \n# Approach\n<!-- Describe your approach to solving the problem. -->\nOptimal approach using binary search\n# Complexity\n- Time complexity:O(n+logn)=O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int chalkReplacer(int[] chalk, int k) {\n int len = chalk.length;\n long sum[] = new long[len];\n sum[0] = chalk[0];\n for(int i=1;i<len;i++){\n sum[i]=chalk[i]+sum[i-1];\n }\n k = (int)(k%sum[len-1]);\n \n int i=0, j=len-1;\n while(i<j){\n int mid = (i + j) / 2;\n if (sum[mid] > k) {\n j = mid;\n } else {\n i = mid + 1;\n }\n }\n return i;\n }\n}\n``` | 4 | 0 | ['Array', 'Binary Search', 'Simulation', 'Prefix Sum', 'Java'] | 1 |
find-the-student-that-will-replace-the-chalk | 🌟| Efficient Solution | 76ms Beats 95.27% | C++ Java Py3 | O(n) | | efficient-solution-76ms-beats-9527-c-jav-ucdz | \n#\n---\n\n## Intuition\nWe need to keep track of the total amount of chalk each student uses until the remaining chalk is insufficient for the next student. T | user4612MW | NORMAL | 2024-09-02T03:30:46.776366+00:00 | 2024-09-02T03:33:10.135413+00:00 | 13 | false | \n#\n---\n\n## Intuition\nWe need to keep track of the total amount of chalk each student uses until the remaining chalk is insufficient for the next student. The efficient way to approach this is by first summing up the total chalk usage in one full round. Then, instead of repeatedly subtracting the chalk for every student until we run out, we can take advantage of the modulus operation to significantly reduce the number of operations needed.\n\n## Approach\nFirst, calculate the total chalk used by all students in one complete round. Then, reduce $$k$$ using the modulus operation **(k %= total)** to determine the effective chalk count after accounting for all full rounds of distribution. Finally, traverse the chalk array, subtracting each student\'s chalk usage from $$k$$ until the remaining chalk is insufficient for a student. This approach efficiently minimizes unnecessary iterations, making it optimal even for large inputs.\n\n## Complexity\n- **Time Complexity** The time complexity is $$O(n)$$ due to the initial summation and the subsequent traversal.\n- **Space Complexity** The space complexity is $$O(1)$$ since we\'re only using a few extra variables.\n\n---\n\n```cpp []\nclass Solution {\npublic:\n int chalkReplacer(vector<int>& ch, int k) {\n long long total{0};\n for (int c : ch) total += c;\n k %= total;\n int i{0};\n while (k >= ch[i]) k -= ch[i++];\n return i;\n }\n};\n```\n\n```java []\nclass Solution {\n public int chalkReplacer(int[] chalk, int k) {\n long total = 0;\n for (int c : chalk) total += c;\n k %= total;\n int i = 0;\n while (k >= chalk[i]) k -= chalk[i++];\n return i;\n }\n}\n```\n\n```python []\nclass Solution:\n def chalkReplacer(self, chalk: List[int], k: int) -> int:\n total = sum(chalk)\n k %= total\n i = 0\n while k >= chalk[i]:\n k -= chalk[i]\n i += 1\n return i\n```\n\n\n---\n | 4 | 0 | ['C++', 'Java', 'Python3'] | 0 |
find-the-student-that-will-replace-the-chalk | simple and easy explained Python solution 😍❤️🔥 | simple-and-easy-explained-python-solutio-xw9r | \n# if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n###### Follow on Github: www.github.com/shishirRsiam\n###### Let\'s Connect on LinkedIn: www.linkedin. | shishirRsiam | NORMAL | 2024-09-02T03:12:41.507947+00:00 | 2024-09-02T03:12:41.507986+00:00 | 572 | false | \n# if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n###### Follow on Github: www.github.com/shishirRsiam\n###### Let\'s Connect on LinkedIn: www.linkedin.com/in/shishirrsiam\n###### Let\'s Connect on Facebook: www.fb.com/shishirrsiam\n\n\n# Complexity\n- Time complexity: O(n)\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```python []\nclass Solution(object):\n def chalkReplacer(self, chalk, k):\n allSum = 0\n \n # Calculate the total sum of all elements in the chalk array\n for val in chalk:\n allSum += val\n \n # Calculate the remainder of k when divided by allSum\n # This determines how much chalk remains after several full cycles\n mod = k % allSum\n \n # Get the number of students\n n = len(chalk)\n \n # Iterate through the chalk array\n for i in range(n):\n # If the current student\'s chalk usage is more than the remaining chalk, return their index\n if chalk[i] > mod:\n return i\n \n # Otherwise, subtract the current student\'s chalk usage from the remaining chalk\n mod -= chalk[i]\n \n # This line should never be reached since the problem guarantees a solution.\n return mod\n``` | 4 | 0 | ['Array', 'Binary Search', 'Simulation', 'Prefix Sum', 'Python', 'Python3'] | 6 |
find-the-student-that-will-replace-the-chalk | Simple easy to understand solution. | simple-easy-to-understand-solution-by-co-rw7w | Intuition\nJust apply basic maths. Fully explained within the code.\n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(1)\n\n# Code\n\nclass Solu | codeHunter01 | NORMAL | 2023-04-06T07:28:46.757664+00:00 | 2023-04-06T07:28:46.757690+00:00 | 633 | false | # Intuition\nJust apply basic maths. Fully explained within the code.\n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(1)\n\n# Code\n```\nclass Solution {\n public int chalkReplacer(int[] chalk, int k) {\n int n= chalk.length;\n\n // First calculate the total sum of the array\n long sum = 0;\n for(int i=0;i<n;i++)\n {\n sum+=chalk[i];\n }\n\n // Now find the remaining chalk by dividing k by sum and take reminder. This will give you the remaining chalk for the last iteration.\n long rem = k%sum;\n\n // Now for the last iteration check if any value > remaining chalk or not. If yes, return that index.\n for(int i=0;i<n;i++)\n {\n if(chalk[i]>rem)\n return i;\n rem -= chalk[i];\n }\n return 0;\n }\n}\n``` | 4 | 0 | ['Array', 'Binary Search', 'Java'] | 2 |
find-the-student-that-will-replace-the-chalk | Java Easy Solution ( O(n) time | O(1) space ) | java-easy-solution-on-time-o1-space-by-t-xh1c | Intuition\nuse prefix sum to find that student in single round\n\n# Approach\nprefix sum to calculate number of chalks require for students \n\n# Complexity\n- | TSumit | NORMAL | 2022-12-11T11:03:21.238791+00:00 | 2022-12-11T11:03:21.238824+00:00 | 587 | false | # Intuition\nuse prefix sum to find that student in single round\n\n# Approach\nprefix sum to calculate number of chalks require for students \n\n# Complexity\n- Time complexity:\n O(n) time {O(n)+O(n)} is used for (n=length of chalk array) \n O(n) for prefix sum ans O(n) for serching student\n- Space complexity:\n O(1) space require for execution\n\n# Code\n```\n/* it takes O(n) space to store prefix sum\nclass Solution {\n public int chalkReplacer(int[] chalk, int k) {\n long prev=0l;\n long []ps=new long[chalk.length];\n for(int i=0;i<chalk.length;i++){\n prev+=chalk[i];\n ps[i]=prev;\n }\n k=(int)(k%prev);\n // System.out.println(prev);\n int lo=0,hi=chalk.length-1;\n int ans=0;\n while(lo<=hi){\n int mid=lo+(hi-lo)/2;\n if(ps[mid]==k){\n ans=mid+1;\n break;\n }\n else if(ps[mid]<k){\n lo=mid+1;\n }\n else{\n ans=mid;\n hi=mid-1;\n }\n }\n return ans;\n }\n}\n*/\n\nclass Solution {\n public int chalkReplacer(int[] chalk, int k) {\n long sum=0l;\n for(int val:chalk){\n sum+=val;\n }\n sum=(int)(k%sum);\n int ans=0;\n for(int i=0;i<chalk.length;i++){\n if(sum<chalk[i]){\n ans=i;\n break;\n }\n sum-=chalk[i];\n }\n return ans;\n }\n}\n``` | 4 | 0 | ['Java'] | 1 |
find-the-student-that-will-replace-the-chalk | Two approaches || O(n) - Javasript >> | two-approaches-on-javasript-by-ravitejay-gy6o | (1)\n\n\tlet sum = chalk.reduce((s,ele) => s + ele, 0);\n let iter = Math.floor(k/sum);\n let i=0;\n while(i < iter){\n k -= sum;\n i++;\ | ravitejay | NORMAL | 2022-10-06T12:21:58.416110+00:00 | 2023-01-19T04:16:15.875812+00:00 | 251 | false | # (1)\n```\n\tlet sum = chalk.reduce((s,ele) => s + ele, 0);\n let iter = Math.floor(k/sum);\n let i=0;\n while(i < iter){\n k -= sum;\n i++;\n }\n for(let i=0; i<chalk.length; i++){\n if(k >= chalk[i]){\n k -= chalk[i]\n } else {\n return i;\n }\n }\n```\n\n# (2)\n```\n\tlet i = 0;\n while(i<=chalk.length){\n if(i === chalk.length){\n i = 0;\n } else if(k >= chalk[i]){\n k -= chalk[i];\n i++;\n } else {\n return i;\n }\n }\n```\n\n*if the solution works for you* **please upvote** | 4 | 0 | ['Binary Tree', 'JavaScript'] | 1 |
find-the-student-that-will-replace-the-chalk | javascript binary search solution | javascript-binary-search-solution-by-chr-y8t5 | Iteration solution\n\nvar chalkReplacer = function(chalk, k) {\n let arr = new Array(chalk.length)\n let sum = 0\n for(let i =0; i< chalk.length; i++){ | chriskk | NORMAL | 2021-09-16T22:58:02.908820+00:00 | 2021-09-16T22:59:00.381789+00:00 | 200 | false | **Iteration solution**\n```\nvar chalkReplacer = function(chalk, k) {\n let arr = new Array(chalk.length)\n let sum = 0\n for(let i =0; i< chalk.length; i++){\n sum += chalk[i]\n arr[i]= sum\n }\n k = k%sum\n if(k==0 || k < chalk[0])\n return 0\n \n for(let i =0; i< chalk.length; i++){\n if(k < chalk[i]){\n return i\n }else{\n k-=chalk[i]\n }\n }\n};\n```\n**Binary search solution**\n```\nvar chalkReplacer = function(chalk, k) {\n let arr = new Array(chalk.length)\n let sum = 0\n for(let i =0; i< chalk.length; i++){\n sum += chalk[i]\n arr[i]= sum\n }\n \n k = k%sum\n if(k==0 || k < chalk[0])\n return 0\n let left = 0, right = chalk.length-1\n while(left < right){\n let mid = left + ((right - left) >> 1)\n if(arr[mid] > k){\n right = mid\n }else{\n left = mid + 1\n }\n }\n return left\n};\n``` | 4 | 0 | ['Binary Tree', 'JavaScript'] | 3 |
find-the-student-that-will-replace-the-chalk | Python 3 | O(N) | Explanation | python-3-on-explanation-by-idontknoooo-3r57 | Mod the total sum of chalk, so that k can be exhaust in one iteration\n- Then, iterate over chalk to find student i\n\nclass Solution:\n def chalkReplacer(se | idontknoooo | NORMAL | 2021-09-01T17:14:22.981300+00:00 | 2021-09-01T17:14:22.981365+00:00 | 240 | false | - Mod the total sum of `chalk`, so that `k` can be exhaust in one iteration\n- Then, iterate over `chalk` to find student i\n```\nclass Solution:\n def chalkReplacer(self, chalk: List[int], k: int) -> int:\n k %= sum(chalk)\n for i, num in enumerate(chalk):\n if k >= num: k -= num\n else: return i\n return -1\n``` | 4 | 0 | ['Array', 'Python', 'Python3'] | 1 |
find-the-student-that-will-replace-the-chalk | java easy and 100% time & 100% space | java-easy-and-100-time-100-space-by-jssa-5apl | \nclass Solution {\n public int chalkReplacer(int[] chalk, int k) {\n \n long sum = 0;\n for(int i = 0;i<chalk.length;i++){\n s | jssam002 | NORMAL | 2021-06-13T08:05:43.749376+00:00 | 2021-06-13T08:05:43.749419+00:00 | 243 | false | ```\nclass Solution {\n public int chalkReplacer(int[] chalk, int k) {\n \n long sum = 0;\n for(int i = 0;i<chalk.length;i++){\n sum+=chalk[i];\n k = k-chalk[i];\n if(k<0){\n return i;\n }\n }\n System.out.println(sum);\n if(sum>1000000007){\n sum = sum%1000000007;\n \n } k =k%(int)sum;\n int i = 0;\n while(k>=chalk[i]){\n k = k-chalk[i];\n i++;\n // System.out.println(k);\n if(i>=chalk.length){\n i = i%chalk.length;\n }\n }\n return i;\n }\n}\n``` | 4 | 0 | [] | 0 |
find-the-student-that-will-replace-the-chalk | c++ | c-by-rajat_gupta-qq7y | \nclass Solution {\npublic:\n int chalkReplacer(vector<int>& chalk, int k) {\n long int sum=accumulate(chalk.begin() , chalk.end() , 0l);\n\t\t//we su | rajat_gupta_ | NORMAL | 2021-06-12T20:43:10.102974+00:00 | 2021-06-12T20:48:13.392023+00:00 | 209 | false | ```\nclass Solution {\npublic:\n int chalkReplacer(vector<int>& chalk, int k) {\n long int sum=accumulate(chalk.begin() , chalk.end() , 0l);\n\t\t//we subtract the multiple of sum of chalks from the total chalks.\n k%=sum;\n\t\t//Now we distribute the remaining chalks from student 0 untill chalks are sufficient.\n for(int i=0;i<chalk.size();i++){\n k-=chalk[i];\n if(k<0) return i;\n }\n return -1;\n }\n};\n```\n**Feel free to ask any question in the comment section.**\nI hope that you\'ve found the solution useful.\nIn that case, **please do upvote and encourage me** to on my quest to document all leetcode problems\uD83D\uDE03\nHappy Coding :)\n | 4 | 2 | ['C', 'C++'] | 2 |
find-the-student-that-will-replace-the-chalk | Python | simple O(N) | python-simple-on-by-harshhx-rrk8 | \nclass Solution:\n def chalkReplacer(self, chalk: List[int], k: int) -> int:\n x = sum(chalk)\n if x<k:\n k = k%x\n if x == | harshhx | NORMAL | 2021-06-12T16:07:57.992669+00:00 | 2021-06-13T02:15:16.784064+00:00 | 493 | false | ```\nclass Solution:\n def chalkReplacer(self, chalk: List[int], k: int) -> int:\n x = sum(chalk)\n if x<k:\n k = k%x\n if x == k:\n return 0\n i = 0\n n = len(chalk)\n while True:\n if chalk[i]<=k:\n k -= chalk[i]\n else:\n break\n i +=1\n \n return i\n``` | 4 | 0 | ['Python', 'Python3'] | 2 |
find-the-student-that-will-replace-the-chalk | 2 Approaches!✅One Beats 99.19% with 1ms Solution💯 and other Brute Force with 2938ms | 2-approachesone-beats-9919-with-1ms-solu-s8s1 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nInitially the approach is very simple and naive , i.e to iterate the loop | ArcuLus | NORMAL | 2024-09-03T15:10:43.641542+00:00 | 2024-09-03T15:10:43.641577+00:00 | 11 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nInitially the approach is very simple and naive , i.e to iterate the loop till k becomes 0 , good for small iteration , very bad for big ones , that\'s why we got this much complexity which Mathematically it\'s O(n) only \n\nSo to Minimize the complexity we reduced the iteration by getting the knowledge about the cycles , by getting the remainder which is basically the final value of i , which we gonna return , and that\'ll cause the maximum iteration n and that\'s why it\'s complexity will be also same as O(n)\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\n// class Solution {\n// public int chalkReplacer(int[] arr, int k) {\n// int n = arr.length;\n// int i = 0;\n// while(k>0){\n// k = k - arr[i];\n// if(k == 0){\n// if(i == n-1){\n// return 0;\n// }else{\n// return i+1;\n// }\n// }else if(k<0){\n// return i;\n// }\n// if(i == n-1){\n// i = 0;\n// }else{\n// i++;\n// }\n// }\n// return 0;\n// }\n// } ALL TEST CASES PASSED BUT WITH 2328 MS ,, WHAT A brutally FORCED APPROACH\n\nclass Solution {\n public int chalkReplacer(int[] arr, int k) {\n long sum = 0;\n int n = arr.length;\n for(int value:arr) sum+=value;\n k %=sum;\n for(int i = 0;i<arr.length;i++){\n k = k-arr[i];\n if(k == 0){\n if(i == n-1){\n return 0;\n }else{\n return i+1;\n }\n }else if(k<0){\n return i;\n }\n }\n return 0;\n }\n} \n// 70/72 test cases passed , obviously because of long int\n\n\n``` | 3 | 0 | ['Java'] | 2 |
find-the-student-that-will-replace-the-chalk | Simple Solution with Approach | 🚀 | simple-solution-with-approach-by-hemants-fqqo | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nImagine how many comple | hemantsingh_here | NORMAL | 2024-09-02T18:25:33.884384+00:00 | 2024-09-02T18:25:33.884417+00:00 | 10 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nImagine how many complete rounds of chalk array you can take, suppose k = 25 and sum(chalk) = 10, then we can take 2 complete rounds and we have 5 remaining chalks. Then simply distribute these remaining chalks. Happy?\n\nTip : directly calculating sum using accumulate() can result in overflow as sum can be large value. To address this problem break loop when current sum > k.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int chalkReplacer(vector<int>& chalk, int k) {\n\n int curr_student = 0;\n int sum = 0;\n for (int i = 0; i < chalk.size(); i++) {\n sum += chalk[i];\n if (sum > k) {\n break;\n }\n }\n \n int remaining_chalks = k % sum;\n \n\n while(remaining_chalks >= 0 && remaining_chalks >= chalk[curr_student]){\n if(remaining_chalks >= chalk[curr_student]){\n remaining_chalks -= chalk[curr_student];\n curr_student++;\n }\n }\n \n return curr_student;\n }\n};\n``` | 3 | 0 | ['Array', 'C++'] | 0 |
find-the-student-that-will-replace-the-chalk | 💢☠💫Easiest👾Faster✅💯 Lesser🧠 🎯 C++✅Python3🐍✅Java✅C✅Python🐍✅C#✅💥🔥💫Explained☠💥🔥 Beats 100 | easiestfaster-lesser-cpython3javacpython-6b02 | Intuition\n\n Describe your first thoughts on how to solve this problem. \n- JavaScript Code --> https://leetcode.com/problems/find-the-student-that-will-replac | Edwards310 | NORMAL | 2024-09-02T14:35:36.254668+00:00 | 2024-09-02T17:57:18.009286+00:00 | 64 | false | # Intuition\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n- ***JavaScript Code -->*** https://leetcode.com/problems/find-the-student-that-will-replace-the-chalk/submissions/1376821379\n- ***C++ Code -->*** https://leetcode.com/problems/find-the-student-that-will-replace-the-chalk/submissions/1376517475?envType=daily-question&envId=2024-09-02\n- ***Python3 Code -->*** https://leetcode.com/problems/find-the-student-that-will-replace-the-chalk/submissions/1376533361?envType=daily-question&envId=2024-09-02\n- ***Java Code -->*** https://leetcode.com/problems/find-the-student-that-will-replace-the-chalk/submissions/1376551854?envType=daily-question&envId=2024-09-02\n- ***C Code -->*** https://leetcode.com/problems/find-the-student-that-will-replace-the-chalk/submissions/1376556170?envType=daily-question&envId=2024-09-02\n- ***Python Code -->*** https://leetcode.com/problems/find-the-student-that-will-replace-the-chalk/submissions/1376543166?envType=daily-question&envId=2024-09-02\n- ***C# Code -->*** https://leetcode.com/problems/find-the-student-that-will-replace-the-chalk/submissions/1376566563?envType=daily-question&envId=2024-09-02\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```javascript []\n/**\n * @param {number[]} chalk\n * @param {number} k\n * @return {number}\n */\nvar chalkReplacer = function(chalk, k) {\n let tot = 0\n for (let ele of chalk)\n tot += ele\n let re_after_rounds = k % tot\n for (let i = 0; i < chalk.length; ++i){\n if (re_after_rounds < chalk[i])\n return i;\n re_after_rounds -= chalk[i]\n }\n return -1\n};\n```\n\n | 3 | 0 | ['Array', 'C', 'Simulation', 'Python', 'C++', 'Java', 'Python3', 'JavaScript', 'C#'] | 0 |
find-the-student-that-will-replace-the-chalk | Easy Simulation Trick | Layman Language Explanation | easy-simulation-trick-layman-language-ex-x9e7 | Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem involves finding out which student will not have enough chalk to continue w | AkashGupta7 | NORMAL | 2024-09-02T08:09:58.793671+00:00 | 2024-09-02T08:09:58.793695+00:00 | 55 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem involves finding out which student will not have enough chalk to continue when a large number of chalks are distributed. Initially, it seemed like a direct simulation could work, but for large values of `k`, simulating each step would be inefficient. The key insight is that once we know the total sum of chalk needed for one full round, we can reduce `k` significantly by removing the number of full rounds possible, thus speeding up the process.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. **Calculate Total Chalk Sum:** First, calculate the total amount of chalk needed for one full round across all students.\n2. **Reduce `k`:** If `k` is greater than the total chalk sum, reduce `k` by the total sum until it becomes smaller than the sum. This step skips full rounds of distribution, making the process faster.\n3. **Find the Culprit:** Finally, iterate through the students, subtracting the chalk each student uses. The first student who cannot get enough chalk will be the answer.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity is $$O(n)$$, where `n` is the number of students. This is because we iterate through the list of students twice, once to calculate the sum and once to find the culprit.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is $$O(1)$$, as we are only using a constant amount of extra space regardless of the input size.\n\n# Code\n```cpp\nclass Solution {\npublic:\n int chalkReplacer(vector<int>& chalk, int k) {\n int n = chalk.size();\n int i = 0;\n\n // Jab tak chalk available hai, tab tak current chalk length ith student ke liye kaam karegi...\n\n long long sum = 0;\n for (int i = 0; i < n; i++) {\n sum += chalk[i]; // total chalk ka sum nikal lo\n }\n\n while (k > sum) { // Kitne gol gol poore chakkar laga sakta hai, isse iterations fast fast calculate ho jaengi...culprit to neeche wale loop se pta chalega...\n k -= sum; // total chalk ka multiple subtract karte raho jab tak sum se kam na ho jaye\n }\n\n while (k > 0 && k >= chalk[i]) {\n k -= chalk[i]; // chalk use karo\n\n if (i == n - 1) i = 0; // agar last student hai to wapas front pe aajao\n else i++; // warna next student ko chalk pakda do...\n }\n \n return i; // jis student ke liye chalk bachi hi nahi, wahi culprit hai\n }\n};\n | 3 | 0 | ['Array', 'Simulation', 'C++'] | 0 |
find-the-student-that-will-replace-the-chalk | Best solution in java || Simple approach || | best-solution-in-java-simple-approach-by-hw9l | Intuition\nWhen solving this problem, the main observation is that repeatedly looping through the array for every iteration of k is unnecessary. Since the sum o | Surbhi_Pandey | NORMAL | 2024-09-02T07:11:46.467231+00:00 | 2024-09-02T07:11:46.467260+00:00 | 192 | false | # Intuition\nWhen solving this problem, the main observation is that repeatedly looping through the array for every iteration of k is unnecessary. Since the sum of the chalk usage is constant in every full round, we can reduce k by taking its modulo with the total chalk consumption for one full round. This way, we only need to focus on the leftover chalk distribution for k.\n\n# Approach\nSum Calculation: First, calculate the total sum of chalk needed for one full round across all students. This will help reduce the large number k by removing unnecessary full rounds.\n\nModulo Reduction: By taking k %= totalSum, we reduce the problem to dealing with the remaining chalk after complete rounds have been accounted for. This is much more efficient than simulating every single round when k is large.\n\nFinal Iteration: After reducing k, we iterate over the chalk array one more time and simulate the distribution of chalk among the students. The first student for whom k becomes less than the chalk they need will be the one who runs out and needs to replace it.\n\n# Complexity\n- Time complexity:\n- The algorithm involves two loops through the chalk array. The first loop calculates the total sum, and the second loop iterates through the chalk to find the student who will replace the chalk. Both loops take linear time, resulting in O(n) time complexity\n\n- Space complexity:\n- We only use a constant amount of extra space for variables like totalSum and k, so the space complexity is constant.\n\n\n# Code\n```java []\nclass Solution {\n public int chalkReplacer(int[] chalk, int k) {\n long totalSum=0;\n for(int use:chalk){\n totalSum+=use;\n }\n k %= totalSum;\n for(int i=0;i<chalk.length;i++){\n if(k < chalk[i]){\n return i;\n }\n k -= chalk[i];\n }\nreturn -1;\n\n }\n}\n``` | 3 | 0 | ['Java'] | 2 |
find-the-student-that-will-replace-the-chalk | JAVA | 99% Beats | Linear Approach with Constant Space | java-99-beats-linear-approach-with-const-o0dq | \n# Complexity\n- Time complexity: O(n) \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) \ | SudhikshaGhanathe | NORMAL | 2024-09-02T06:30:34.491521+00:00 | 2024-09-02T06:30:34.491552+00:00 | 146 | false | \n# Complexity\n- Time complexity: O(n) \n\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int chalkReplacer(int[] chalk, int k) {\n\n int sum = 0;\n\n for (int i = 0 ; i < chalk.length ; i++) {\n sum += chalk[i];\n if (sum > k) return i;\n }\n\n k %= sum;\n\n for (int i = 0 ; i < chalk.length ; i++) {\n if (k < chalk[i])\n return i;\n k -= chalk[i];\n }\n\n return 0;\n }\n}\n``` | 3 | 0 | ['Array', 'Java'] | 0 |
find-the-student-that-will-replace-the-chalk | Easy O(N) solution beats 100% ---> | easy-on-solution-beats-100-by-its_shiv43-h4d8 | Approach\n1. Calculate the total sum: First, calculate the total sum of chalk required by all students.\n2. Reduce k modulo sum: Use the modulo operation to red | its_shiv43 | NORMAL | 2024-09-02T06:10:18.551522+00:00 | 2024-09-02T06:10:18.551561+00:00 | 249 | false | # Approach\n1. Calculate the total sum: First, calculate the total sum of chalk required by all students.\n2. Reduce k modulo sum: Use the modulo operation to reduce k by the total sum, as once the chalk runs out and starts over, it effectively loops back.\n3. Find the student: Iterate through the list of students and subtract their chalk requirement from k. The first student whose chalk requirement is greater than the remaining k is the one who will need to replenish the chalk, so return that student\'s index.\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(1)\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int chalkReplacer(vector<int>& chalk, int k) {\n \n long long sum=0;\n for(int i=0;i<chalk.size();i++){\n sum+=chalk[i];\n } \n\n k=k%sum;\n if(k==0){\n return 0;\n }\n \n int i=0;\n while(i<chalk.size()){\n if(k<chalk[i]){\n return i;\n }\n else{\n k-=chalk[i];\n i++;\n }\n }\n return 0;\n }\n};\n```\n```java []\nclass Solution {\n public int chalkReplacer(int[] chalk, int k) {\n long sum = 0;\n\n for (int i = 0; i < chalk.length; i++) {\n sum += chalk[i];\n }\n\n k = (int)(k % sum);\n if (k == 0) {\n return 0;\n }\n\n int i = 0;\n while (i < chalk.length) {\n if (k < chalk[i]) {\n return i;\n } else {\n k -= chalk[i];\n i++;\n }\n }\n return 0;\n }\n}\n\n```\n```python []\nclass Solution:\n def chalkReplacer(self, chalk, k):\n total_sum = sum(chalk)\n k = k % total_sum\n\n if k == 0:\n return 0\n i = 0\n while i < len(chalk):\n if k < chalk[i]:\n return i\n else:\n k -= chalk[i]\n i += 1\n\n return 0\n\n```\n```javascript []\nvar chalkReplacer = function(chalk, k) {\n let sum = 0;\n for (let i = 0; i < chalk.length; i++) {\n sum += chalk[i];\n }\n\n k = k % sum;\n if (k === 0) {\n return 0;\n }\n\n let i = 0;\n while (i < chalk.length) {\n if (k < chalk[i]) {\n return i;\n } else {\n k -= chalk[i];\n i++;\n }\n }\n\n return 0;\n};\n```\n\n\n\n\n\n | 3 | 0 | ['Array', 'Binary Search', 'Simulation', 'Prefix Sum', 'Python', 'C++', 'Java', 'Python3', 'JavaScript'] | 0 |
find-the-student-that-will-replace-the-chalk | 💡 C++ | O(n) | Using Math | Fully Explained ✏️ | c-on-using-math-fully-explained-by-tusha-e4f9 | Intuition\n- Cyclic Nature: The use of the modulus operator simplifies the problem by reducing it to a smaller, equivalent problem size, reflecting the cyclic n | Tusharr2004 | NORMAL | 2024-09-02T05:25:47.900237+00:00 | 2024-09-02T05:25:47.900270+00:00 | 3 | false | # Intuition\n- **Cyclic Nature:** The use of the modulus operator simplifies the problem by reducing it to a smaller, equivalent problem size, reflecting the cyclic nature of the students needing chalk.\n- **Efficiency:** Instead of simulating every unit of chalk usage, the code efficiently finds the result by working with the remainder of chalk after accounting for full cycles, making it much faster for large inputs.\n\n# Approach\n1. **Calculate Total Chalk Needed:**\n\n - First, the code calculates the total amount of chalk required by summing up all the values in the `chalk` vector. This is stored in the variable `sm`.\n\n```long sm = 0;\nfor (int i : chalk) {\n sm += i;\n}\n```\n\n2. **Reduce `k` Using Modulus:**\n\n - Since the chalk usage is cyclic (i.e., after the last student, it goes back to the first), we can use the modulus operator to find the effective amount of chalk needed after potentially many full cycles through all students.\n\n```\nk %= sm;\n```\nBy doing this, we reduce the problem size and work only with the remaining chalk `k` that hasn\'t been used up by full cycles of the `chalk` vector.\n\n3. **Find the Student:**\n\nThe code then iterates through the chalk vector to determine which student will need `chalk` when `k` is less than the amount of chalk that student requires.\n```\nfor (int j = 0; j < chalk.size(); j++) {\n if (k < chalk.at(j)) {\n return j;\n } else {\n k -= chalk.at(j);\n }\n}\n```\n\n- If `k` is less than chalk[j]: The current student `j` will be the one who needs more `chalk` than is available, so we return their index.\n- Otherwise: Subtract the amount of chalk used by the current student from `k` and continue to the next student.\n\n4. **Edge Case:**\n\n- The return 0; at the end is a fallback, but logically it should never be reached because the condition to return within the loop should always cover all cases. This line can be considered a safeguard, but it is effectively redundant in this context.\n\n\n# Complexity\n- Time complexity:\n```O(n)```\n\n- Space complexity:\n```O(1)```\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int chalkReplacer(vector<int>& chalk, int k) {\n // Step 1: Calculate the total amount of chalk needed for one full cycle\n long sm = 0; // Variable to store the sum of all chalk requirements\n for (int i : chalk) {\n sm += i; // Sum up all the chalk requirements\n }\n \n // Step 2: Reduce k to the effective amount of chalk needed\n k %= sm; // Only need to consider the remainder when chalk is divided by the total chalk usage\n\n // Step 3: Determine which student will run out of chalk first\n for (int j = 0; j < chalk.size(); j++) {\n // If the remaining chalk k is less than the chalk needed by the current student\n if (k < chalk[j]) {\n return j; // Return the index of this student\n } else {\n k -= chalk[j]; // Subtract the chalk needed by this student from k and move to the next student\n }\n }\n\n // Fallback return, but should not be reached as the loop should always find a valid student\n return 0;\n }\n};\n\n```\n\n\n\n# Ask any doubt !!!\nReach out to me \uD83D\uDE0A\uD83D\uDC47\n\uD83D\uDD17 https://tusharbhardwa.github.io/Portfolio/\n | 3 | 0 | ['Math', 'C++'] | 0 |
find-the-student-that-will-replace-the-chalk | Beats 97% || Easy to Understand C++ code | beats-97-easy-to-understand-c-code-by-ji-ebgn | Intuition\nThe intuition behind this approach is to first reduce the problem by handling the cyclic nature of the chalk distribution, making it more manageable. | jitenagarwal20 | NORMAL | 2024-09-02T05:19:13.456321+00:00 | 2024-09-02T05:19:13.456359+00:00 | 36 | false | # Intuition\nThe intuition behind this approach is to first reduce the problem by handling the cyclic nature of the chalk distribution, making it more manageable. Then, by iterating through the students, we can quickly identify the first student who will run out of chalk after the remaining k chalks are distributed.\n\n# Approach\n**1.Calculate the Total Chalk Requirement (sum):**\n\nFirst, the code calculates the total amount of chalk required by all students in one complete round. This is done using the accumulate function, which sums up all the elements in the chalk vector.\n\n**2.Reduce the Problem Size:**\n\nIf k is greater than or equal to sum, it means that you can complete several full rounds of chalk distribution. However, because of the cyclic nature of the problem, distributing k chalks is equivalent to distributing k % sum chalks (remainder after dividing k by sum). This step helps in reducing the size of k to a manageable number, potentially smaller than sum.\n\n**3.Identify the Student:**\n\nAfter reducing k, the code iterates through each student\'s chalk requirement:\nFor each student i, it checks if the remaining chalk k is less than the chalk required by that student (chalk[i]).\nIf true, it means this student will be the one who can\'t get enough chalk, and the function returns the index i.\nIf not, it subtracts the student\'s chalk requirement from k and moves on to the next student.\n\n**4.Return the Result:**\n\nThe function will return the index of the student who cannot get the required chalk, which is the solution.\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```cpp []\nclass Solution {\npublic:\n int chalkReplacer(vector<int>& chalk, int k) {\n ios::sync_with_stdio(false);\n cin.tie(0);\n long long sum = 0;\n sum = accumulate(chalk.begin(),chalk.end(),sum);\n k=k%sum;\n for(int i=0;i<chalk.size();i++){\n if(chalk[i]>k)\n return i;\n k-=chalk[i];\n }\n return -1;\n //Do upvote if you like the solution and approach\n }\n};\n``` | 3 | 0 | ['C++'] | 0 |
find-the-student-that-will-replace-the-chalk | Python | Greedy | python-greedy-by-khosiyat-l62w | see the Successfully Accepted Submission\n\n# Code\npython3 []\nclass Solution:\n def chalkReplacer(self, chalk: List[int], k: int) -> int:\n # Step 1 | Khosiyat | NORMAL | 2024-09-02T05:17:20.556207+00:00 | 2024-09-02T05:17:20.556240+00:00 | 370 | false | [see the Successfully Accepted Submission](https://leetcode.com/problems/find-the-student-that-will-replace-the-chalk/submissions/1376082291/?envType=daily-question&envId=2024-09-02)\n\n# Code\n```python3 []\nclass Solution:\n def chalkReplacer(self, chalk: List[int], k: int) -> int:\n # Step 1: Calculate the total chalk usage in one round\n total_chalk = sum(chalk)\n \n # Step 2: Reduce k by the total chalk usage\n k %= total_chalk\n \n # Step 3: Find the student who needs to replace the chalk\n for i in range(len(chalk)):\n if k < chalk[i]:\n return i\n k -= chalk[i]\n\n```\n\n## Step 1: Calculate the Total Chalk Usage in One Round\nFirst, we need to calculate the total amount of chalk used in one complete round of students. This is simply the sum of all elements in the `chalk` array.\n\n## Step 2: Reduce `k` by the Total Chalk Used in One Round\nIf `k` is larger than or equal to the total chalk used in one round, we can reduce `k` modulo this sum. This way, we are effectively simulating several complete rounds in just one step.\n\n## Step 3: Determine the Student Who Will Run Out of Chalk\nAfter reducing `k`, we iterate through the `chalk` array and subtract the chalk used by each student from `k` until `k` is less than the chalk required by the current student. This student is the one who will need to replace the chalk.\n\n## Explanation with Example\nFor example, in the case where `chalk = [5,1,5]` and `k = 22`:\n\n- First, the total chalk usage in one round is `5 + 1 + 5 = 11`.\n- We reduce `k` by the total chalk: `k = 22 % 11 = 0`.\n- We then iterate through the students:\n - Student 0 needs 5 chalk, but `k` is 0, which is less than 5, so student 0 will replace the chalk.\n\nThus, the function returns `0` as expected.\n\n## Complexity\n- **Time Complexity**: O(n) where n is the number of students. We compute the sum of the array (O(n)) and then perform a single pass through the array (O(n)).\n- **Space Complexity**: O(1) because we only use a constant amount of extra space.\n\n\n\n | 3 | 0 | ['Python3'] | 0 |
find-the-student-that-will-replace-the-chalk | ✅ 🔥 Java | Greedy | 100% faster with O(N) and O(1) ✅ 🔥 | java-greedy-100-faster-with-on-and-o1-by-hare | Intuition\n Describe your first thoughts on how to solve this problem. \nSubtracting k from each student\'s chalk count step by step is a redundant task, so I d | Surendaar | NORMAL | 2024-09-02T04:55:18.078774+00:00 | 2024-09-02T16:02:02.930677+00:00 | 181 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSubtracting k from each student\'s chalk count step by step is a redundant task, so I decided to sum the counts and use modulo k to directly reach the final lap of the cycle.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Since the sum can be large, I initialized both sum and k as long.\n- First, calculate the sum of the given chalks.\n- Take k modulo sum to go directly to the final lap instead of repeating the process multiple times.\n- Now, iterate through the students\' chalk counts to find the student where k becomes less than the chalk count, and return that student\'s index.\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\nKindly upvote and encourage... \n\n# Code\n```java []\nclass Solution {\n public int chalkReplacer(int[] chalk, int k) {\n long sum=0, K =k;\n for(int i:chalk){\n sum = sum+i;\n }\n K = K %sum;\n for(int i=0; i<chalk.length; i++){\n if(K<chalk[i]){\n return i;\n }\n K = K-chalk[i];\n }\n return 0;\n }\n}\n``` | 3 | 0 | ['Greedy', 'Java'] | 0 |
find-the-student-that-will-replace-the-chalk | C# Solution for Find the Student that Will Replace the Chalk Problem | c-solution-for-find-the-student-that-wil-zf21 | Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem revolves around distributing chalk to students in a cyclic manner until the | Aman_Raj_Sinha | NORMAL | 2024-09-02T03:53:09.913968+00:00 | 2024-09-02T03:53:09.913993+00:00 | 84 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem revolves around distributing chalk to students in a cyclic manner until the chalk runs out. Given the constraints, a direct simulation would be inefficient, so we can optimize the process by leveraging a prefix sum array combined with binary search.\n\nThe prefix sum array helps us efficiently track the cumulative amount of chalk used by students up to a certain point. With this array, we can use binary search to quickly identify the student who will run out of chalk and need to replace it, instead of iterating through each cycle repeatedly.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1.\tPrefix Sum Calculation:\n\t\u2022\tCreate a prefix sum array where each element represents the total chalk used from the first student up to the current student. For example, prefixSums[i] will hold the sum of chalk[0] + chalk[1] + ... + chalk[i].\n\t\u2022\tThis allows us to determine the cumulative chalk usage up to any given student in constant time.\n2.\tReduce k Using Modulo Operation:\n\t\u2022\tSince the problem is cyclic, we reduce k by calculating k % totalChalk, where totalChalk is the total amount of chalk used in one complete cycle. This effectively reduces the problem size to a single incomplete cycle.\n3.\tBinary Search:\n\t\u2022\tPerform a binary search on the prefix sum array to find the smallest index where the prefix sum exceeds k. This index corresponds to the student who will need to replace the chalk because they cannot complete their turn.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n):\n\t\u2022\tCalculating the prefix sum array requires iterating over the chalk array once, which takes O(n) time.\n\t\u2022\tThe binary search on the prefix sum array takes O(log n) time.\n\t\u2022\tThe overall time complexity is dominated by the prefix sum calculation, so it is O(n).\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n):\n\t\u2022\tThe solution requires storing the prefix sum array, which is of size n. Therefore, the space complexity is O(n).\n\n# Code\n```csharp []\npublic class Solution {\n public int ChalkReplacer(int[] chalk, int k) {\n int n = chalk.Length;\n \n // Step 1: Calculate prefix sums\n long[] prefixSums = new long[n];\n prefixSums[0] = chalk[0];\n for (int i = 1; i < n; i++) {\n prefixSums[i] = prefixSums[i - 1] + chalk[i];\n }\n\n // Step 2: If k is larger than total chalk used in one round, reduce it\n k = (int)(k % prefixSums[n - 1]);\n\n // Step 3: Binary search to find the first index where prefixSum > k\n int left = 0, right = n - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (prefixSums[mid] > k) {\n right = mid - 1;\n } else {\n left = mid + 1;\n }\n }\n\n // left is the index of the student who cannot finish their turn\n return left;\n }\n}\n``` | 3 | 0 | ['C#'] | 0 |
find-the-student-that-will-replace-the-chalk | simple and easy explained Javascript solution 😍❤️🔥 | simple-and-easy-explained-javascript-sol-kyu0 | \n# if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n###### Follow on Github: www.github.com/shishirRsiam\n###### Let\'s Connect on LinkedIn: www.linkedin. | shishirRsiam | NORMAL | 2024-09-02T03:16:23.099513+00:00 | 2024-09-02T03:16:23.099562+00:00 | 211 | false | \n# if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n###### Follow on Github: www.github.com/shishirRsiam\n###### Let\'s Connect on LinkedIn: www.linkedin.com/in/shishirrsiam\n###### Let\'s Connect on Facebook: www.fb.com/shishirrsiam\n\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```javascript []\nvar chalkReplacer = function(chalk, k) \n{\n let allSum = 0;\n \n // Calculate the total sum of all elements in the chalk array\n for(let val of chalk) \n allSum += val;\n \n // Calculate the remainder of k when divided by allSum\n // This determines how much chalk remains after several full cycles\n let mod = k % allSum;\n \n // Get the number of students\n let n = chalk.length;\n \n // Iterate through the chalk array\n for(let i = 0; i < n; i++)\n {\n // If the current student\'s chalk usage is more than the remaining chalk, return their index\n if(chalk[i] > mod) \n return i;\n \n // Otherwise, subtract the current student\'s chalk usage from the remaining chalk\n mod -= chalk[i];\n }\n \n // This line should never be reached since the problem guarantees a solution.\n return mod;\n};\n``` | 3 | 0 | ['Array', 'Binary Search', 'Simulation', 'Prefix Sum', 'JavaScript'] | 6 |
find-the-student-that-will-replace-the-chalk | simple and easy explained C++ solution 😍❤️🔥 | simple-and-easy-explained-c-solution-by-r0kqy | \n# if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n###### Follow on Github: www.github.com/shishirRsiam\n###### Let\'s Connect on LinkedIn: www.linkedin. | shishirRsiam | NORMAL | 2024-09-02T03:09:18.940955+00:00 | 2024-09-02T03:09:18.940978+00:00 | 393 | false | \n# if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n###### Follow on Github: www.github.com/shishirRsiam\n###### Let\'s Connect on LinkedIn: www.linkedin.com/in/shishirrsiam\n###### Let\'s Connect on Facebook: www.fb.com/shishirrsiam\n\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int chalkReplacer(vector<int>& chalk, int k) \n {\n long allSum = 0;\n \n // Calculate the total sum of all elements in the chalk array\n for(auto val : chalk)\n allSum += val;\n \n // Calculate the remainder of k when divided by allSum\n // This determines how much chalk remains after several full cycles\n long mod = k % allSum, n = chalk.size();\n \n // Iterate through the chalk array\n for(int i = 0; i < n; i++)\n {\n // If the current student\'s chalk usage is more than the remaining chalk, return their index\n if(chalk[i] > mod) return i;\n \n // Otherwise, subtract the current student\'s chalk usage from the remaining chalk\n mod -= chalk[i];\n }\n \n // This line should never be reached since the problem guarantees a solution.\n return mod;\n }\n};\n``` | 3 | 0 | ['Array', 'Binary Search', 'Simulation', 'Prefix Sum', 'C++'] | 7 |
find-the-student-that-will-replace-the-chalk | ✅Simple Prefix Sum (C++/Java/Python) Solution With Detailed Explanation✅ | simple-prefix-sum-cjavapython-solution-w-lwfq | Detailed Explanation\n\n1. Initialization:\n cpp\n int n = chalk.size();\n long long int sum = 0;\n\n - n stores the number of elements in the chalk | suyogshete04 | NORMAL | 2024-07-06T06:42:25.716129+00:00 | 2024-07-06T06:42:25.716171+00:00 | 480 | false | # Detailed Explanation\n\n1. **Initialization**:\n ```cpp\n int n = chalk.size();\n long long int sum = 0;\n ```\n - `n` stores the number of elements in the `chalk` vector.\n - `sum` is initialized to store the total amount of chalk needed for one complete round.\n\n2. **Calculating the Total Chalk Usage**:\n ```cpp\n for (auto num : chalk)\n sum += num;\n ```\n - This loop iterates through each element in the `chalk` vector and accumulates the total amount of chalk needed for one full round of usage.\n\n3. **Reducing `k` by the Total Chalk Usage**:\n ```cpp\n k %= sum;\n ```\n - Since using more than `sum` amount of chalk in one full round doesn\'t change the outcome, we reduce `k` to `k % sum`. This effectively simulates the scenario as if we only have `k % sum` amount of chalk left after completing full rounds.\n\n4. **Finding the Student Who Will Run Out of Chalk**:\n ```cpp\n int i;\n for (i = 0; i < n; i++) {\n if (k < chalk[i])\n break;\n else\n k -= chalk[i];\n }\n ```\n - This loop iterates through the `chalk` vector again to determine which student will run out of chalk first.\n - If `k` is less than the amount of chalk the current student uses, that student will run out of chalk.\n - Otherwise, we subtract the current student\'s chalk usage from `k` and move to the next student.\n\n5. **Returning the Result**:\n ```cpp\n return i;\n ```\n - The index `i` of the student who will run out of chalk is returned.\n\n### Time Complexity\n\n1. **Calculating the Total Chalk Usage**:\n - The loop `for (auto num : chalk)` runs `n` times, where `n` is the size of the `chalk` vector.\n - Time complexity: \\(O(n)\\).\n\n2. **Reducing `k` by the Total Chalk Usage**:\n - The operation `k %= sum` is a constant-time operation.\n - Time complexity: \\(O(1)\\).\n\n3. **Finding the Student Who Will Run Out of Chalk**:\n - The loop `for (i = 0; i < n; i++)` runs at most `n` times.\n - Time complexity: \\(O(n)\\).\n\nOverall, the time complexity of the algorithm is \\(O(n)\\).\n\n### Space Complexity\n\n1. **Auxiliary Space**:\n - The space used by the algorithm is constant because we only use a few extra variables (`n`, `sum`, `i`, and `k`).\n - Space complexity: \\(O(1)\\).\n\n2. **Input Space**:\n - The space used by the input `chalk` vector is \\(O(n)\\), but this is not considered extra space since it is part of the input.\n\nOverall, the space complexity of the algorithm is \\(O(1)\\) in terms of auxiliary space.\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int chalkReplacer(vector<int>& chalk, int k) {\n int n = chalk.size();\n long long int sum = 0;\n for (auto num : chalk)\n sum += num;\n\n k %= sum;\n int i;\n for (i=0; i<n; i++)\n {\n if (k % chalk[i] == k)\n break;\n else\n k -= chalk[i];\n }\n\n return i;\n }\n};\n```\n```Java []\npublic class Solution {\n public int chalkReplacer(int[] chalk, int k) {\n int n = chalk.length;\n long sum = 0;\n for (int num : chalk) {\n sum += num;\n }\n\n k %= sum;\n int i;\n for (i = 0; i < n; i++) {\n if (k < chalk[i]) {\n break;\n } else {\n k -= chalk[i];\n }\n }\n\n return i;\n }\n}\n\n```\n```Python []\nfrom typing import List\n\nclass Solution:\n def chalkReplacer(self, chalk: List[int], k: int) -> int:\n n = len(chalk)\n total = sum(chalk)\n \n k %= total\n for i in range(n):\n if k < chalk[i]:\n return i\n k -= chalk[i]\n \n return -1 # Just a safeguard, should never hit this line\n\n``` | 3 | 0 | ['Array', 'Prefix Sum', 'C++', 'Java', 'Python3'] | 1 |
find-the-student-that-will-replace-the-chalk | 2 C++ solutions || Binary search || Prefix-Sum || Beats 90% !! | 2-c-solutions-binary-search-prefix-sum-b-8edr | Code\n\n// Solution 1\nclass Solution {\npublic:\n int chalkReplacer(vector<int>& chalk, int k) {\n int n = chalk.size();\n vector<long long> p | prathams29 | NORMAL | 2023-07-12T07:39:46.149618+00:00 | 2023-07-12T07:39:46.149646+00:00 | 352 | false | # Code\n```\n// Solution 1\nclass Solution {\npublic:\n int chalkReplacer(vector<int>& chalk, int k) {\n int n = chalk.size();\n vector<long long> pref(n);\n pref[0] = chalk[0];\n for(int i = 1; i < n; i++)\n pref[i] = chalk[i] + pref[i-1];\n k %= pref[n-1];\n int i = 0, j = n-1, ans;\n while(i<=j){\n int mid = (i+j)/2;\n if(pref[mid] <= k)\n i = mid+1;\n else\n ans = mid, j = mid-1;\n }\n return ans;\n }\n};\n\n// Solution 2\nclass Solution {\npublic:\n int chalkReplacer(vector<int>& chalk, int k) {\n long long int sum = 0;\n int i = 0;\n for(int c : chalk)\n sum += c;\n k %= sum;\n while(k>=chalk[i])\n k -= chalk[i], i++;\n return i;\n }\n};\n``` | 3 | 0 | ['Binary Search', 'Prefix Sum', 'C++'] | 1 |
find-the-student-that-will-replace-the-chalk | Python: Explained Easy O(n) Solution | python-explained-easy-on-solution-by-mea-xwbm | One way to think this is, Iterate through each chalk and keep decrementing K, till K becomes negative.\nTime = O(n * ( k / sum(chalk)) But This will give TLE. \ | meaditya70 | NORMAL | 2021-06-12T16:16:23.476223+00:00 | 2021-06-12T16:34:00.786995+00:00 | 105 | false | One way to think this is, Iterate through each chalk and keep decrementing K, till K becomes negative.\nTime = O(n * ( k / sum(chalk)) But This will give TLE. \n```\n\tdef chalkReplacer(self, chalk: List[int], k: int) -> int:\n n = len(chalk)\n while True:\n for i in range(n):\n k -= chalk[i]\n if k < 0:\n return i\n```\n\nOther way to think this is, Take the sum of chalk as \'s\', now \n1. one round can be completed by \'s\' chalks and \'k-s\' chalks are still left.\n2. Second round can be completed by \'2 * s\' chalks and \'k - 2 * s\' chalks are still left and so on...\n\nSimply, it means K/s will give the complete number of round and the remainder K%s will give the number of chalks that are still left after K/s rounds.\n\nNow, after full rounds, when remaining = K%s chalks are left, traverse the chalks and subtract chalks[i] from K, till K becomes negative and return the index.\n\nTime = O(n) and constant space.\n```\n\tdef chalkReplacer(self, chalk: List[int], k: int) -> int:\n summ = sum(chalk)\n remaining = k % summ\n for i in range(len(chalk)):\n remaining -= chalk[i]\n if remaining<0:\n return i\n``` | 3 | 0 | ['Python'] | 0 |
find-the-student-that-will-replace-the-chalk | Java Short Code with explanation | Logic | java-short-code-with-explanation-logic-b-sen8 | \nSince we know every chalk is consumed fully we can cancel the iterations that the teacher makes from begining to end by assiging them to students. Lets see ho | sandip_jana | NORMAL | 2021-06-12T16:02:04.751373+00:00 | 2021-06-13T05:25:45.075293+00:00 | 282 | false | \nSince we know every chalk is consumed fully we can cancel the iterations that the teacher makes from begining to end by assiging them to students. Lets see how.\n\nSo we know when the teacher starts distributing chalks and does that till the end of array she has distributed\n\n= chalk[0] + chalk[1] + chalk[2] + .... + chalk[n-2] + chalk[n-1]\n\nand she again starts from index 0.\n\nNow lets say , chalk[0] + chalk[1] + chalk[2] + .... + chalk[n-2] + chalk[n-1] = SUM\n\nSo, if teacher peforms the cycle of distribution of chalks from begining to end Y times , \nthe total chalks distributed = SUM * Y\n\nafter all cycles she is left with how many chalks ?\n\nremaining = ( k - (SUM * Y) ) = k % SUM\n\nthus we can simply compute this remainder\nand then iterate over the chalks array and check which student cannot get the chalk now.\n\n\n```\nclass Solution {\n public int chalkReplacer(int[] chalk, int k) {\n\t\tlong sum = 0;\n\t\tfor (int eachChalk : chalk) sum+=eachChalk;\n\t\tlong remainder = k%sum;\n\n\t\tfor (int i= 0 ; i<chalk.length ; i++) {\n\t\t\tif ( remainder>=chalk[i] )\n\t\t\t\tremainder-=chalk[i];\n\t\t\telse\n\t\t\t\treturn i;\n\t\t}\n\t\tthrow new IllegalStateException();\n\t}\n} | 3 | 0 | ['Greedy', 'Java'] | 2 |
find-the-student-that-will-replace-the-chalk | Beats 100%, beginner way | beats-100-beginner-way-by-coderashu1-tlz8 | IntuitionThe problem revolves around efficiently determining which student will run out of chalk during a repetitive distribution process. If we naively simulat | coderashu1 | NORMAL | 2024-12-26T08:21:01.158593+00:00 | 2024-12-26T08:21:01.158593+00:00 | 21 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
The problem revolves around efficiently determining which student will run out of chalk during a repetitive distribution process. If we naively simulate the entire process, it may take too long for large inputs. Instead, we can optimize the solution by observing patterns:
The total chalk consumption of one full round is the sum of the chalk array.
The value of k modulo this total sum determines how much chalk remains after completing as many full rounds as possible.
After reducing k with the modulo operation, we only need to simulate the process for the remaining chalk to find the specific student.
# Approach
<!-- Describe your approach to solving the problem. -->
Calculate Total Chalk Requirement for a Full Round:
Compute the sum of the `chalk array (sum)`.
Reduce `k`:
Calculate `k % sum.` This gives the remaining chalk after completing as many full rounds as possible.
Simulate the Remaining Process:
Iterate through the chalk array and subtract each student's chalk usage from the remaining` chalk (sum)`.
When sum becomes less than the current student's chalk requirement, that student will be the one who needs to replace the chalk.
Return the Index:
Return the `index` of the student who runs out of chalk.
# 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 chalkReplacer(vector<int>& chalk, int k) {
int ans;
//find sum
long long sum=0;
int n=chalk.size();
for(int i=0;i<n;i++){
sum+=chalk[i];
}
//Modulo
sum=k%sum;
//0---->n check and sub
for(int i=0;i<n;i++){
if(sum>=chalk[i]){
sum=sum-chalk[i];
}else{
ans=i;
break;
}
}
return ans;
}
};
``` | 2 | 0 | ['C++'] | 0 |
find-the-student-that-will-replace-the-chalk | O(N) - Beats 93.23% in Cpp - Basic Math | on-beats-9323-in-cpp-basic-math-by-jamiy-ng3s | Intuition\nThe problem asks us to determine which student will be unable to continue drawing with chalk once the chalk runs out. Since each student uses a certa | Jamiyat | NORMAL | 2024-09-02T18:23:39.523157+00:00 | 2024-09-02T18:24:33.133533+00:00 | 0 | false | # Intuition\nThe problem asks us to determine which student will be unable to continue drawing with chalk once the chalk runs out. Since each student uses a certain amount of chalk in a cyclic manner, a key observation is that the total amount of chalk used by all students in one complete cycle can be used to reduce the problem size. This leads to a more efficient solution by reducing the number of iterations required.\n\n# Approach\n- **Calculate the total chalk usage per cycle**: First, compute the sum of chalk used by all students in one cycle. This is the total amount of chalk needed to go through one complete round of students.\n\n- **Reduce the problem size**: Use the modulo operation to determine the effective remaining chalk (`k % ChalkSum`). This step is crucial because it significantly reduces the number of chalk pieces we need to consider, eliminating full cycles.\n\n- **Determine the student**: Iterate through the students, subtracting their chalk usage from the remaining chalk. The first student whose chalk requirement exceeds the remaining chalk will be the answer, as they won\'t have enough chalk to proceed.\n\n# Complexity\n- **Time complexity**: The time complexity is \\(O(n)\\), where \\(n\\) is the number of students. This is because we first compute the sum of the chalk array and then perform a linear scan through the students.\n\n- **Space complexity**: The space complexity is \\(O(1)\\) since we\'re only using a few extra variables for calculations and not any additional space proportional to the input size.\n\n# Code\n```cpp\nclass Solution {\npublic:\n int chalkReplacer(vector<int>& chalk, int k) {\n long long ChalkSum = 0; \n\n // Calculate total chalk used in one complete cycle\n for(auto i: chalk)\n ChalkSum += i;\n\n // Reduce k to the remaining chalk after full cycles\n k %= ChalkSum;\n\n // Determine which student will run out of chalk\n for(int i = 0; i < chalk.size(); ++i){\n if(k < chalk[i])\n return i;\n k -= chalk[i];\n }\n return 0;\n }\n};\n```\n\n---\n | 2 | 0 | ['C++'] | 0 |
find-the-student-that-will-replace-the-chalk | Easy Solution in O(n) time.Beats 99% | easy-solution-in-on-timebeats-99-by-prat-vjy5 | Approach\nwe Know then after all student are done we revert back to the first student so we need to take the modulo of total sum of array.\nNow we need to trave | pratyush4competative | NORMAL | 2024-09-02T18:05:04.012713+00:00 | 2024-09-02T18:05:04.012740+00:00 | 9 | false | # Approach\nwe Know then after all student are done we revert back to the first student so we need to take the modulo of total sum of array.\nNow we need to traverse the array only once and check where K becomes less than chalk[i].\n\n# Complexity\n- Time complexity:O(n)\n\n- Space complexity:O(n)\n# Code\n```cpp []\nclass Solution {\npublic:\n int chalkReplacer(vector<int>& chalk, int k) {\n ios_base::sync_with_stdio(false);\n cin.tie(NULL);\n int n = chalk.size();\n vector<long long>s;\n long long sum = 0;\n for(int i = 0;i<n;i++){\n sum+=chalk[i];\n s.push_back(sum);\n }\n int x = k%sum;\n int i = 0;\n cout<<x<<endl;\n while(x>0 && i<n){\n x-=chalk[i];\n if(x<0){\n return i;\n }\n i++;\n }\n return i;\n }\n};\n``` | 2 | 0 | ['Array', 'Simulation', 'Prefix Sum', 'C++'] | 0 |
find-the-student-that-will-replace-the-chalk | Solution By Dare2Solve | Detailed Explanation | Clean Code | solution-by-dare2solve-detailed-explanat-ybx3 | Explanation []\nauthorslog.com/blog/BPkbFkKeLD\n\n# Code\n\ncpp []\nclass Solution {\npublic:\n int chalkReplacer(vector<int>& chalk, int k) {\n long | Dare2Solve | NORMAL | 2024-09-02T17:47:34.147474+00:00 | 2024-09-02T17:47:34.147511+00:00 | 15 | false | ```Explanation []\nauthorslog.com/blog/BPkbFkKeLD\n```\n# Code\n\n```cpp []\nclass Solution {\npublic:\n int chalkReplacer(vector<int>& chalk, int k) {\n long long total = 0;\n for (int c : chalk) {\n total += c;\n }\n\n k %= total;\n\n for (int i = 0; i < chalk.size(); ++i) {\n if (chalk[i] > k) {\n return i;\n }\n k -= chalk[i];\n }\n\n return -1; // This should never be reached\n }\n};\n```\n\n```python []\nclass Solution:\n def chalkReplacer(self, chalk, k):\n total = sum(chalk)\n k %= total\n \n for i in range(len(chalk)):\n if chalk[i] > k:\n return i\n k -= chalk[i]\n \n return -1 # This should never be reached\n\n```\n\n```java []\nclass Solution {\n public int chalkReplacer(int[] chalk, int k) {\n int i = 0;\n while (chalk[i] <= k) {\n k -= chalk[i];\n i = (i >= chalk.length - 1) ? 0 : i + 1;\n }\n return i;\n }\n}\n```\n\n```javascript []\nvar chalkReplacer = function (chalk, k) {\n\n let i = 0\n while (chalk[i] <= k) {\n k -= chalk[i]\n\n if (i >= chalk.length - 1) i = 0\n else i++\n }\n return i\n};\n``` | 2 | 0 | ['Binary Search', 'Simulation', 'Python', 'C++', 'Java', 'Python3', 'JavaScript'] | 0 |
find-the-student-that-will-replace-the-chalk | Simple to follow (1 ms Beats 99.36%) | simple-to-follow-1-ms-beats-9936-by-neha-jov8 | 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 | NehaSinghal032415 | NORMAL | 2024-09-02T17:43:11.241999+00:00 | 2024-09-02T17:43:11.242029+00:00 | 6 | 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```java []\nclass Solution {\n public int chalkReplacer(int[] chalk, int k) {\n int sum=0;\n for(int i=0;i<chalk.length;i++){\n sum=sum+chalk[i];\n if(k<sum)return i;\n }\n k=k%sum;\n if(k==0)return 0;\n sum=0;\n for(int i=0;i<chalk.length;i++){\n sum=sum+chalk[i];\n if(k<sum)return i;\n }\n return -1;\n }\n}\n``` | 2 | 0 | ['Array', 'Java'] | 0 |
find-the-student-that-will-replace-the-chalk | Efficient Solution to Find the Student Who Will Replace the Chalk with O(n) Complexity | efficient-solution-to-find-the-student-w-r8t2 | 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 | shoaibkhalid65 | NORMAL | 2024-09-02T17:21:23.416843+00:00 | 2024-09-02T17:21:23.416879+00:00 | 11 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nThis program runs in 1ms and beats 99.36%\n\n- Space complexity:\nThis program\'s memory is 60MB and beats 41%\n\n# Code\n```java []\nclass Solution {\n public int chalkReplacer(int[] chalk, int k) {\n int res=0;\n long sum=0;\n for(int a:chalk){\n sum+=a;\n }\n if(sum<k){\n k=(int)(k%sum);\n }\n if(k==sum){\n return 0;\n }\n for(int i=0;i<chalk.length;i++){\n if(chalk[i]>k){\n res=i;\n break;\n }else{\n k=k-chalk[i];\n }\n }\n return res;\n }\n}\n``` | 2 | 0 | ['Java'] | 1 |
find-the-student-that-will-replace-the-chalk | 🔥99.36% beats🔥with proof 💫 easy java solution | 9936-beatswith-proof-easy-java-solution-iu9oy | \n# Approach\n Describe your approach to solving the problem. \n- Sum Calculation: First, calculate the total chalk required for one complete round by summing u | Jayaanthsr | NORMAL | 2024-09-02T15:10:22.678691+00:00 | 2024-09-02T15:10:22.678718+00:00 | 4 | false | \n# Approach\n<!-- Describe your approach to solving the problem. -->\n- **Sum Calculation:** First, calculate the total chalk required for one complete round by summing up the chalk each student uses.\n- **Modulo Operation:** Use modulo operation to find the remaining chalk after all possible full rounds. This is equivalent to reducing the problem to a smaller equivalent one where the remaining chalk is less than one full round.\n- **Identify the Student:** Traverse through the list of students, subtracting the chalk each student uses from the remaining chalk. The first student who cannot be given the required amount of chalk will be the answer.\nComplexity\n\n# Complexity\n- Time complexity:\n$$O(n)$$ \n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```java []\nclass Solution {\n public int chalkReplacer(int[] chalk, int k) {\n long sum=0;\n for(int i: chalk){\n sum=sum+i;\n }\n sum=k%sum;\n int i=0;\n for(i=0;i<chalk.length;i++){\n sum=sum-chalk[i];\n if(sum<0){\n return i;\n }\n }\n return i;\n }\n}\n```\n\n\n | 2 | 0 | ['Java'] | 0 |
find-the-student-that-will-replace-the-chalk | Easy to Understand || C++ Code | easy-to-understand-c-code-by-brightworld-gvon | Code\ncpp []\nclass Solution {\npublic:\n int chalkReplacer(vector<int>& chalk, int k) {\n int n = chalk.size();\n int i=0;\n long long | brightworld | NORMAL | 2024-09-02T15:07:26.421162+00:00 | 2024-09-02T15:07:26.421194+00:00 | 4 | false | # Code\n```cpp []\nclass Solution {\npublic:\n int chalkReplacer(vector<int>& chalk, int k) {\n int n = chalk.size();\n int i=0;\n long long sum = 0;\n for(auto it : chalk){\n sum += it;\n }\n\n int round = k%sum;\n while(i<n){\n if(round>=chalk[i]){\n round -= chalk[i];\n }\n else{\n break;\n }\n i++;\n }\n return i;\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
find-the-student-that-will-replace-the-chalk | Python Solution | python-solution-by-pushkar91949-cgnj | 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 | Pushkar91949 | NORMAL | 2024-09-02T14:36:34.006291+00:00 | 2024-09-02T14:36:34.006323+00:00 | 29 | 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```python3 []\nclass Solution:\n def chalkReplacer(self, chalk: List[int], k: int) -> int:\n s = sum(chalk)\n rem = k % s\n i = 0\n while rem > 0 and i < len(chalk):\n rem -= chalk[i]\n if rem < 0:\n return i\n i += 1\n return i\n \n``` | 2 | 0 | ['Array', 'Python3'] | 2 |
find-the-student-that-will-replace-the-chalk | Easy Solution in java | easy-solution-in-java-by-nishapandey4-i5qh | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nUsed the prefix sum and | NishaPandey4 | NORMAL | 2024-09-02T13:12:37.873081+00:00 | 2024-09-02T13:12:37.873128+00:00 | 3 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nUsed the prefix sum and modulo reduction approach to efficiently determine the student who will need chalk next.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->Time Complexity: O(n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nSpace Complexity: O(1)O(1)\n\n# Code\n```java []\nclass Solution {\n public int chalkReplacer(int[] chalk, int k) {\n while(k>=0){\n for (int i=0;i<chalk.length;i++){ \n if(k<chalk[i])\n return i;\n k=k-chalk[i];\n }\n }\n return -1;\n }\n}\n``` | 2 | 0 | ['Java'] | 0 |
find-the-student-that-will-replace-the-chalk | Who Runs Out of Chalk First? An O(n) Solution C++ | who-runs-out-of-chalk-first-an-on-soluti-ni5m | Intuition\n Describe your first thoughts on how to solve this problem. \n- The problem involves a circular usage of chalk by students. The challenge is to deter | ROHAN_SHETTY | NORMAL | 2024-09-02T13:04:56.991203+00:00 | 2024-09-02T13:04:56.991229+00:00 | 20 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- The problem involves a circular usage of chalk by students. The challenge is to determine which student will run out of chalk when given a certain amount, k. Each student uses a specific amount of chalk from the chalk array, and they use it in a cyclic manner. To solve this problem efficiently, we can reduce the amount of k by removing full cycles of total chalk usage.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Calculate Total Chalk Usage: First, compute the total chalk used in one complete cycle by summing up all elements in the chalk array. Let\'s call this total sum.\n- Reduce k: Since the chalk usage is cyclic, reduce k using the modulus operation **k %= sum**. This step removes full cycles of chalk usage, leaving a smaller k value that is easier to handle.\n- Find the Student: Iterate through the chalk array and keep subtracting each student\'s chalk usage from k. The first time k becomes less than the chalk needed by a student, that student is the one who will run out of chalk. Return the index of that student.\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```cpp []\nclass Solution {\npublic:\n int chalkReplacer(vector<int>& chalk, int k) {\n int n = chalk.size();\n long long int sum = 0;\n \n for(auto i : chalk)\n {\n sum+=i;\n }\n \n k %= sum;\n \n for (int i = 0; i < n; ++i) {\n if (k < chalk[i]) {\n return i;\n }\n k -= chalk[i];\n }\n \n return -1;\n }\n};\n\n``` | 2 | 0 | ['C++'] | 0 |
find-the-student-that-will-replace-the-chalk | Solution | solution-by-neelgohel-0j66 | Approach\n\n1. Calculate Total Chalk Needed:\nIterate through the chalk array and sum up the chalk required by each student to complete one full cycle of the pr | NeelGohel | NORMAL | 2024-09-02T11:54:19.512998+00:00 | 2024-09-02T11:54:19.513031+00:00 | 11 | false | # Approach\n\n1. Calculate Total Chalk Needed:\nIterate through the chalk array and sum up the chalk required by each student to complete one full cycle of the problem-solving process. Let\'s denote this sum as totalChalk.\n\n2. Determine Effective Chalk Usage:\nCompute the remaining chalk after accounting for all complete cycles. This is done using the modulo operation: remainingChalk = k % totalChalk.\n\n3. Find the Student Who Will Replace the Chalk:\nIterate through the chalk array and keep a running total of chalk usage. Once this running total exceeds the remaining chalk (remainingChalk), the current student will be the one who will need to replace the chalk.\n\n# Complexity\n- Time complexity:O(n).\n\n- Space complexity:O(1).\n\n# Code\n```java []\nclass Solution {\n public int chalkReplacer(int[] chalk, int k) {\n int n = chalk.length;\n double totalChalk = 0;\n\n for (int i = 0; i < n; i++) {\n totalChalk += chalk[i];\n }\n\n k %= totalChalk;\n for (int i = 0; i < n; i++) {\n if (k < chalk[i]) {\n return i;\n }\n k -= chalk[i];\n }\n\n return -1;\n }\n}\n\n``` | 2 | 0 | ['Java'] | 0 |
find-the-student-that-will-replace-the-chalk | Java Simple Solution | java-simple-solution-by-shree_govind_jee-gjdt | Complexity\n- Time complexity:O(2*n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity:O(n)\n Add your space complexity here, e.g. O(n) \n\n# Co | Shree_Govind_Jee | NORMAL | 2024-09-02T07:53:55.682694+00:00 | 2024-09-02T07:53:55.682769+00:00 | 81 | false | # Complexity\n- Time complexity:$$O(2*n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int chalkReplacer(int[] chalk, int k) {\n int len = chalk.length;\n\n // First Calculate the total of Array\n long sum = 0;\n for (int chalks : chalk) {\n sum += chalks;\n }\n\n // Now finding the reminder of "k" by divding by "sum" of CHALK\n // such that,\n // Remaining will be Iterated....\n long rem = k % sum;\n\n // Last Check by iterator.....\n // if chalk[i]>rem ---> return index of that Chalk\n // else decrease the remainder by chalk[i]\n for (int i = 0; i < len; i++) {\n if (chalk[i] > rem) {\n return i;\n }\n rem -= chalk[i];\n }\n return 0;\n }\n}\n``` | 2 | 0 | ['Array', 'Math', 'Binary Search', 'Simulation', 'Prefix Sum', 'Java'] | 0 |
find-the-student-that-will-replace-the-chalk | easy c++ solution |🔥🔥 | easy-c-solution-by-sarthakgoel84-i0d1 | 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 | sarthakgoel84 | NORMAL | 2024-09-02T07:40:34.987655+00:00 | 2024-09-02T07:40:34.987693+00:00 | 23 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int chalkReplacer(vector<int>& chalk, int k) {\n long long total=0;\n for(auto i:chalk){\n total+=i;\n if(total>INT_MAX){\n total=INT_MAX;\n break;\n }\n }\n k=k%total;\n int ans=0;\n while(true){\n if(k>=chalk[ans]){\n k-=chalk[ans];\n ans++;\n }\n else{\n break;\n }\n }\n return ans;\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
find-the-student-that-will-replace-the-chalk | Simplest Approach || Brute Force || T.C=O(n) || S.C=O(1) | simplest-approach-brute-force-tcon-sco1-q25nr | Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem revolves around determining which student will run out of chalk first after | prayashbhuria931 | NORMAL | 2024-09-02T06:51:03.871512+00:00 | 2024-09-02T06:51:03.871542+00:00 | 23 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem revolves around determining which student will run out of chalk first after a large number of rounds. Initially, it might seem that we need to simulate each round, but this would be inefficient given the large possible value of k. Instead, we can optimize by first reducing k modulo the total chalk usage, which allows us to focus only on the remainder and thus, the final round.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Calculate the total chalk usage: First, sum up the total amount of chalk required by all students in one complete round.\n2. Reduce the problem: Instead of simulating k rounds, calculate the remainder when k is divided by the total chalk usage (k % sum). This remainder is the effective amount of chalk we need to distribute.\n3. Identify the student: Iterate through the list of chalk usage by each student, subtracting from the remainder until we find the student who cannot receive enough chalk.\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```cpp []\nclass Solution {\npublic:\n int chalkReplacer(vector<int>& chalk, int k) {\n \n long long int sum=0;\n\n for(auto ele:chalk)\n {\n sum+=ele;\n }\n\n int rem=k%sum;\n\n for(int i=0;i<chalk.size();i++)\n {\n if(chalk[i]>rem) return i;\n rem-=chalk[i];\n }\n return 0;\n }\n};\n```\n\n | 2 | 0 | ['Array', 'Simulation', 'C++'] | 0 |
find-the-student-that-will-replace-the-chalk | first approach TLE inuition lene mein laga thoda help discussion is a gr8 platform :D | first-approach-tle-inuition-lene-mein-la-3n0t | 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 | yesyesem | NORMAL | 2024-09-02T06:34:45.475474+00:00 | 2024-09-02T06:34:45.475504+00:00 | 6 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int chalkReplacer(vector<int>& chalk, int k) {\nlong long sum=0;\n \n for(int i=0;i<chalk.size();i++)\n {\n sum+=chalk[i];\n }\n\n k=k%sum;\n\n for(int i=0;i<chalk.size();i++)\n {\n if(k<chalk[i])\n return i;\n \n k-=chalk[i];\n }\n \n \n \n return 0;\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
find-the-student-that-will-replace-the-chalk | Javascript beginner friendly solution with explanation. | javascript-beginner-friendly-solution-wi-ppdr | Intuition\n Describe your first thoughts on how to solve this problem. \nThis problem involves determining which student will be the first to run out of chalk a | sajjan_shivani | NORMAL | 2024-09-02T05:32:28.426192+00:00 | 2024-09-02T05:32:28.426224+00:00 | 49 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis problem involves determining which student will be the first to run out of chalk after a given total supply (k) is distributed in a round-robin fashion among the students. Each student in the chalk array requires a certain amount of chalk.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Calculate Total Chalk Requirement for One Round:\n\n- The total amount of chalk required for one complete round through all the students is the sum of the chalk array.\n- This tells us how much chalk is consumed when every student is given a problem exactly once.\n2. Reduce k Using Modulus Operation:\n\n- Since the students are given problems in a cyclic order, we only care about the leftover chalk after completing full cycles. Thus, compute k % totalChalk.\n- This effectively reduces k to the remaining amount of chalk after as many full rounds as possible.\n3. Find the Student Who Runs Out of Chalk:\n\n- Iterate through the chalk array from the beginning. For each student, check if the remaining chalk (k) is less than the chalk required by that student (chalk[i]).\n- If so, that student will be the one to replace the chalk. Return the index of that student.\n- Otherwise, subtract the student\'s chalk requirement from k and move to the next student.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n), where n is the number of students. This is due to the single pass required to compute the total chalk and another pass to find the student who will replace the chalk.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1), as we only use a few extra variables.\n\n# Code\n```javascript []\n/**\n * @param {number[]} chalk\n * @param {number} k\n * @return {number}\n */\nvar chalkReplacer = function(chalk, k) {\n // Calculate the total chalk required for one complete round\n let totalChalk = 0;\n for (let i = 0; i < chalk.length; i++) {\n totalChalk += chalk[i];\n }\n\n // Reduce k to a value less than totalChalk\n k %= totalChalk;\n\n // Iterate through the chalk requirements\n for (let i = 0; i < chalk.length; i++) {\n if (k < chalk[i]) {\n return i; // Found the student who will run out of chalk\n }\n k -= chalk[i]; // Subtract the current student\'s chalk requirement\n }\n};\n\n``` | 2 | 0 | ['JavaScript'] | 0 |
find-the-student-that-will-replace-the-chalk | Easy C++ Solution | easy-c-solution-by-pradeepredt-a2td | Intuition\n Describe your first thoughts on how to solve this problem. \nReduce the problem by eliminating complete rounds of chalk consumption, then find the f | pradeepredt | NORMAL | 2024-09-02T04:46:23.983486+00:00 | 2024-09-02T04:46:23.983518+00:00 | 24 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nReduce the problem by eliminating complete rounds of chalk consumption, then find the first student who can\'t use the remaining chalk.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n-> Calculate the total chalk consumption in one complete round (sum).\n-> Reduce k using k %= sum to handle only the remaining chalk after complete rounds.\n-> Iterate through the chalk array, subtracting each student\'s chalk usage from k.\n-> If a student\'s chalk usage exceeds the remaining k, return that student\'s index.\n-> Return the index of the first student who can\'t continue due to insufficient chalk.\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```cpp []\nclass Solution {\npublic:\n int chalkReplacer(vector<int>& chalk, int k) {\n int n=chalk.size();\n long long sum=0;\n for(int i: chalk)sum+=i;\n k%=sum;\n int j=-1;\n for(int i=0;i<n;i++){\n if(chalk[i]>k){\n j=i;\n break;\n }\n k-=chalk[i];\n }\n return j;\n }\n};\n```\n\n | 2 | 0 | ['Array', 'Simulation', 'C++'] | 0 |
find-the-student-that-will-replace-the-chalk | beats 100 % users using prefix sum method............. | beats-100-users-using-prefix-sum-method-v7l6l | \n\n# Code\njava []\nclass Solution {\n public int chalkReplacer(int[] chalk, int k) {\n return getChalkReplacer(chalk, k);\n }\n public int get | rudramanikanta02 | NORMAL | 2024-09-02T04:43:41.528233+00:00 | 2024-09-02T04:43:41.528261+00:00 | 16 | false | \n\n# Code\n```java []\nclass Solution {\n public int chalkReplacer(int[] chalk, int k) {\n return getChalkReplacer(chalk, k);\n }\n public int getChalkReplacer(int[] chalk, int remaining_chalk) {\n int chalk_sum = 0;\n for (int i = 0; i < chalk.length; i++) {\n chalk_sum += chalk[i];\n if (remaining_chalk - chalk_sum < 0) {\n return i;\n }\n }\n return getChalkReplacer(chalk, (int) (remaining_chalk % chalk_sum));\n }\n}\n``` | 2 | 0 | ['Java'] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.