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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
describe-the-painting | 🐍 O(nlogn) || Clean and Concise || 97% faster || Well-Explained with Example 📌📌 | onlogn-clean-and-concise-97-faster-well-1mcjq | IDEA :\nWe are finding all the starting and ending points. These points score we are storing in our dictinoary and after sorting all the poiints we are making o | abhi9Rai | NORMAL | 2021-08-10T19:22:36.599026+00:00 | 2021-08-10T19:22:36.599061+00:00 | 632 | false | ## IDEA :\nWe are finding all the starting and ending points. These points score we are storing in our dictinoary and after sorting all the poiints we are making our result array.\n\nEg: segments = [[1,7,9],[6,8,15],[8,10,7]]\nThere are 5 coordinates get involved. 1, 6, 7, 8, 10 respetively.\n* At coordinate 1, only the segment [1, 7, 9] start here. Thus, the current mixed color will be 0 + 9 = 9\n* At coordinate 6, another segment [6, 8, 15] start here. Thus, the current mixed color will be 9 + 15 = 24\n* At coordinate 7, the segment [1, 7, 9] is end here. Thus, the current mixed color will be 24 - 9 = 15\n* At coordinate 8, the segment [6, 8, 15] is end here and the segment [8, 10, 7] also start here. Thus, the current mixed color will be 15 - 15 + 7 = 7\n* At coordinate 10, the segment [8, 10, 7] is end here. Thus, the current mixed color will be 0\n* So we know the final answer should be [1,6,9], [6,7,24], [7,8,15], [8,10,7].\n\n\'\'\'\n\n\tclass Solution:\n def splitPainting(self, segments: List[List[int]]) -> List[List[int]]:\n \n dic = defaultdict(int)\n for s,e,c in segments:\n dic[s]+=c\n dic[e]-=c\n \n st=None\n color=0\n res = []\n for p in sorted(dic):\n if st is not None and color!=0:\n res.append([st,p,color])\n color+=dic[p]\n st = p\n \n return res\n\nThanks and Happy Coding !!\uD83E\uDD1E\nFeel free to ask and **Upvote** if you got any help. \uD83E\uDD17 | 12 | 1 | ['Python', 'Python3'] | 1 |
describe-the-painting | [C++][MAP] - Intuitive Solution | Explained | cmap-intuitive-solution-explained-by-mor-2j27 | Intuition: Similar to prefix sum\n\nNote - Assuming arr[] initialized to zero\n\nCase 1: No overlapping Interval\nGiven [1,4,7] => We can have arr[1] = 7 and ar | morning_coder | NORMAL | 2021-07-25T02:03:23.506467+00:00 | 2021-07-26T08:22:09.264049+00:00 | 985 | false | **Intuition:** Similar to prefix sum\n\nNote - Assuming arr[] initialized to zero\n\n**Case 1: No overlapping Interval**\nGiven [1,4,7] => We can have arr[1] = 7 and arr[4] = -7 so when we will add-up elements, it will be something like : \narr[1] = 7\narr[2] = 0+arr[1] = 7\narr[3] = 0 + arr[2] = 7\narr[4] = -7 + arr[3] = 0\n\n**Case 2: Overlapping Intervals**\nGiven [1,4,7] and [1,10,8] => We can have arr[1] += 7 and arr[4] -=7 , arr[1] += 8 and arr[10] -= 8\narr[1] = 7+8 = 15\narr[2] = 0+arr[1] = 15\narr[3] = 0 + arr[2] = 15\narr[4] = -7 + arr[3] = 8\narr[5] = 0 + arr[4] = 8\narr[6] = 0 + arr[5] = 8\narr[7] = 0 + arr[6] = 8\narr[8] = 0 + arr[7] = 8\narr[9] = 0 + arr[8] = 8\narr[10] = 0 + arr[9] = -8 + 8 = 0\n\nFor this question, instead of storing them into array, we are storing in map (sorted) and populating elements with the above logic.\n\n```\ntypedef long long ll;\n\nclass Solution {\npublic:\n vector<vector<long long>> splitPainting(vector<vector<int>>& segments) {\n vector<vector<ll> > ans;\n map<int,ll> um;\n \n for(auto s : segments){\n um[s[0]] += s[2];\n um[s[1]] -= s[2];\n }\n bool flag = false;\n pair<int,ll> prev;\n ll curr = 0;\n \n for(auto x : um){\n if(flag == false){\n prev = x;\n curr += x.second;\n flag = true;\n continue;\n }\n \n vector<ll> v = {prev.first,x.first,curr};\n prev = x;\n if(curr)\n ans.push_back(v);\n curr += x.second;\n \n }\n return ans;\n }\n};\n``` | 9 | 0 | ['C', 'C++'] | 3 |
describe-the-painting | C++ Solution, same idea as meeting rooms ii. | c-solution-same-idea-as-meeting-rooms-ii-xwsh | same idea as https://github.com/jianchaoche/leetcode-algorithm-solution/blob/master/0001-0999/0253_meeting-rooms-ii.md\n\nclass Solution {\npublic:\n vector< | chejianchao | NORMAL | 2021-07-24T16:01:13.297395+00:00 | 2021-07-24T16:01:13.297439+00:00 | 1,512 | false | same idea as https://github.com/jianchaoche/leetcode-algorithm-solution/blob/master/0001-0999/0253_meeting-rooms-ii.md\n```\nclass Solution {\npublic:\n vector<vector<long long>> splitPainting(vector<vector<int>>& segments) {\n map<long long, long long> cnt;\n for(auto s : segments) {\n cnt[s[0]] += (long long)s[2];\n cnt[s[1]] -= (long long)s[2];\n }\n long long sum = 0;\n long long begin = 0;\n vector<vector<long long> > ans;\n for(auto it : cnt) {\n long long prevColorSum = sum;\n sum += it.second;\n long long end = it.first;\n if(prevColorSum > 0){\n ans.push_back({begin, end, prevColorSum});\n }\n begin = it.first;\n }\n return ans;\n }\n};\n``` | 9 | 1 | [] | 5 |
describe-the-painting | [Python] single array | python-single-array-by-vegishanmukh7-d19f | Take a single array, initiate it with 0\'s. Increment every start point by color and decrement corresponding end point by color. continuously go on adding the i | vegishanmukh7 | NORMAL | 2021-07-24T16:19:17.890706+00:00 | 2021-07-24T16:19:33.136945+00:00 | 376 | false | Take a single array, initiate it with 0\'s. Increment every start point by color and decrement corresponding end point by color. continuously go on adding the i-1\'th point color to i\'th point color, the end value would be taken care as we are decrementing the end by cost. Now whenever we find a point as end or start we consider it as break point and add it to the final answer array and make current pointer to this position.\nNote: If the value is 0 , then it means there is no paint over there because the color value starts from 1(given in the constraints)\n\nCode: \n```\nclass Solution:\n def splitPainting(self, segments: List[List[int]]) -> List[List[int]]:\n mx=0 #maximum (end point)\n mi=10e5 #minimum (start point)\n start,end=set(),set() #start and end points set\n for i in segments:\n start.add(i[0])\n end.add(i[1])\n mx=max(mx,i[1])\n mi=min(mi,i[0])\n l=[0]*(mx+1) #single array\n for i in segments:\n l[i[0]]+=i[2] #increment start point by color\n l[i[1]]-=i[2] #decrementing end point by colot\n for i in range(1,len(l)):\n l[i]+=l[i-1] #adding all the colors at point i\n ans=[] \n val=l[mi] #start color cost\n k=mi #start point\n for i in range(mi+1,len(l)):\n if(i in start or i in end):\n if(l[i-1]!=0): #if color is there appending it to ans, or else no color\n ans.append([k,i,l[i-1]])\n k=i #changing start point to current index\n return ans\n``` | 6 | 0 | [] | 1 |
describe-the-painting | Java solution | java-solution-by-saurabh_kl-1d13 | Find the mixColor for each index\n\n\npublic List<List<Long>> splitPainting(int[][] segments) {\n int n = 1_00_005;\n // mix color array for findi | saurabh_kl | NORMAL | 2021-07-24T16:08:41.364746+00:00 | 2021-07-24T16:12:57.611136+00:00 | 474 | false | Find the mixColor for each index\n\n```\npublic List<List<Long>> splitPainting(int[][] segments) {\n int n = 1_00_005;\n // mix color array for finding the net value of color at each index\n long mix[] = new long[n];\n \n // Using treeset so that duplicates will not store and we get all breakpoints in soted order\n TreeSet<Integer> breakPoints = new TreeSet<>();\n \n for(int i=0; i<segments.length; i++){\n int start = segments[i][0];\n int end = segments[i][1];\n int color = segments[i][2]; \n breakPoints.add(start);\n breakPoints.add(end);\n mix[start]+=color;\n mix[end]-=color;\n }\n \n // finding net color at each index using prefix sum\n for(int i=1; i<n; i++){\n mix[i] += mix[i-1];\n }\n \n List<List<Long>> res = new ArrayList<>();\n \n long prev = breakPoints.first();\n breakPoints.remove((int)prev);\n \n for(int x : breakPoints){\n long curr = x;\n List<Long> list = new ArrayList<>();\n list.add(prev);\n list.add(curr);\n list.add(mix[(int)prev]);\n if(mix[(int)prev] != 0) // Do not consider if net color is 0 given in question\n res.add(list);\n prev = curr;\n }\n return res;\n }\n``` | 6 | 0 | ['Tree', 'Ordered Set', 'Java'] | 0 |
describe-the-painting | [Python 3] Sweep line | python-3-sweep-line-by-yourick-aoel | \npython3 []\nclass Solution:\n def splitPainting(self, segments: List[List[int]]) -> List[List[int]]:\n d = defaultdict(int)\n\n for start, en | yourick | NORMAL | 2024-01-17T17:19:38.668496+00:00 | 2024-01-17T17:19:38.668524+00:00 | 278 | false | \n```python3 []\nclass Solution:\n def splitPainting(self, segments: List[List[int]]) -> List[List[int]]:\n d = defaultdict(int)\n\n for start, end, color in segments:\n d[start] += color\n d[end] -= color\n\n res, color, items = [], 0, sorted(d.items())\n for i in range(len(items)-1):\n color += items[i][1]\n if color > 0:\n res.append([items[i][0], items[i+1][0], color])\n \n return res\n``` | 5 | 0 | ['Line Sweep', 'Python', 'Python3'] | 0 |
describe-the-painting | Simple Java Solution | PriorityQueue | O(nlogn) | simple-java-solution-priorityqueue-onlog-88dt | \nclass Solution {\n public List<List<Long>> splitPainting(int[][] segments) {\n int n = segments.length;\n Arrays.sort(segments,(a,b) -> a[0] | sagarguptay2j | NORMAL | 2021-07-28T10:57:18.257383+00:00 | 2021-07-28T10:57:18.257423+00:00 | 338 | false | ```\nclass Solution {\n public List<List<Long>> splitPainting(int[][] segments) {\n int n = segments.length;\n Arrays.sort(segments,(a,b) -> a[0] == b[0]?a[1]-b[1] : a[0]-b[0]);\n List<List<Long>> res = new ArrayList<>();\n PriorityQueue<int[]> pq = new PriorityQueue<>((a,b) -> a[1]-b[1]);\n int start = segments[0][0], i =0;\n long sum = 0;\n while(i < n || !pq.isEmpty()){\n if(pq.isEmpty()) start = segments[i][0];\n while(i < n && (segments[i][0] <= start || pq.isEmpty())) {\n sum += segments[i][2];\n pq.offer(segments[i++]);\n }\n List<Long> toadd = new ArrayList<>();\n int end = pq.peek()[1];\n if(i < n)\n end = Math.min(end,segments[i][0]);\n toadd.add((long)start);toadd.add((long)end);toadd.add(sum);\n res.add(toadd);\n start = end;\n while(!pq.isEmpty() && pq.peek()[1] <= start) sum -= pq.poll()[2];\n }\n \n return res;\n }\n}\n``` | 5 | 0 | [] | 0 |
describe-the-painting | [Python 3] - Difference Array + Sweep Line | python-3-difference-array-sweep-line-by-33lcc | 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 | dolong2110 | NORMAL | 2023-05-06T17:04:33.547415+00:00 | 2024-10-13T20:38:03.150339+00:00 | 232 | 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(NlogN)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(N)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def splitPainting(self, segments: List[List[int]]) -> List[List[int]]:\n d = collections.defaultdict(int)\n for s, e, p in segments:\n d[s] += p\n d[e] -= p\n res = []\n paints = sorted(d.items())\n l_prev, p_prev = paints[0]\n for l, p in paints[1:]:\n if p_prev != 0:\n res.append([l_prev, l, p_prev])\n l_prev, p_prev = l, p + p_prev\n return res\n``` | 4 | 0 | ['Array', 'Prefix Sum', 'Python3'] | 1 |
describe-the-painting | Simple C++ solution || Easy to understand approach || Using maps | simple-c-solution-easy-to-understand-app-ch5n | \n\n# Code\n\nclass Solution {\npublic:\n vector<vector<long long>> splitPainting(vector<vector<int>>& seg) {\n vector<vector<long long>> ans;\n | prathams29 | NORMAL | 2023-07-03T03:48:55.470997+00:00 | 2023-07-03T03:48:55.471025+00:00 | 273 | false | \n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<long long>> splitPainting(vector<vector<int>>& seg) {\n vector<vector<long long>> ans;\n map<long long,long long> m;\n long long int i=0;\n while(i<seg.size())\n {\n m[seg[i][0]]+=seg[i][2];\n m[seg[i][1]]-=seg[i][2];\n i++;\n }\n long long int j=0,k=0;\n for(auto x:m)\n {\n long long int prev=j;\n j+=x.second;\n if(prev>0)\n ans.push_back({k,x.first,prev});\n k=x.first;\n }\n return ans;\n }\n};\n``` | 3 | 0 | ['C++'] | 0 |
describe-the-painting | Explained - Clean and Concise Line Sweep | Python | explained-clean-and-concise-line-sweep-p-v8f4 | Simple line sweep using a dictionary. Though the order is not important according to the poblem statement but in order for us to leverage the points we marked o | akanksha_kale | NORMAL | 2022-10-30T21:22:17.739779+00:00 | 2022-10-30T21:22:51.748850+00:00 | 247 | false | Simple line sweep using a dictionary. Though the order is not important according to the poblem statement but in order for us to leverage the points we marked on the line, the line needs to be swept from left to right to get the color value right. The color would change at every point we encounter on the line, irrespective of what the sum is at the point. So, I used the previous point and the color value and added it to the final result : painting when I discover a new point. \n\n```\nclass Solution:\n def splitPainting(self, segments: List[List[int]]) -> List[List[int]]:\n line = defaultdict(int)\n \n for start, end, color in segments:\n line[start] += color\n line[end] -= color\n \n painting = []\n prev_color, prev_point = 0, 0\n \n for point in sorted(line.keys()):\n if prev_color:\n painting.append([prev_point, point, prev_color])\n prev_point = point\n prev_color += line[point]\n \n return painting\n```\n\nI practiced this pattern by solving problems from https://leetcode.com/discuss/study-guide/2166045/line-sweep-algorithms. Thanks [c0D3M](https://leetcode.com/c0D3M/) for the article! | 3 | 0 | ['Python'] | 0 |
describe-the-painting | C++ Single Traversal Line Sweep w/ explanation | c-single-traversal-line-sweep-w-explanat-cdme | With different color combinations, we might get the same sum. So we cant just check the sum. \nThe key lies in the fact that different segments will have a dif | varkey98 | NORMAL | 2021-08-06T06:39:43.938497+00:00 | 2021-08-06T06:39:43.938533+00:00 | 229 | false | With different color combinations, we might get the same sum. So we cant just check the sum. \nThe key lies in the fact that **different segments will have a different color**. So whenever a point is marked on that line, that is either a segment\'s start or end. \nCombining both of these, I used a C++ Map bc, it will have all the points which have been referenced atleast once. So even if we have the same sum, if the map has a particular point, it means that is start or end of a segment. The remaining part is a classical line sweep. With one catch, **whenever the sum is 0, that means from here on there\'s nothing painted till the next point in the line**.\n\n```\n#define ll long long\nvector<vector<long long>> splitPainting(vector<vector<int>>& arr) \n{\n\tmap<int,ll> line;\n\tfor(auto& x:arr)\n\t{\n\t\tline[x[0]]+=x[2];\n\t\tline[x[1]]-=x[2];\n\t}\n\tvector<vector<ll>> ret;\n\tll prev=-1,color=0;\n\tfor(auto itr=line.begin();itr!=line.end();++itr)\n\t{\n\t\tif(prev!=-1)\n\t\t ret.push_back({prev,itr->first,color});\n\t\tprev=itr->first;\n\t\tcolor+=itr->second;\n\t\tif(color==0)\n\t\t\tprev=-1;\n\t}\n\treturn ret;\n}\n``` | 3 | 1 | ['C'] | 0 |
describe-the-painting | [C++] Explained with some initial Thought process | c-explained-with-some-initial-thought-pr-d5tz | Thoughtprocess:\n - It was tough to figure out the logic in contest as first thought would be to iterate segment wise add add/Sub color accordingling but it | avinashvrm | NORMAL | 2021-07-29T04:40:57.535786+00:00 | 2021-07-29T04:43:49.674473+00:00 | 230 | false | Thoughtprocess:\n - It was tough to figure out the logic in contest as first thought would be to iterate segment wise add add/Sub color accordingling but it will make things more complex.\n- So instead of that approach, we should observe every start and end points are reflecting a interval and can combine with either of them, so why not treat them seperately\n- Now, how to treat them seperately?(and calculate right-color value for them)\n- why not store them seperately with thier color value\n```\nclass Solution {\npublic:\n vector<vector<long long>> splitPainting(vector<vector<int>>& seg) \n {\n vector<vector<int>> s;\n //Storing every start and end point along with thier color,(1,-1) is for tracking color\n //if we encouter multiple start then we add those color and make a Seg, and wif we encounter any end point than we know the prev color has to be removed as it will not contribute for net segment\n \n for(auto &x : seg)\n {\n s.push_back({x[0],1,x[2]});\n s.push_back({x[1],-1,x[2]});\n }\n sort(s.begin(),s.end());//\n vector<vector<long long>> res;\n long long color = s[0][2];//startin with first segment\n for(int i=1;i<s.size();i++)\n {\n if(s[i][0] > s[i-1][0] && color!=0)// if color is zero it means there\'s no painting\n res.push_back({s[i-1][0],s[i][0],color});\n \n color = color + s[i][1]*s[i][2];// handling color value based on contribution for next segment\n }\n return res;\n \n }\n};\nHope it helped. | 3 | 0 | [] | 1 |
describe-the-painting | C++| map | O(nlogn) time | c-map-onlogn-time-by-warlock1997-nhk7 | map<long long,long long> is necessary or else you\'ll get runtime error because of integer overflow\n\n\n\n/**\n * @author : archit \n * @GitHub : arc | warlock1997 | NORMAL | 2021-07-25T11:11:03.657841+00:00 | 2021-07-28T09:08:12.996039+00:00 | 316 | false | `map<long long,long long> is necessary or else you\'ll get runtime error because of integer overflow`\n\n\n```\n/**\n * @author : archit \n * @GitHub : archit-1997\n * @email : architsingh456@gmail.com\n * @file : describeThePainting.cpp\n * @created : Sunday Jul 25, 2021 15:58:16 IST\n */\n\n\n#include <bits/stdc++.h>\nusing namespace std;\n\nclass Solution {\npublic:\n vector<vector<long long>> splitPainting(vector<vector<int>>& segments) {\n map<long long int,long long int> color;\n for(vector<int> v : segments){\n color[v[0]]+=v[2];\n color[v[1]]-=v[2];\n }\n\n vector<vector<long long>> ans;\n auto it=color.begin();\n long long int start,end;\n long long int sum=0;\n for(auto it=color.begin();it!=color.end();it++){\n end=it->first;\n if(sum!=0)\n ans.push_back({start,end,sum});\n start=end;\n sum+=it->second;\n }\n return ans;\n }\n};\n\n\n``` | 3 | 0 | [] | 1 |
describe-the-painting | C++ Approach Easiest Explanation | c-approach-easiest-explanation-by-divyat-abzg | Heyaaaa ,\n\nIn the contest, 2 solutions hit me, one was based on interval merge , and other was based on Line Sweep. Line sweep was more optimised as merge int | Divyatez | NORMAL | 2021-07-25T10:11:33.599820+00:00 | 2021-07-25T10:11:33.599865+00:00 | 244 | false | Heyaaaa ,\n\nIn the contest, 2 solutions hit me, one was based on interval merge , and other was based on Line Sweep. Line sweep was more optimised as merge interval would require sorting.\n\n**Note : In ques interval are half open [ ) , but I have used [ ] in explantion.**\n\nSo what is logic, \n\n**LineSweep**\n\nIf i want to add c from [a,b]\nthen, on arr[a] add c and arr[b+1] , subtract c\n\nhow does this help in getting final value:\nconsider\n[0,0,0,0,0] intial array , query is [1,2,3], ie add 3 in [1,2]\n\nso it becomes arr[1]+=3 and arr[2+1]-=3\nwe get\n[0,3,0,-3,0]\nnow do traverse from 0 to n , and keep adding elemet at that pos to array \n\n\t\tarr-> [ 0 , 3 , 0 , -3 , 0 ]\n\t add\t 0 3 3 0 0 \n\nSo we get value at positon .\nFor multiple queries of adding values in interval, just do this for all queries , then at final calculate this sum\n\nIn question [a,b) is given , ie b is not included in interval , so we update value at position a and b ( not b+1 as b is also not included)\n\n\n**How does it work in getting interval:**\n\nNow how to work this in interval ->**ALL CONTINIOUS SAME VALUES IN ONE INTERVAL** \n\nExample for [0,0, 1, 1, 2, 3, 3] -> [{0,1},{2,3},{4,4},{5,6}]\n\nSo first use map , mark all positions as explained above.\n```\nmp[segments[i][0]]+=segments[i][2];\nmp[segments[i][1]]-=segments[i][2];\n```\n\nThen traverse and add all intervals with non zero values and add then in vector\n\n**Extra Case:**\nConsider a position , if it has non zero value and If adding/subtracting value of current interval makes it zero , then we have to make a break there as given by second sample test case in question.\n\n```\nInput: segments = [[1,4,5],[1,4,7],[4,7,1],[4,7,11]]\nOutput: [[1,4,12],[4,7,12]]\nExplanation: The painting can be described as follows:\n- [1,4) is colored {5,7} (with a sum of 12) from the first and second segments.\n- [4,7) is colored {1,11} (with a sum of 12) from the third and fourth segments.\nNote that returning a single segment [1,7) is incorrect because the mixed color sets are different.\n```\n\nSo , while inputing value also mark positions where we are gonna make 0 , after adding or substracting\n\n\n```\n\n if(mp[segments[i][0]]==(-1)*segments[i][2])\n mark[segments[i][0]]=1;\n mp[segments[i][0]]+=segments[i][2];\n if(mp[segments[i][1]]==segments[i][2])\n mark[segments[i][1]]=1;\n mp[segments[i][1]]-=segments[i][2];\n```\n\n\n\nI have commented the code , if you have no time to read above stuff::\n```\n#define pii pair<int,int>\n#define s second\n#define f first\n#define piii pair<int,pii> \n\nclass Solution {\npublic:\n \n long long min(long long a, long long b)\n {\n if(a<=b)\n return a;\n return b;\n }\n long long max(long long a, long long b)\n {\n if(a>=b)\n return a;\n return b;\n }\n\t\n vector<vector<long long>> splitPainting(vector<vector<int>>& segments) {\n \n unordered_map<long long,long long>mp;\n long long mini = INT_MAX;\n long long maxi = INT_MIN;\n unordered_map<long long,long long>mark;\n for(int i=0;i<segments.size();i++)\n {\n\t\t\t// If adding makes 0 at that position , mark it \n if(mp[segments[i][0]]==(-1)*segments[i][2])\n mark[segments[i][0]]=1;\n\t\t\t//add at position to mark increment by line sweep\n mp[segments[i][0]]+=segments[i][2];\n\t\t\t\n\t\t\t// Similar as above\n if(mp[segments[i][1]]==segments[i][2])\n mark[segments[i][1]]=1;\n\t\t\t\t\n\t\t\t// Bracket is half open so , we have to suptract at end , not at end+1\n mp[segments[i][1]]-=segments[i][2];\n\t\t\t\n mini = min(mini,segments[i][0]);\n maxi = max(maxi,segments[i][1]);\n }\n long long val=mp[mini];\n long long st = mini;\n vector<vector<long long >>ans;\n for(long long i=mini+1;i<=maxi;i++)\n {\n\t\t\t// If that position is not zero then the value of iterval will be changed so we need to break\n\t\t\t// If the pos is 0 , but according to sample test 2 , it is actuay end and begin of new interval , so its like 1-1 =0, ie it became 0 by adding and subtracting same values at that position \n if(mp[i]!=0||mark[i]==1)\n {\n\t\t\t\t// Only if value is non zero we consider it as interval\n if(val!=0)\n {\n vector<long long>curr ={st,i,val};\n ans.push_back(curr);\n }\n\t\t\t\t// Mark new start and add value\n st=i;\n val+=mp[i];\n }\n \n }\n return ans;\n \n }\n};\n```\n\nLOL, I didnt knew it was called line swep, I just called it with random names.\nFeel free to drop suggestions and doubts :) | 3 | 0 | ['C'] | 0 |
describe-the-painting | Simple Line Sweep | simple-line-sweep-by-rsrs3-ooef | \nclass Solution:\n def splitPainting(self, segments: List[List[int]]) -> List[List[int]]:\n pointMap = collections.defaultdict(int)\n for segm | rsrs3 | NORMAL | 2021-07-25T01:34:08.580386+00:00 | 2021-07-25T01:34:08.580417+00:00 | 202 | false | ```\nclass Solution:\n def splitPainting(self, segments: List[List[int]]) -> List[List[int]]:\n pointMap = collections.defaultdict(int)\n for segment in segments:\n x, y, v = segment\n pointMap[x] += v\n pointMap[y] -= v\n \n res = []\n curr, prev = 0, -1\n for point in sorted(pointMap.keys()):\n if curr:\n res.append([prev, point, curr])\n prev = point\n curr += pointMap[point]\n \n return res\n \n \n \n``` | 3 | 0 | [] | 0 |
describe-the-painting | [JAVA] Easy Explanation With Comments. T=O(NlogN), S=O(N) | java-easy-explanation-with-comments-tonl-o973 | \n/*\nSince we have distinct colors, so every segment of the answer will result from either starting or ending of any segment(s) in the input.\nNote, we do not | pramitb | NORMAL | 2021-07-24T16:11:20.190139+00:00 | 2021-07-24T16:15:59.916001+00:00 | 276 | false | ```\n/*\nSince we have distinct colors, so every segment of the answer will result from either starting or ending of any segment(s) in the input.\nNote, we do not include any segment where the mix color sum equals 0, which means that segment is not a part of the painting.\nNow, two or more of the segments of the input can have equal starting or ending point(s).\nWe first separate the starting and ending points of all the segments of the input and then pick them up greedily starting with the minimum.\nWhen any segment of the input starts or any segment of the input ends, we close close one painting segment and insert it in the answer list.\nPlease go through the code and comments for better understanding.\n*/\nclass Solution {\n public List<List<Long>> splitPainting(int[][] seg) {\n \n // separating the starting and ending points of the input segments, along with their respective colors.\n List<int[]>start=new ArrayList<>();\n List<int[]>end=new ArrayList<>();\n for(int[] i:seg){\n start.add(new int[]{i[0],i[2]}); // [starting_point,color]\n end.add(new int[]{i[1],i[2]}); // [ending_point,color]\n }\n \n // sorting each of the above lists so that I can pick up any segment greedily from the minimum to the maximum.\n Collections.sort(start,(a,b)->Integer.compare(a[0],b[0]));\n Collections.sort(end,(a,b)->Integer.compare(a[0],b[0]));\n \n List<List<Long>> ans=new ArrayList<>();\n List<Long> temp;\n \n \n int i=0,j=0,n=seg.length;\n long val=0l,pre=start.get(0)[0],post,v;\n boolean flag,started=false;\n while(i<n){\n /*\n In each iteration of this loop at least one segment of the inputends or at least one segment of the input begins.\n So, we need to insert one segment in the answer list. \n */\n \n if(started){\n // boolean started will determine if at least one iteration of this has happened before.\n // If not, we will not add any segment in the answer list.\n \n temp=new ArrayList<>();\n temp.add(pre);\n post=Math.min(end.get(j)[0],start.get(i)[0]); // next update point.\n temp.add(post);\n temp.add(val);\n if(val>0) // we add only when sum of colors in the mix array is positive, that is, this segment belongs to this painting.\n ans.add(temp);\n pre=post; // ending point of this segment marks the starting point of next.\n }\n started=true;\n \n v=Math.min(end.get(j)[0],start.get(i)[0]); // \'v\' stores the next update point.\n // This will determine the ending of current segment and beginning of next segment. Note \'v\' has same value as \'post\'.\n \n while(j<n&&end.get(j)[0]==v){\n val-=(long)end.get(j)[1]; // we subtract when a segment ends.\n j++; \n }\n while(i<n&&start.get(i)[0]==v){\n val+=(long)start.get(i)[1]; // we add when a segment begins.\n i++; \n }\n }\n \n // The below loop will run when no more segments of the input are yet to start. The functions within are similar as sbove.\n while(j<n){\n temp=new ArrayList<>();\n temp.add(pre);\n post=end.get(j)[0];\n temp.add(post);\n temp.add(val);\n if(val>0)\n ans.add(temp);\n pre=post;\n v=end.get(j)[0];\n while(j<n&&end.get(j)[0]==v){\n val-=(long)end.get(j)[1];\n j++; \n }\n }\n return ans;\n }\n}\n// T=O(NlogN) S=O(N)\n// Please share and upvote if this helps you.\n``` | 3 | 1 | [] | 0 |
describe-the-painting | ❇ describe-the-painting Images👌 🏆O(N)❤️ Javascript🎯 Memory👀14.29%🕕 ++Explanation✍️🔴🔥✅💪🙏👉 | describe-the-painting-images-on-javascri-03k0 | Time Complexity: O(N)\nSpace Complexity: O(N)\n\nvar splitPainting = function (segments) {\n let max = -Infinity;\n const timeStartToColorMapping = {};\n | anurag-sindhu | NORMAL | 2024-06-17T15:58:59.150192+00:00 | 2024-06-17T16:00:21.382732+00:00 | 79 | false | Time Complexity: O(N)\nSpace Complexity: O(N)\n```\nvar splitPainting = function (segments) {\n let max = -Infinity;\n const timeStartToColorMapping = {};\n const timeEndToColorMapping = {};\n for (const [start, end, color] of segments) {\n max = Math.max(max, start, end);\n if (!timeStartToColorMapping[start]) {\n timeStartToColorMapping[start] = 0;\n }\n timeStartToColorMapping[start] += color;\n if (!timeEndToColorMapping[end]) {\n timeEndToColorMapping[end] = 0;\n }\n timeEndToColorMapping[end] += color;\n }\n let potential = 0;\n let potentialStartedIndex = null;\n const output = [];\n for (let index = 1; index <= max; index++) {\n if (timeEndToColorMapping[index]) {\n if (potential) {\n output.push([potentialStartedIndex, index, potential]);\n }\n potential -= timeEndToColorMapping[index];\n potentialStartedIndex = index;\n }\n if (timeStartToColorMapping[index]) {\n if (potentialStartedIndex !== null && potentialStartedIndex !== index && potential) {\n output.push([potentialStartedIndex, index, potential]);\n }\n potentialStartedIndex = index;\n potential += timeStartToColorMapping[index];\n }\n }\n return output;\n};\n```\n\nFor Input:\n```\n[[4, 16, 12], [9, 10, 15], [18, 19, 13], [3, 13, 20], [12, 16, 3], [2, 10, 10], [3, 11, 4], [13, 16, 6]]\n```\n\n\n![Uploading file...]()\n\n\n | 2 | 0 | ['JavaScript'] | 0 |
describe-the-painting | Just like Shifting Letters-2. Prefix Sum Trick. Commented Code | just-like-shifting-letters-2-prefix-sum-l7jpk | First read the answer to Shifting Letters II to understand the concept better: https://leetcode.com/problems/shifting-letters-ii/discuss/2463201/Shifting-Letter | aryan899gupta | NORMAL | 2022-08-22T10:09:09.654000+00:00 | 2022-08-22T10:11:46.096505+00:00 | 553 | false | First read the answer to Shifting Letters II to understand the concept better: https://leetcode.com/problems/shifting-letters-ii/discuss/2463201/Shifting-Letters-2.-Prefix-Sum-Method\n\n```\nclass Solution {\npublic:\n vector<vector<long long>> splitPainting(vector<vector<int>>& segments) \n {\n int n=segments.size();\n int l=INT_MAX;\n int r=INT_MIN;\n long long len=1e5;\n vector <long long> store(len+1);\n unordered_set <int> st; //For elements which are at the points given in sample testcase 3\n \n for(int i=0; i<n; i++)\n {\n l=min(l, segments[i][0]);\n r=max(r, segments[i][1]);\n \n store[segments[i][0]]+=segments[i][2];\n store[segments[i][1]]-=segments[i][2];\n \n //For sample testcase 3 kind of elements\n if(segments[i][0]!=0 && st.find(segments[i][0])!=st.end())\n st.erase(segments[i][0]);\n if(segments[i][1]!=0 && st.find(segments[i][1])!=st.end())\n st.erase(segments[i][1]);\n if(store[segments[i][0]]==0)\n st.insert(segments[i][0]);\n if(store[segments[i][1]]==0)\n st.insert(segments[i][1]);\n }\n \n //Prefix sum trick as seen in questions like shifitng letters-2\n for(int i=l+1; i<=r; i++) \n store[i]+=store[i-1];\n \n vector <vector<long long>> ans;\n long long curr=store[l];\n int pos=l;\n for(int i=l; i<=r; i++)\n {\n if(store[i]!=curr || i==r || st.find(i)!=st.end())\n {\n ans.push_back({pos, i, curr});\n pos=i;\n curr=store[i];\n if(ans.back()[2]==0) //To remove the unpainted sections\n ans.pop_back();\n }\n }\n \n return ans;\n }\n};\n``` | 2 | 0 | ['C', 'Prefix Sum', 'C++'] | 0 |
describe-the-painting | Java | Sweeping in Line | Similar to Meeting rooms | java-sweeping-in-line-similar-to-meeting-2tq6 | Create a list of segments with starting and ending points\n2. sort the list\n3. Traverse the list and keep adding the new result based on the current traversing | trigodeepak | NORMAL | 2021-08-14T12:01:02.442448+00:00 | 2021-08-14T12:01:36.428756+00:00 | 343 | false | 1. Create a list of segments with starting and ending points\n2. sort the list\n3. Traverse the list and keep adding the new result based on the current traversing value (See code for detailed conditions)\n\n```\nclass Solution {\n //class for segments \n class Seg{\n int val,end;\n int color;\n boolean isStart;\n public Seg(int val,int end,int color, boolean isStart){\n this.val = val;\n this.end = end;\n this.color = color;\n this.isStart = isStart; \n }\n public String toString(){\n return "[" + val+" "+end+" "+color+" "+isStart+"]";\n }\n }\n public List<List<Long>> splitPainting(int[][] segments) {\n List<List<Long>> res = new ArrayList();\n \n List<Seg> list = new ArrayList();\n \n //making a list of segments\n for(int[] segment : segments){\n list.add(new Seg(segment[0],segment[1],segment[2],true));\n list.add(new Seg(segment[1],segment[1],segment[2],false)); \n }\n \n //Sorting the segments\n Collections.sort(list,(a,b)->{return a.val-b.val;});\n \n //System.out.println(list);\n \n //Iterating over list to combine the elements\n for(Seg curr: list){\n int len = res.size();\n if(curr.isStart){\n //if the segment is starting there could be three ways \n if(res.size()>0 && res.get(len-1).get(0)==curr.val){\n //if starting point of two things is same\n List<Long> temp = res.get(len-1);\n temp.set(1,Math.max(temp.get(1),curr.end));\n temp.set(2,(long)(temp.get(2)+curr.color));\n }else if(res.size()>0 && res.get(len-1).get(1)>curr.val){\n //if there is a start in between create a new segment of different color \n List<Long> prev = res.get(len-1);\n prev.set(1,(long)curr.val);\n List<Long> temp = new ArrayList();\n temp.add((long)curr.val); temp.add((long)curr.end); temp.add((long)(prev.get(2)+curr.color));\n res.add(temp);\n }else{\n //Add a new value if nothing is present in result\n List<Long> temp = new ArrayList();\n temp.add((long)curr.val); temp.add((long)curr.end); temp.add((long)curr.color);\n res.add(temp);\n }\n }else{\n if(res.size()>0 && res.get(len-1).get(0)==curr.val){\n //if ending point of 2 segments is same\n Long prevColor = res.get(len-1).get(2);\n res.get(len-1).set(2,(long)(prevColor-curr.color));\n }\n else if(res.size()>0 && res.get(len-1).get(1)>curr.val){\n //if there is a ending in between create a new segment of different color \n Long prevColor = res.get(len-1).get(2);\n Long prevEnd = res.get(len-1).get(1);\n res.get(len-1).set(1,(long)curr.val);\n \n List<Long> temp = new ArrayList();\n temp.add((long)curr.val); temp.add((long)prevEnd); temp.add((long)(prevColor-curr.color));\n res.add(temp);\n }\n }\n //System.out.println(res+" "+curr);\n \n }\n //System.out.println(res);\n return res; \n \n }\n}\n``` | 2 | 0 | ['Java'] | 0 |
describe-the-painting | C++ Line Sweep without abusing the constraints nLogn | c-line-sweep-without-abusing-the-constra-kfcf | We create an vector of pairs for each start/end point. For start points we store start index and +color, for end we store end index and -color.\nThen we sort th | MotuMonk | NORMAL | 2021-07-25T09:19:51.799046+00:00 | 2021-07-25T09:19:51.799091+00:00 | 134 | false | We create an vector of pairs for each start/end point. For start points we store start index and +color, for end we store end index and -color.\nThen we sort the array and go index by index, adding to our result vector if current color != 0 and current start != index store in our vector of pairs. At each index we move the current start and current color.\n```\nclass Solution {\npublic:\n vector<vector<long long>> splitPainting(vector<vector<int>>& segments) {\n\n std::vector<std::pair<int, int>> sweeper;\n\n for (auto& segment : segments)\n {\n sweeper.push_back({ segment[0],segment[2] });\n sweeper.push_back({ segment[1],-segment[2] });\n }\n std::vector<std::vector<long long>> result;\n int curr_start = 0; // current start\n long long curr_color = 0; // curr_color\n std::sort(sweeper.begin(),sweeper.end());\n for (int i = 0; i < sweeper.size(); i++)\n {\n\n if (curr_color != 0 && curr_start != sweeper[i].first)\n result.push_back({ curr_start, sweeper[i].first, curr_color }); // store current color\n \n curr_color += sweeper[i].second; //increment/decrement color \n curr_start = sweeper[i].first; //update curr_start \n }\n\n return result;\n }\n};\n```\n | 2 | 0 | [] | 0 |
describe-the-painting | CPP SOLUTION | PREFIX-SUM LOGIC | cpp-solution-prefix-sum-logic-by-gaurav_-waz2 | \nclass tNode{\n public:\n long long data, startData;\n bool start, end;\n\n tNode(){\n data=0;\n startData=0;\n | gaurav_k268 | NORMAL | 2021-07-24T19:27:34.669030+00:00 | 2021-07-24T19:27:34.669066+00:00 | 185 | false | ```\nclass tNode{\n public:\n long long data, startData;\n bool start, end;\n\n tNode(){\n data=0;\n startData=0;\n start=false;\n end=false;\n }\n};\n\nclass Solution {\npublic:\n vector<vector<long long>> splitPainting(vector<vector<int>>& segments) {\n tNode arr[100005];\n\n for(auto &x:segments){\n arr[x[0]].start=true;\n arr[x[0]].startData+=x[2];\n arr[x[0]].data+=x[2];\n\n arr[x[1]].data-=x[2];\n arr[x[1]].end=true;\n }\n\n vector<vector<long long>> result;\n\n int lastIndex=1, sum=0;\n for(int i=1; i<100005; i++){\n arr[i].data += arr[i-1].data;\n\n if((arr[i].end || (lastIndex!=i && arr[i].start)) && (arr[i-1].data != 0)){\n result.push_back({lastIndex, i, arr[i-1].data});\n lastIndex=i;\n }\n \n if(arr[i].start){\n lastIndex=i;\n }\n }\n\n return result;\n }\n};\n``` | 2 | 0 | [] | 0 |
describe-the-painting | Java Solution With explanation | java-solution-with-explanation-by-sandip-zbq6 | We consider a boolean array which marks the change whenever a segment starts or ends. This means the colors were added or removed and hence we need to consider | sandip_jana | NORMAL | 2021-07-24T16:21:51.488401+00:00 | 2021-07-24T18:23:32.345197+00:00 | 289 | false | We consider a boolean array which marks the change whenever a segment starts or ends. This means the colors were added or removed and hence we need to consider from this point a new segment altogether.\n\nReason i mark both start and end is because :\nCase 1 : **when a segment starts color is added**\n\t```previousSum + color ```\nCase 2 : **when a segment end color is removed**\n\t```previousSum - color ```\n\nSo in both cases sum is bound to change and we can hop to a new set of colors altogether and hence i use this intuition to avoid the third test case given in problem statement.\n\nAlso use the line sweep approach to compute the sum of color mix for each point in O(n) time.\n\nSo for every start index i keep moving ahead my end pointer till the time i saw some start or end of a segment was detected. that\'s how detect segments and finally i track the color using the sweep array. if value is above zero then thats a valid segment.\n\nTC - O ( 100000 ) \nSC = O ( 100000 ) \nbecause thats the maximum end of a segment .\n\n```\nclass Solution {\n public List<List<Long>> splitPainting(int[][] segments) {\n\t\tList<List<Long>> ans = new ArrayList<>();\n\t\tint MAX = 100010;\n\t\tlong sweep[] = new long[MAX+1];\n\t\tboolean change[] = new boolean[MAX+1];\n\t\tfor (int i=0 ; i<segments.length ; i++) {\n\t\t\tint start = segments[i][0];\n\t\t\tint end = segments[i][1];\n\t\t\tsweep[start]+=segments[i][2];\n\t\t\tsweep[end]-=segments[i][2];\n\t\t\tchange[start] = change[end] = true;\n\t\t}\n\n\t\tfor (int i=1 ; i<MAX ; i++) {\n\t\t\tsweep[ i ] += sweep[ i - 1 ];\n\t\t}\n \n\t\tfor (int start=1 ; start<=MAX ; start++) {\n\t\t\tlong currentColor = sweep[start];\n\t\t\tint end = start+1;\n\t\t\twhile ( end<=MAX && !change[end] ) {\n\t\t\t\t++end;\n\t\t\t}\n if (currentColor > 0) {\n\t\t\t Long a[] = new Long[]{ new Long(start) , new Long(end) , currentColor};\n\t\t\t ans.add( Arrays.asList(a) );\n }\n\t\t\tif ( end == MAX ) break;\n\t\t\tstart = end-1;\n\t\t}\n\n\t\treturn ans;\n\t}\n}\n```\n\nUpvote if you liked! | 2 | 0 | ['Java'] | 1 |
describe-the-painting | (C++) 1943. Describe the Painting | c-1943-describe-the-painting-by-qeetcode-1xwj | \n\nclass Solution {\npublic:\n vector<vector<long long>> splitPainting(vector<vector<int>>& segments) {\n vector<vector<int>> vals; \n for (au | qeetcode | NORMAL | 2021-07-24T16:04:06.515444+00:00 | 2021-07-24T16:04:06.515492+00:00 | 408 | false | \n```\nclass Solution {\npublic:\n vector<vector<long long>> splitPainting(vector<vector<int>>& segments) {\n vector<vector<int>> vals; \n for (auto& segment : segments) {\n vals.push_back({segment[0], segment[2]}); \n vals.push_back({segment[1], -segment[2]}); \n }\n sort(vals.begin(), vals.end()); \n \n int prev = 0; \n long long prefix = 0; \n vector<vector<long long>> ans; \n \n for (auto& val : vals) {\n if (prev < val[0] && prefix) ans.push_back({prev, val[0], prefix}); \n prev = val[0]; \n prefix += val[1]; \n }\n return ans; \n }\n};\n``` | 2 | 0 | ['C'] | 1 |
describe-the-painting | I hacked the problem | Difference array | O(N) | i-hacked-the-problem-difference-array-on-7r4q | Initially i was using sums alone, but then 5+7, and 11+1 are not same according to the problem so i check if the product is also same or not. \n\nclass Solution | IamVaibhave53 | NORMAL | 2021-07-24T16:01:26.396911+00:00 | 2021-07-24T16:03:15.876581+00:00 | 449 | false | Initially i was using sums alone, but then 5+7, and 11+1 are not same according to the problem so i check if the product is also same or not. \n```\nclass Solution {\npublic:\n //I HACKED THE PROBLEM, i am sure this wasn\'t the intended solution. xD\n vector<vector<long long>> splitPainting(vector<vector<int>>& segments) {\n vector<long long int> diff(1e5+1);\n vector<long double> st(1e5+1,1);\n vector<vector<long long>> ans;\n for(auto &x:segments){\n st[x[0]]*=x[2];\n st[x[1]]/=x[2];\n diff[x[0]]+=x[2];\n diff[x[1]]-=x[2];\n }\n for(int i=1;i<=1e5;i++){\n st[i]*=st[i-1];\n diff[i]+=diff[i-1];\n }\n long long int s=0,i=0;\n while(i<=1e5){\n if(diff[i]==0){\n i++;\n continue;\n }\n int j=i;\n while(j<=1e5 and diff[j]==diff[i] and st[j]==st[i]){\n j++;\n }\n ans.push_back({i,j,diff[i]});\n i=max(j,i+1);\n }\n return ans;\n }\n};\n``` | 2 | 0 | [] | 1 |
describe-the-painting | DIFFERENCE ARRAY EASY AND READABLE CODE | difference-array-easy-and-readable-code-u9z3e | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | Ronak2k24 | NORMAL | 2025-01-08T11:13:13.841005+00:00 | 2025-01-08T11:13:13.841005+00:00 | 105 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
vector<vector<long long>> splitPainting(vector<vector<int>>& segments) {
int n=segments.size();
set<int>st;
for(int i=0;i<n;i++){
st.insert(segments[i][0]);
st.insert(segments[i][1]);
}
vector<long long>v(1e5+1);
for(int i=0;i<n;i++){
v[segments[i][0]]+=segments[i][2];
v[segments[i][1]]-=segments[i][2];
}
int m=v.size();
for(int i=1;i<m;i++)v[i]+=v[i-1];
vector<int>s(st.begin(),st.end());
//int s=v.size();
//for(int i=0;i<v.size();i++)cout<<v[i]<<" ";
vector<vector<long long>>ans;
for(int i=1;i<s.size();i++){
long long end=s[i];
long long start=s[i-1];
long long cost=v[s[i-1]];
if(cost!=0)ans.push_back({start,end,cost});
}
return ans;
}
};
``` | 1 | 0 | ['C++'] | 0 |
describe-the-painting | linear time and space complexity (java) | linear-time-and-space-complexity-java-by-8sof | Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(n)\n\n# Code\n\nclass Solution {\n\n public List<List<Long>> splitPainting(int[][] segments) {\n | sanjay-kr-commit | NORMAL | 2024-03-06T16:31:48.482925+00:00 | 2024-03-06T16:31:48.482955+00:00 | 38 | false | # Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(n)\n\n# Code\n```\nclass Solution {\n\n public List<List<Long>> splitPainting(int[][] segments) {\n // calculate line dimension\n int min = Integer.MAX_VALUE ,\n max = Integer.MIN_VALUE ;\n for ( int[] segment : segments ) {\n if ( min > segment[0] ) min = segment[0] ;\n if ( max < segment[1] ) max = segment[1] ;\n }\n // create a line\n long [] line = new long[ max - min + 1 ] ;\n int [] coordinates = new int[ max - min + 1 ] ;\n // fill adjacent points\n for ( int [] segment : segments ) {\n coordinates[segment[0]-min] = 1 ;\n coordinates[segment[1]-min] = 1 ;\n line[segment[0]-min] += segment[2] ;\n line[segment[1]-min] -= segment[2] ;\n }\n // detect mixed color\n int prev = 0 ;\n long color = line[prev] ;\n ArrayList<List<Long>> painting = new ArrayList<>() ;\n for ( int i = 1 ; i < coordinates.length ; i++ ) {\n if ( coordinates[i] == 0 ) continue;\n if ( color != 0 ) {\n ArrayList<Long> newSegment = new ArrayList<>();\n newSegment.add((long) prev + min);\n newSegment.add((long) i + min);\n newSegment.add(color);\n painting.add( newSegment ) ;\n }\n color += line[i] ;\n prev = i ;\n }\n if ( prev != line.length -1 ) {\n ArrayList<Long> newSegment = new ArrayList<>() ;\n newSegment.add((long) prev+min ) ;\n newSegment.add((long) line.length+min ) ;\n newSegment.add( color ) ;\n painting.add( newSegment ) ;\n }\n return painting ;\n }\n\n}\n``` | 1 | 0 | ['Java'] | 0 |
describe-the-painting | C++ solution sort by start and end then check at all points | c-solution-sort-by-start-and-end-then-ch-u724 | 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 | Rushikesh_1218 | NORMAL | 2023-04-05T08:54:59.768438+00:00 | 2023-04-05T08:54:59.768489+00:00 | 45 | 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)$$ --> $$O(nlogn)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --> $$O(n)$$\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<long long>> splitPainting(vector<vector<int>>& seg) {\n vector<vector<long long>> ans;\n vector<pair<int,int>> s;\n vector<pair<int,int>> e;\n for(int i=0;i<seg.size();i++){\n s.push_back({seg[i][0],seg[i][2]});\n e.push_back({seg[i][1],seg[i][2]});\n }\n sort(s.begin(),s.end());\n sort(e.begin(),e.end());\n int min = s[0].first;\n int max = e[e.size()-1].first;\n //cout<<min<<max<<endl;\n int x=0,y=0;\n long long color = 0;\n vector<long long> temp;\n for(int i=min;i<=max;i++){\n if(color==0) temp.clear();\n if(y<e.size()){\n \n if(i==e[y].first && temp.size()!=0){\n temp.push_back(i);\n temp.push_back(color);\n ans.push_back(temp);\n temp.clear();\n }\n if(i==e[y].first && temp.size()==0 && color!=0) temp.push_back(i);\n while(y<e.size() && i==e[y].first){\n color -= e[y].second;\n y++;\n }\n }\n \n if(x<s.size()){\n if(i==s[x].first && temp.size()!=0 && temp[0]!=i){\n temp.push_back(i);\n temp.push_back(color);\n ans.push_back(temp);\n temp.clear();\n }\n if(i==s[x].first && temp.size()==0) temp.push_back(i);\n while(x<s.size() && i==s[x].first){\n color += s[x].second;\n x++;\n }\n } \n }\n return ans;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
describe-the-painting | C++ / bucket and map / two simple solutions with explanation | c-bucket-and-map-two-simple-solutions-wi-qoiz | solution 1: map\nWe use ordered map to sort the paint start and end time and use curc to calulate aggregated sum of color that we currently have.\nAlso, record | pat333333 | NORMAL | 2022-05-11T04:25:06.242243+00:00 | 2022-05-11T04:25:26.189723+00:00 | 85 | false | # solution 1: map\nWe use ordered map to sort the paint start and end time and use `curc` to calulate aggregated sum of color that we currently have.\nAlso, record last position `last` to be used in the start position of result segment.\n\nIf `curc` != 0 and `last` != -1, we have a new result segment.\n\n`n`: size of `segments`\n* time: `O(nlogn)`\n* space: `O(n)`\n\n```\nclass Solution {\npublic:\n using ll = long long;\n vector<vector<long long>> splitPainting(vector<vector<int>>& segments) {\n map<int,ll> m;\n for (auto &segment: segments) {\n m[segment[0]] += segment[2];\n m[segment[1]] -= segment[2];\n }\n vector<vector<ll>> res;\n ll curc = 0, last = -1;\n for (auto &[time, color]: m) {\n if (last != -1 && curc) {\n res.push_back({last, time, curc});\n }\n curc += color;\n last = time;\n }\n return res;\n }\n};\n```\n# solution 2: bucket\nWe can also use bucket to sort the segments. Note that we need another data structure `end` to record whether current position is start or end position from `segments`.\n`n`: size of `segments`\n* time: `O(n+1e5)`\n* space: `O(1e5)`\n\n```\nclass Solution {\npublic:\n using ll = long long;\n vector<vector<long long>> splitPainting(vector<vector<int>>& segments) {\n vector<ll> m(100001);\n vector<bool> end(100001);\n for (auto &segment: segments) {\n m[segment[0]] += segment[2];\n m[segment[1]] -= segment[2];\n end[segment[0]] = end[segment[1]] = true;\n }\n vector<vector<ll>> res;\n ll curc = 0, last = -1;\n for (int i = 1; i <= 100000; ++i) {\n if (!end[i]) {\n continue;\n }\n if (last != -1 && curc) {\n res.push_back({last, i, curc});\n }\n curc += m[i];\n last = i;\n }\n return res;\n }\n};\n``` | 1 | 0 | [] | 0 |
describe-the-painting | c++ | line sweep | easy to understand | c-line-sweep-easy-to-understand-by-crabb-fiep | \n vector<vector<long long>> splitPainting(vector<vector<int>>& seg) {\n int p=1e5+2;\n vector<long long> sum(p,0);\n vector<bool> change(p | crabbyD | NORMAL | 2022-02-17T00:07:44.501182+00:00 | 2022-02-17T00:07:44.501231+00:00 | 175 | false | ```\n vector<vector<long long>> splitPainting(vector<vector<int>>& seg) {\n int p=1e5+2;\n vector<long long> sum(p,0);\n vector<bool> change(p,false);\n for(auto &i:seg)\n {\n sum[i[0]]+=i[2];\n sum[i[1]]-=i[2];\n change[i[0]]=change[i[1]]=true;\n }\n long long last=0;\n long long s=0;\n vector<vector<long long>> ans;\n for(int i=1;i<sum.size();i++)\n {\n if(s!=0 && change[i])\n {\n ans.push_back({last,i,s});\n }\n if(change[i])\n {\n last=i;\n s+=sum[i];\n }\n }\n return ans;\n }\n``` | 1 | 0 | [] | 0 |
describe-the-painting | 22 ms faster than 93.60% of Java solution | 22-ms-faster-than-9360-of-java-solution-oon9r | Based on:\nhttps://leetcode.com/problems/describe-the-painting/discuss/1359720/Line-Sweep\n\nNo overlapping is easy. After sorting ranges by start then end poin | anquan | NORMAL | 2021-09-16T19:40:37.356969+00:00 | 2021-09-16T19:40:37.357015+00:00 | 149 | false | Based on:\nhttps://leetcode.com/problems/describe-the-painting/discuss/1359720/Line-Sweep\n\nNo overlapping is easy. After sorting ranges by start then end point, there are five types of overlappings between the two closed ranges (see diagram below). The solution can be verified on them \n\nCode:\n```\nclass Solution {\n public List<List<Long>> splitPainting(int[][] segments) {\n List<List<Long>> result = new ArrayList<>();\n int n = 1;\n \n for (var s: segments) {\n n = Math.max(n, s[1]); //performance tunning, reduce max end index value\n }\n n += 1;\n \n long[] line = new long[n];\n boolean[] endpoint = new boolean[n];\n \n for (var s: segments) {\n int start = s[0], end = s[1], color = s[2];\n line[start] += color;\n line[end] -= color;\n endpoint[start] = endpoint[end] = true;\n }\n \n long mixedColor = 0;\n for (int end = 1, start = 1; end < n; end++) {\n if (endpoint[end] == true) {\n if (mixedColor > 0) {\n result.add(Arrays.asList((long)start, (long)end, mixedColor));\n }\n start = end;\n }\n\t\t\t\n mixedColor += line[end];\n }\n \n return result;\n }\n}\n```\n | 1 | 0 | [] | 0 |
describe-the-painting | [C++] sort intervals | c-sort-intervals-by-yunqu-q16m | I hate the test case where the unpainted segment has to be excluded. Otherwise it is cleaner. To handle that unpainted segment, we will have to use if (mix) ans | yunqu | NORMAL | 2021-08-15T02:05:48.323729+00:00 | 2021-08-15T02:05:48.323761+00:00 | 228 | false | I hate the test case where the unpainted segment has to be excluded. Otherwise it is cleaner. To handle that unpainted segment, we will have to use `if (mix) ans.push_back({j, inter[i][0], mix});` in the following program.\n\n```cpp\nclass Solution {\npublic:\n vector<vector<long long>> splitPainting(vector<vector<int>>& segments) {\n vector<vector<long long>> ans;\n vector<vector<long long>> inter;\n for (auto s: segments){\n inter.push_back({s[0], s[2]});\n inter.push_back({s[1], -s[2]});\n }\n sort(inter.begin(), inter.end());\n long long mix = 0;\n long long j = inter[0][0];\n for (int i = 0; i < inter.size(); ++i){\n if (inter[i][0] != j){\n if (mix) ans.push_back({j, inter[i][0], mix});\n j = inter[i][0];\n }\n mix += inter[i][1];\n }\n return ans;\n }\n};\n``` | 1 | 1 | [] | 0 |
describe-the-painting | C++ Easy Solution O(n) Prefix sum | c-easy-solution-on-prefix-sum-by-vibhu17-pn18 | \nclass Solution {\npublic:\n vector<vector<long long>> splitPainting(vector<vector<int>>& segments) {\n int maxi=INT_MIN;\n for(int i=0;i<segm | vibhu172000 | NORMAL | 2021-07-30T12:20:53.457684+00:00 | 2021-07-30T12:20:53.457724+00:00 | 150 | false | ```\nclass Solution {\npublic:\n vector<vector<long long>> splitPainting(vector<vector<int>>& segments) {\n int maxi=INT_MIN;\n for(int i=0;i<segments.size();i++)\n {\n maxi=max(maxi,segments[i][1]);\n }\n vector<long long>v(maxi+1,0);\n vector<bool>check(maxi+1,0);\n for(int i=0;i<segments.size();i++)\n {\n v[segments[i][0]]+=segments[i][2];\n v[segments[i][1]]-=segments[i][2];\n check[segments[i][0]]=true;\n check[segments[i][1]]=true;\n }\n vector<vector<long long>>ans;\n vector<long long>s;\n for(int i=1;i<v.size();i++)\n {\n v[i]+=v[i-1];\n }\n for(int i=1;i<v.size();i++)\n {\n if(v[i]!=0 && s.size()==0)\n {\n s.push_back(i);\n }\n else if(v[i]!=v[i-1] && s.size()!=0 || (check[i]==true))\n {\n s.push_back(i);\n s.push_back(v[i-1]);\n ans.push_back(s);\n s.clear();\n if(v[i]!=0 || (check[i]==true && v[i]==v[i-1]))\n {\n s.push_back(i);\n }\n }\n }\n return ans;\n }\n};\n``` | 1 | 0 | [] | 0 |
describe-the-painting | Golang linear solution | golang-linear-solution-by-tjucoder-n05w | go\nfunc splitPainting(segments [][]int) [][]int64 {\n // math.MaxInt64 is large enough for sentinel\n\tline := make([]int, 100001)\n\tfor i := range line {\ | tjucoder | NORMAL | 2021-07-28T16:32:50.169847+00:00 | 2021-07-28T16:32:50.169903+00:00 | 82 | false | ```go\nfunc splitPainting(segments [][]int) [][]int64 {\n // math.MaxInt64 is large enough for sentinel\n\tline := make([]int, 100001)\n\tfor i := range line {\n\t\tline[i] = math.MaxInt64\n\t}\n\tfor _, v := range segments {\n\t\tif line[v[0]] == math.MaxInt64 {\n\t\t\tline[v[0]] = 0\n\t\t}\n\t\tif line[v[1]] == math.MaxInt64 {\n\t\t\tline[v[1]] = 0\n\t\t}\n\t\tline[v[0]] += v[2]\n\t\tline[v[1]] -= v[2]\n\t}\n\tpainting := make([][]int64, 0)\n\tprefix := 0\n\tcolor := 0\n // Notice: from 1 to 100000, inclusive\n\tfor i := 1; i <= 100000; i++ {\n\t\tif line[i] == math.MaxInt64 {\n // skip invalid index\n\t\t\tcontinue\n\t\t}\n\t\tif color != 0 {\n\t\t\tpainting = append(painting, []int64{int64(prefix), int64(i), int64(color)})\n\t\t}\n\t\tcolor += line[i]\n\t\tprefix = i\n\t}\n\treturn painting\n}\n``` | 1 | 0 | ['Go'] | 0 |
describe-the-painting | C++ Easy and Clean O(n) using prefix array | c-easy-and-clean-on-using-prefix-array-b-yq3v | \nclass Solution {\npublic:\n vector<vector<long long>> splitPainting(vector<vector<int>>& segments) {\n vector<long long> a(100002, 0);\n vect | allw | NORMAL | 2021-07-24T21:48:37.696046+00:00 | 2021-07-24T21:50:05.776799+00:00 | 95 | false | ```\nclass Solution {\npublic:\n vector<vector<long long>> splitPainting(vector<vector<int>>& segments) {\n vector<long long> a(100002, 0);\n vector<bool> f(100002, false);\n for (int i = 0; i < segments.size(); i++) {\n a[segments[i][0]] += segments[i][2];\n a[segments[i][1]] -= segments[i][2];\n f[segments[i][0]] = true;\n f[segments[i][1]] = true;\n }\n \n vector<vector<long long>> result;\n int l = 0;\n for (int i = 1; i < a.size(); i++) {\n if (f[i]) {\n if (a[i-1] > 0) result.push_back({l, i, a[i-1]});\n l = i;\n }\n a[i] += a[i-1];\n }\n \n return result;\n }\n};\n``` | 1 | 0 | [] | 2 |
describe-the-painting | JAVA | 100% faster | 100% less space | Easy | Fastest among all | java-100-faster-100-less-space-easy-fast-bgc9 | class Solution {\n\n public List> splitPainting(int[][] segments) {\n HashMap start = new HashMap<>();\n HashMap end = new HashMap<>();\n | rahul516 | NORMAL | 2021-07-24T19:38:31.085852+00:00 | 2021-07-24T19:49:42.849225+00:00 | 199 | false | class Solution {\n\n public List<List<Long>> splitPainting(int[][] segments) {\n HashMap<Long, Long> start = new HashMap<>();\n HashMap<Long, Long> end = new HashMap<>();\n int n = segments.length;\n for(int i = 0; i < n; i++){\n int[] arr = segments[i];\n Long srt = (long) arr[0];\n Long ed = (long) arr[1];\n Long val = (long) arr[2];\n \n if(start.containsKey(srt)){\n start.put(srt, start.get(srt) + val);\n }else{\n start.put(srt, val);\n }\n \n if(end.containsKey(ed)){\n end.put(ed, end.get(ed) + val);\n }else{\n end.put(ed, val);\n }\n }\n \n PriorityQueue<Long> queue1 = new PriorityQueue<>();\n PriorityQueue<Long> queue2 = new PriorityQueue<>();\n \n for(long key : start.keySet()){\n queue1.add(key);\n }\n \n for(long key : end.keySet()){\n queue2.add(key);\n }\n \n List<List<Long>> answer = new ArrayList<>();\n \n long startTime = queue1.poll();\n long valCount = (long) start.get(startTime);\n \n while(!queue1.isEmpty() && !queue2.isEmpty()){\n if(queue2.peek() <= queue1.peek()){\n List<Long> subAns = new ArrayList<>();\n subAns.add(startTime);\n subAns.add(queue2.peek());\n subAns.add(valCount);\n if(valCount != 0){\n answer.add(subAns); \n }\n startTime = queue2.peek();\n valCount -= end.get(queue2.poll());\n }else{\n if(queue1.peek() == startTime){\n valCount += start.get(queue1.poll());\n continue;\n }\n List<Long> subAns = new ArrayList<>();\n subAns.add(startTime);\n subAns.add(queue1.peek());\n subAns.add(valCount);\n if(valCount != 0){\n answer.add(subAns); \n }\n startTime = queue1.peek();\n valCount += start.get(queue1.poll());\n }\n }\n \n \n while(!queue2.isEmpty()){\n List<Long> subAns = new ArrayList<>();\n subAns.add(startTime);\n subAns.add(queue2.peek());\n subAns.add(valCount);\n if(valCount != 0){\n answer.add(subAns); \n }\n startTime = queue2.peek();\n valCount -= end.get(queue2.poll());\n }\n \n return answer;\n \n }\n} | 1 | 0 | ['Heap (Priority Queue)', 'Java'] | 0 |
describe-the-painting | [Python] Sweeping - with detailed explanation | python-sweeping-with-detailed-explanatio-lwt3 | This is a problem giving simple example of Sweeping algorithm in Computational Geometry (https://en.wikipedia.org/wiki/Sweep_line_algorithm). The problem\'s in | durvorezbariq | NORMAL | 2021-07-24T16:39:11.829024+00:00 | 2021-07-24T16:40:28.095054+00:00 | 116 | false | This is a problem giving simple example of Sweeping algorithm in Computational Geometry (https://en.wikipedia.org/wiki/Sweep_line_algorithm). The problem\'s input is given in the form of intervals and one could easily fall in the trap of trying to "merge" intervals and trying to obtain disjoint parts while maintaining color. A better approach is to imagine a timeline with "*events of color changes*". Each segment [`start`,`end`,`color`] gives two events: At time `start` we increase `curr_color` by `color` and at time `end` we decrease the `curr_color` by `color`. In the code below *"the events of color changes*" are considered as `points`. We sort these events in increasing time order and consider them one by one.\nComplexity: O(nlgn)\n```\nclass Solution:\n def splitPainting(self, segments: List[List[int]]) -> List[List[int]]:\n points=[]\n\t\t# transform input\n for start,end,color in segments:\n points.append([start,color])\n points.append([end,-color])\n\t\t\t\n res=[]\n points.sort(key=lambda x: x[0])\n curr_start=points[0][0]\n curr_color=points[0][1]\n for time,color in points[1:]:\n\t\t\t# we add new interval to res only if the time of the incoming point is greater than the current time\n\t\t\t# e.g. point1= [1,3], point2=[2,4]\n\t\t\t# otherwise if time ==curr_start we do not add anything\n if time>curr_start and curr_color:\n res.append([curr_start,time,curr_color])\n curr_start=time\n curr_color+=color\n\t\t\t# e.g. point1=[1,7] point2=[1,6]\n else:\n curr_color+=color\n curr_start=time\n return res\n``` | 1 | 0 | [] | 0 |
describe-the-painting | Sweep Line | Coordinate Compression | sweep-line-coordinate-compression-by-asd-70gg | Code | asd_44 | NORMAL | 2025-04-08T06:22:59.087075+00:00 | 2025-04-08T06:22:59.087075+00:00 | 3 | false |
# Code
```cpp []
class Solution {
public:
vector<vector<long long>> splitPainting(vector<vector<int>>& segments) {
// return sweep_line(segments);
return sweep_line_coordiante_compression(segments);
}
vector<vector<long long>> sweep_line(vector<vector<int>>& segments) {
map<int, long long> diff;
// 1. Build the diff map
for (auto& seg : segments) {
int start = seg[0], end = seg[1], color = seg[2];
diff[start] += color;
diff[end] -= color;
}
vector<vector<long long>> res;
long long curr_color = 0;
int prev = -1;
// 2. Sweep through the sorted map
for (auto& [pos, change] : diff) {
if (curr_color > 0 && prev != -1) {
res.push_back({(long long)prev, (long long)pos, curr_color});
}
curr_color += change;
prev = pos;
}
return res;
}
vector<vector<long long>> sweep_line_coordiante_compression(vector<vector<int>>& segments) {
set<int> coords;
// Step 1: Collect all unique coordinates
for (auto& seg : segments) {
coords.insert(seg[0]);
coords.insert(seg[1]);
}
// Step 2: Coordinate compression
vector<int> indexToCoord(coords.begin(), coords.end());
unordered_map<int, int> coordToIndex;
for (int i = 0; i < indexToCoord.size(); ++i) {
coordToIndex[indexToCoord[i]] = i;
}
int N = indexToCoord.size();
vector<long long> diff(N + 1, 0);
// Step 3: Fill difference array
for (auto& seg : segments) {
int l = coordToIndex[seg[0]];
int r = coordToIndex[seg[1]];
int color = seg[2];
diff[l] += color;
diff[r] -= color;
}
// Step 4: Build result with prefix sum
vector<vector<long long>> res;
long long curr = 0;
for (int i = 0; i < N - 1; ++i) {
curr += diff[i];
if (curr > 0) {
res.push_back({(long long)indexToCoord[i], (long long)indexToCoord[i+1], curr});
}
}
return res;
}
};
``` | 0 | 0 | ['C++'] | 0 |
describe-the-painting | messy but working solution | messy-but-working-solution-by-owenwu4-7mva | Intuitionuse line sweep algo and try to follow the picture exactlyApproachComplexity
Time complexity:
Space complexity:
Code | owenwu4 | NORMAL | 2025-03-16T22:18:43.708458+00:00 | 2025-03-16T22:18:43.708458+00:00 | 4 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
use line sweep algo and try to follow the picture exactly
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python3 []
class Solution:
def splitPainting(self, segments: List[List[int]]) -> List[List[int]]:
d = defaultdict(int)
sl = set()
ms, me = float('inf'), float('-inf')
for s in segments:
start, end, val = s[0], s[1], s[2]
sl.add(start)
sl.add(end)
d[start] += val
if start <= ms:
ms = start
d[end] -= val
if end >= me:
me = end
sl = sorted(list(sl))
print(sl, "sl")
a = list(range(0, me + 1))
big = a[-1]
p = [0] * len(a)
for s in segments:
start, end, val = s[0], s[1], s[2]
if 0 <= start <= big:
p[start] += val
if 0 <= end <= big:
p[end] -= val
k = list(itertools.accumulate(p))
ms = float('inf')
me = float('-inf')
res = []
for i in range(1, len(sl)):
start, end = sl[i - 1], sl[i]
ms = min(ms, start)
me = max(me, end)
print(k[start: end], "now")
now = sum(k[start: end]) // (end - start)
if now > 0:
cur = [start, end, now]
print(cur)
res.append(cur)
return res
``` | 0 | 0 | ['Python3'] | 0 |
describe-the-painting | Easy Python Solution | easy-python-solution-by-vidhyarthisunav-jtdc | Code | vidhyarthisunav | NORMAL | 2025-02-05T18:10:54.341608+00:00 | 2025-02-05T18:10:54.341608+00:00 | 7 | false | # Code
```python3 []
class Solution:
def splitPainting(self, segments: List[List[int]]) -> List[List[int]]:
events = defaultdict(int)
for start, end, color in segments:
events[start] += color
events[end] -= color
sorted_events = sorted(events.keys())
res, prev, curr_color = [], None, 0
for point in sorted_events:
if prev is not None and curr_color > 0:
res.append([prev, point, curr_color])
curr_color += events[point]
prev = point
return res
``` | 0 | 0 | ['Python3'] | 0 |
describe-the-painting | 87% Beat || Line-Sweep-Approach || Easy-to-Understand | 87-beat-line-sweep-approach-easy-to-unde-gkne | IntuitionApproach
Firt Find max end-point to store value in vector form.
Apply Prefix-Sum at start index update by + and at end index update by - .
And Track th | PRAVEEN_RAUTELA | NORMAL | 2025-01-29T19:44:12.273787+00:00 | 2025-01-29T19:44:12.273787+00:00 | 27 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
1. Firt Find max end-point to store value in vector form.
2. Apply Prefix-Sum at start index update by + and at end index update by - .
3. And Track the breaking point at all start and end index .
4. Traverse through array if at any point curr_sum = 0 then update prev_breaking_point = i+1 , Else if next is breaking point then push the ans and update prev_breaking point.
# Complexity
- Time complexity : O(N)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity : O(N)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
// Line-Sweep Algo
// Just do 1-thing when the interval is starting add the paint and update -paint at (end) index
// And where ever we encounter start and end just mark it has breaking point
typedef long long int ll;
class Solution {
public:
vector<vector<long long>> splitPainting(vector<vector<int>>& segments) {
int start = INT_MAX;
int end = INT_MIN;
for(auto seg : segments){
start = min(start,seg[0]);
end = max(end,seg[1]);
}
vector<ll> line_sweep(end+2,0);
vector<bool> breaking(end+2,false);
for(auto seg : segments){
line_sweep[seg[0]] += (ll)seg[2];
line_sweep[seg[1]] += (ll)(-1*seg[2]);
breaking[seg[0]] = true;
breaking[seg[1]] = true;
}
vector<vector<ll>> ans;
ll curr_sum = 0;
ll prev = -1;
for(int i=start;i<end+1;i++){
if(prev == -1) prev = i;
curr_sum += line_sweep[i];
if(curr_sum != 0){
if(breaking[i+1]) ans.push_back({prev,i+1,curr_sum}) ,prev = i+1;
}
else prev = i+1;
}
return ans;
}
};
``` | 0 | 0 | ['Line Sweep', 'Prefix Sum', 'C++'] | 0 |
describe-the-painting | C++ | c-by-giri_69-jhjh | Intuition
at beginning of interval, add the color value and at end of interval, substract the color value
Note : The reason for checking count>0 is that there m | giri_69 | NORMAL | 2025-01-17T16:54:00.337229+00:00 | 2025-01-17T16:54:00.337229+00:00 | 8 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
1) at beginning of interval, add the color value and at end of interval, substract the color value
Note : The reason for checking `count>0` is that there may be gap b/w intervals like $$[[1,2,3],[5,7,7]]$$, Here if we don't check for the condition, the code will push $$[3,5,0]$$ to our answer which is unneccessary
# Complexity
- Time complexity:O(N)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:O(N)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
vector<vector<long long>> splitPainting(vector<vector<int>>& segments) {
map <long long,long long> hash;
for(auto i : segments){
hash[i[0]]+=i[2];
hash[i[1]]-=i[2];
}
vector <vector<long long>> ans;
long long count=0;
long long prev=-1;
for(auto &[curr,change] : hash){
if(prev!=-1 && count>0)ans.push_back({prev,curr,count});
count+=change;
prev=curr;
}
return ans;
}
};
``` | 0 | 0 | ['C++'] | 0 |
describe-the-painting | Aggregate and sweep | aggregate-and-sweep-by-theabbie-uoq2 | \nclass Solution:\n def splitPainting(self, segments: List[List[int]]) -> List[List[int]]:\n vals = {}\n for l, r, c in segments:\n | theabbie | NORMAL | 2024-12-23T12:16:30.418867+00:00 | 2024-12-23T12:16:30.418906+00:00 | 3 | false | ```\nclass Solution:\n def splitPainting(self, segments: List[List[int]]) -> List[List[int]]:\n vals = {}\n for l, r, c in segments:\n vals[l] = vals.get(l, 0) + c\n vals[r] = vals.get(r, 0) - c\n vals = sorted(vals.items())\n res = []\n p = 0\n for i in range(len(vals) - 1):\n p += vals[i][1]\n if p:\n res.append((vals[i][0], vals[i + 1][0], p))\n return res\n``` | 0 | 0 | ['Python'] | 0 |
describe-the-painting | Line Sweep | Python | line-sweep-python-by-wxy0925-8w7e | \n"""\nLine Sweep\n"""\nclass Solution:\n def splitPainting_v1(self, segments: List[List[int]]) -> List[List[int]]:\n n = len(segments)\n \n | wxy0925 | NORMAL | 2024-12-14T03:20:57.635957+00:00 | 2024-12-14T03:20:57.636003+00:00 | 1 | false | ```\n"""\nLine Sweep\n"""\nclass Solution:\n def splitPainting_v1(self, segments: List[List[int]]) -> List[List[int]]:\n n = len(segments)\n \n d = collections.defaultdict(int)\n for a, b, delta in segments:\n d[a] += delta\n d[b] -= delta\n \n info = sorted([[k, v] for k, v in d.items()])\n \n print(info)\n \n res = []\n h = 0\n for i in range(len(info) - 1):\n (s, dh), e = info[i], info[i+1][0]\n h = h + dh\n if h > 0:\n res.append([s, e, h])\n return res\n \n \n \n def splitPainting(self, segments: List[List[int]]) -> List[List[int]]:\n n = len(segments)\n \n d = collections.defaultdict(int)\n for a, b, delta in segments:\n d[a] += delta\n d[b] -= delta\n \n info = sorted([[k, v] for k, v in d.items()])\n \n pos = [item[0] for item in info]\n dh = [item[1] for item in info]\n \n for i in range(1, len(dh)):\n dh[i] += dh[i-1]\n\n res = []\n for i in range(1, len(pos)):\n if dh[i-1] > 0:\n res.append([pos[i-1], pos[i], dh[i-1]])\n return res\n``` | 0 | 0 | [] | 0 |
describe-the-painting | Easy Line Sweep | C++ | easy-line-sweep-c-by-marknaman05-5si6 | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | marknaman05 | NORMAL | 2024-12-26T22:51:17.336030+00:00 | 2024-12-26T22:51:17.336030+00:00 | 15 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
vector<vector<long long>> splitPainting(vector<vector<int>>& segments) {
map<long long,long long> mp;
for(auto it : segments){
mp[it[0]]+=it[2];
mp[it[1]]-=it[2];
}
long long cnt = 0;
long long st = 0;
long long end = 0;
vector<vector<long long>> res;
long long temp = 0;
for(auto it : mp){
st = end;
end = it.first;
if(st>0 && cnt>0){
res.push_back({st,end,cnt});
}
cnt += it.second;
}
return res;
}
};
``` | 0 | 0 | ['C++'] | 0 |
describe-the-painting | [Java] ✅ 36MS ✅ 80% ✅ LINE SWEEP ✅ FAST ✅ CLEAN CODE | java-36ms-80-line-sweep-fast-clean-code-re1h2 | Approach
Use a long[][2] colorLine matrix to mark the indices of where segments open and close
colorLine[i][0] to add the openings (+color)
colorLine[i + 1][1] | StefanelStan | NORMAL | 2024-12-20T00:53:06.085196+00:00 | 2024-12-20T00:53:06.085196+00:00 | 38 | false | # Approach
1. Use a long[][2] colorLine matrix to mark the indices of where segments open and close
- colorLine[i][0] to add the openings (+color)
- colorLine[i + 1][1] to add the closings (-color)
2. Traverse segments and mark the start/end of each color segment (colorLine[start][0] , colorLine[end + 1][1])
3. Traverse colorLine with 2 pointers (left, right) that will mark the current window color
4. At each step, check if current segment ends (line[i+1][1] != 0) or if a new segment starts.
- add to list of answers the segment
# Complexity
- Time complexity:$$O(n)$$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:$$O(max)$$ (max - max value of ending segment)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public List<List<Long>> splitPainting(int[][] segments) {
long[][] colorLine = getColorLine(segments);
List<List<Long>> description = new ArrayList<>();
long lineSum = 0L;
for (int left = 0, right = 0; right < colorLine.length - 1; right++) {
if (colorLine[right + 1][1] != 0) {
description.add(List.of((long)left, (long)right, lineSum));
lineSum += colorLine[right + 1][1];
left = right;
}
if (colorLine[right][0] > 0) {
if(lineSum == 0) { // don't add any segment
left = right;
lineSum += colorLine[right][0];
} else {
if (left != right) {
description.add(List.of((long)left, (long)right, lineSum));
}
lineSum += colorLine[right][0];
left = right;
}
}
}
return description;
}
private long[][] getColorLine(int[][] segments) {
int maxLength = 0;
for (int[] segment : segments) {
maxLength = Math.max(maxLength, segment[1]);
}
long[][] colorLine = new long[maxLength + 2][2];
for (int[] segment : segments) {
colorLine[segment[0]][0] += segment[2];
colorLine[segment[1] + 1][1] -= segment[2];
}
return colorLine;
}
}
``` | 0 | 0 | ['Java'] | 0 |
describe-the-painting | Simple Boundary Addition technique | simple-boundary-addition-technique-by-ta-l39p | 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 | tanishqj2005 | NORMAL | 2024-12-08T18:25:58.582613+00:00 | 2024-12-08T18:25:58.582647+00:00 | 9 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<vector<long long>> splitPainting(vector<vector<int>>& segments) {\n vector<vector<int>> fs;\n for (vector<int>& x : segments) {\n fs.push_back({x[0], x[2]});\n fs.push_back({x[1], -x[2]});\n }\n sort(fs.begin(), fs.end());\n long long sum = 0;\n vector<vector<long long>> ans;\n int ps = -1;\n for (vector<int>& x : fs) {\n // mixing the color\n if (x[0] == ps || ps == -1) {\n sum += x[1];\n ps = x[0];\n } else {\n // new color portion\n if (sum > 0) {\n ans.push_back({ps, x[0], sum});\n }\n sum += x[1];\n ps = x[0];\n }\n }\n\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
describe-the-painting | Using Line Sweep Algorithm | using-line-sweep-algorithm-by-sasukexnar-6gfv | Code\ncpp []\n#define ll long long\nclass Solution {\npublic:\n vector<vector<ll>> splitPainting(vector<vector<int>>& segments) {\n map<ll, ll> mp;\n | sasukexnaruto | NORMAL | 2024-11-23T21:03:29.978591+00:00 | 2024-11-23T21:03:29.978631+00:00 | 28 | false | # Code\n```cpp []\n#define ll long long\nclass Solution {\npublic:\n vector<vector<ll>> splitPainting(vector<vector<int>>& segments) {\n map<ll, ll> mp;\n for(auto it: segments) {\n mp[it[0]] += it[2];\n mp[it[1]] -= it[2];\n }\n vector<vector<ll>> ans;\n int first_iter = true;\n ll prev_l = 0;\n ll prev_val = 0;\n for(auto it: mp) {\n if(first_iter) {\n prev_l = it.first;\n prev_val = it.second;\n first_iter = false;\n } else {\n if(prev_val != 0)\n ans.push_back({prev_l, it.first, prev_val});\n prev_val += it.second;\n prev_l = it.first;\n }\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['Line Sweep', 'C++'] | 0 |
describe-the-painting | JS | Line Sweep | js-line-sweep-by-srini39-7psc | Code\njavascript []\n/**\n * @param {number[][]} segments\n * @return {number[][]}\n */\nvar splitPainting = function(segments) {\n const mix = new Array(100 | srini39 | NORMAL | 2024-10-22T17:56:28.570426+00:00 | 2024-10-22T17:56:28.570460+00:00 | 9 | false | # Code\n```javascript []\n/**\n * @param {number[][]} segments\n * @return {number[][]}\n */\nvar splitPainting = function(segments) {\n const mix = new Array(100002).fill(0);\n let sum = 0, last_i = 0;\n const ends = new Array(100002).fill(false);\n const res = [];\n\n for(let [start, end, paint] of segments) {\n mix[start] += paint;\n mix[end] -= paint;\n ends[start] = ends[end] = true;\n }\n\n for(let i=1; i<100002; i++) {\n if(ends[i] && sum > 0) {\n res.push([last_i, i, sum]);\n }\n last_i = ends[i] ? i : last_i;\n sum += mix[i];\n }\n\n return res;\n};\n``` | 0 | 0 | ['JavaScript'] | 0 |
describe-the-painting | Line Sweep Algorithm | C++ | Map | line-sweep-algorithm-c-map-by-anoshor-vcnv | Just Line Sweep...\n\n# Code\ncpp []\nclass Solution {\npublic:\n vector<vector<long long>> splitPainting(vector<vector<int>>& segments) {\n ios_base: | Anoshor | NORMAL | 2024-10-15T23:41:13.326829+00:00 | 2024-10-15T23:41:13.326861+00:00 | 24 | false | Just Line Sweep...\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<vector<long long>> splitPainting(vector<vector<int>>& segments) {\n ios_base::sync_with_stdio(false);\n cin.tie(NULL);\n\n //code\n vector<vector<long long>> res;\n map<int, long long> mp; //using map for automatic sorting -- can use vector instead\n //LINE SWEEP ALGORITHM\n for(auto& it : segments) {\n mp[it[0]] += it[2]; \n mp[it[1]] -= it[2]; \n }\n\n long long count = 0;\n int start = -1;\n for (auto it = mp.begin(); it != mp.end(); ++it) {\n int end = it->first; \n long long val = it->second; \n\n if (start != -1 && count > 0) {\n res.push_back({start, end, count});\n }\n \n count += val;\n start = end;\n }\n\n return res;\n }\n};\n\n``` | 0 | 0 | ['Ordered Map', 'Line Sweep', 'C++'] | 0 |
describe-the-painting | weird python solution ngl but it works 🤷♂️ | weird-python-solution-ngl-but-it-works-b-qlgn | Code\npython3 []\nclass Solution:\n def splitPainting(self, segments: List[List[int]]) -> List[List[int]]:\n left_side, right_side = min(x[0] for x in | HickoryMans_AND_LesterMan | NORMAL | 2024-10-08T02:03:57.120730+00:00 | 2024-10-08T02:03:57.120758+00:00 | 6 | false | # Code\n```python3 []\nclass Solution:\n def splitPainting(self, segments: List[List[int]]) -> List[List[int]]:\n left_side, right_side = min(x[0] for x in segments), max(x[1] for x in segments)\n arr = [0] * (right_side - left_side + 1)\n changed = [False] * (right_side - left_side + 1)\n for segment in segments:\n arr[segment[0] - left_side] += segment[2]\n arr[segment[1] - left_side] -= segment[2]\n changed[segment[0] - left_side] = True\n changed[segment[1] - left_side] = True\n res = []\n idx = 0\n curr = 0\n while idx < len(arr):\n curr += arr[idx]\n if curr != 0:\n start = idx\n idx += 1\n while idx < len(arr) and arr[idx] == 0 and not changed[idx]:\n idx += 1\n res.append([start + left_side, idx + left_side, curr])\n else:\n idx += 1\n return res\n \n``` | 0 | 0 | ['Python3'] | 0 |
describe-the-painting | ✅ Java || TreeMap + Line Sweep | java-treemap-line-sweep-by-shrek02-bqov | Code\njava []\nclass Solution {\n public List<List<Long>> splitPainting(int[][] segments) {\n int n = segments.length;\n List<List<Long>> res = | shrek02 | NORMAL | 2024-10-05T21:47:04.074329+00:00 | 2024-10-05T21:47:04.074356+00:00 | 13 | false | # Code\n```java []\nclass Solution {\n public List<List<Long>> splitPainting(int[][] segments) {\n int n = segments.length;\n List<List<Long>> res = new ArrayList<>();\n\n Map<Integer, Long> tm = new TreeMap<>();\n\n for(int[] seg: segments){\n int st = seg[0];\n int ed = seg[1];\n int color = seg[2];\n\n tm.put(st, tm.getOrDefault(st, 0L) + color);\n tm.put(ed, tm.getOrDefault(ed, 0L) - color);\n }\n\n long color = 0;\n long begin = -1;\n for(Map.Entry<Integer, Long> e: tm.entrySet()){\n long curr = e.getKey();\n if(color != 0){\n List<Long> temp = new ArrayList<>();\n temp.add(begin);\n temp.add(curr);\n temp.add(color);\n res.add(temp);\n }\n begin = curr;\n color += e.getValue();\n }\n\n return res;\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
describe-the-painting | Line Sweep method (explanation + code comments) | line-sweep-method-explanation-code-comme-qjes | Approach\n1. We can store the total color value at each index (in chronological order) where there is a change in color (i.e., when a paint is added or removed) | vikktour | NORMAL | 2024-09-27T19:00:00.868533+00:00 | 2024-09-27T22:22:50.124613+00:00 | 85 | false | # Approach\n1. We can store the total color value at each index (in chronological order) where there is a change in color (i.e., when a paint is added or removed)\n2. Since our answer should be in the form of each intervals (looking at the start of each interval is more intuitive), we can iterate through each start index and get the total color value for that interval by adding the previous colorValue with the starting color value.\n\nWhy does this work?\nLet\'s look at example 1: \n[[1,4,5],[4,7,7],[1,7,9]]\n\nAfter building the colorDict, we have this:\ncolorDict: SortedDict({1: 14, 4: 2, 7: -16})\n\nIf you look at their provided diagram, the colorValue of index=4 should be 7+9=16, but we only have 2.\nThis is because our dictionary only accounted for the -5 (for 5 leaving) and +7 (for the 7 joining) at index=4.\n\nWe don\'t exactly want the first segment to be a net -5, we want it to be 0 at index=4, so to do that, we add it back in. We also want the third segment [1,7,9] to be included in index=4, so we also need to add it in. We can do so by doing colorValue = colorValue + colorDict[start].\n\n# Complexity\nLet N = len(segments)\n- Time complexity: O(N Log N)\nN: For loop iterates through the segments.\nLogN: For getting the value from a sorted dict, when given a key.\nThus, NLogN is the time complexity for each for loop block.\n\n- Space complexity: O(N)\ncolorDict stores the start, end, and color value of all segments\n\n# Code\n```python3 []\nfrom sortedcontainers import SortedDict\nclass Solution:\n def splitPainting(self, segments: List[List[int]]) -> List[List[int]]:\n \n # Build the sorted color dictionary.\n # colorDict[(start,end)] = color_sum\n colorDict = SortedDict()\n for (start, end, colorValue) in segments:\n colorDict[start] = colorDict.get(start,0) + colorValue\n colorDict[end] = colorDict.get(end,0) - colorValue\n\n # Iterate through the color dictioanry (this is already in chronological order), and get the value at each\n # point of change\n indices = colorDict.keys()\n numIntervals = len(indices) - 1\n ans = []\n colorValue = 0 # The colorValue will build on from what is is previously\n for idx in range(numIntervals):\n start = indices[idx]\n end = indices[idx+1]\n colorValue = colorValue + colorDict[start]\n if colorValue > 0:\n # Check for > 0, since we exclude parts that are not painted (i.e., exclude indices where colorValue = 0)\n ans.append([start, end, colorValue])\n \n return ans\n\n"""\nEdge case where there is a colorValue = 0:\n[[4,16,12],[9,10,15],[18,19,13],[3,13,20],[12,16,3],[2,10,10],[3,11,4],[13,16,6]]\n"""\n``` | 0 | 0 | ['Line Sweep', 'Python3'] | 1 |
describe-the-painting | Line Sweep | line-sweep-by-prashant047-hjeu | Approach\nLine Sweep\n\n# Complexity\n- Time complexity:\nO(nlogn)\n\n- Space complexity:\nO(n)\n\n# Code\npython3 []\nclass Solution:\n def splitPainting(se | prashant047 | NORMAL | 2024-09-15T13:10:45.436422+00:00 | 2024-09-15T13:10:45.436444+00:00 | 6 | false | # Approach\nLine Sweep\n\n# Complexity\n- Time complexity:\nO(nlogn)\n\n- Space complexity:\nO(n)\n\n# Code\n```python3 []\nclass Solution:\n def splitPainting(self, segments: List[List[int]]) -> List[List[int]]:\n line = {}\n for start, end, color in segments:\n if start not in line:\n line[start] = 0\n if end not in line:\n line[end] = 0\n line[start] += color\n line[end] -= color\n \n ans = []\n color = 0\n start = None\n\n points = list(line.keys())\n points.sort()\n\n for key in points:\n if color == 0:\n start = key\n else:\n ans.append([start, key, color])\n start = key\n color += line[key]\n return ans\n\n``` | 0 | 0 | ['Python3'] | 0 |
describe-the-painting | Sweep line O(nlogn) | sweep-line-onlogn-by-senninsagar-5yjw | Code\ncpp []\nclass Solution {\n struct segment{\n int start;\n bool end;\n int val;\n\n bool operator<(const segment& other){\n | SenninSagar | NORMAL | 2024-09-02T22:57:57.192821+00:00 | 2024-09-02T22:57:57.192849+00:00 | 15 | false | # Code\n```cpp []\nclass Solution {\n struct segment{\n int start;\n bool end;\n int val;\n\n bool operator<(const segment& other){\n return start < other.start; \n }\n };\n\npublic:\n vector<vector<long long>> splitPainting(vector<vector<int>>& segments) {\n\n vector<segment> arr;\n\n for(auto& v: segments){\n segment s1{v[0], false, v[2]};\n segment s2{v[1], true, v[2]};\n\n arr.push_back(s1);\n arr.push_back(s2);\n }\n\n sort(arr.begin(), arr.end());\n\n vector<vector<long long>> ans;\n\n long long sum = 0, prev;\n\n bool has_open = false;\n\n auto it = arr.begin();\n\n while(it != arr.end()){\n int curr = it->start;\n\n if(has_open){\n //def changing something\n ans.push_back({prev, curr, sum});\n }\n\n while(it != arr.end() && it->start == curr){\n if(it->end){\n sum -= it->val;\n }\n else{\n sum += it->val;\n }\n\n it++;\n }\n\n if(sum > 0 && !has_open){\n has_open = true;\n }\n else if(sum == 0){\n has_open = false;\n }\n\n prev = curr;\n }\n\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
describe-the-painting | Sorting + prefix sum. | sorting-prefix-sum-by-alexpg-mrqg | \n# Code\ncpp []\nclass Solution {\npublic:\n vector<vector<long long>> splitPainting(vector<vector<int>>& segments) {\n // Add start and end points o | AlexPG | NORMAL | 2024-08-31T14:34:10.211870+00:00 | 2024-08-31T14:34:10.211899+00:00 | 8 | false | \n# Code\n```cpp []\nclass Solution {\npublic:\n vector<vector<long long>> splitPainting(vector<vector<int>>& segments) {\n // Add start and end points of each segment to line with color value\n vector<pair<int, int>> line;\n line.reserve(segments.size());\n for (auto& segment : segments) {\n line.push_back({segment[0], segment[2]});\n line.push_back({segment[1], -segment[2]});\n }\n // Sort all points in increasing order\n sort(begin(line), end(line));\n long long color = line[0].second;\n int start = line[0].first;\n vector<vector<long long>> result;\n result.reserve(segments.size());\n // Use prefix sum to calculate color of each segment.\n // Add all segments with color into result array.\n for (int i = 1; i < line.size(); i++) {\n if (line[i].first != start) {\n if (color != 0)\n result.push_back({start, line[i].first, color});\n start = line[i].first;\n }\n color += line[i].second;\n }\n return result;\n }\n};\n\nauto init = []() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n cout.tie(nullptr);\n return \'c\';\n}();\n\n``` | 0 | 0 | ['C++'] | 0 |
describe-the-painting | easy simple solution using prefix and diff array. | easy-simple-solution-using-prefix-and-di-a2d3 | 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 | romaishawaqar | NORMAL | 2024-08-22T10:14:11.261011+00:00 | 2024-08-22T10:14:11.261042+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 vector<vector<long long>> splitPainting(vector<vector<int>>& segments) {\n set<long long> st;\n for(auto & it : segments){\n st.insert(it[0]);\n st.insert(it[1]);\n }\n vector<long long> a(st.begin(),st.end());\n \n \n vector<long long> b(1e5+5,0);\n for(auto & it : segments){\n long long l = it[0];\n long long r = it[1];\n b[l] += it[2];\n b[r] -= it[2];\n }\n \n vector<long long> pref(1e5+5,0);\n pref[0] = b[0];\n for(int i = 1; i < 1e5; i++){\n pref[i] = pref[i-1] + b[i];\n }\n // for(int i = 0; i < pref.size(); i++){\n // cout<<pref[i]<<" ";\n // }\n vector<vector<long long>> ans;\n ans.push_back({a[0],a[1],pref[a[0]]});\n for(int i = 1; i < a.size()-1; i++){\n if(pref[a[i]] == 0) continue;\n ans.push_back({a[i],a[i+1],pref[a[i]]}); \n }\n return ans;\n\n\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
describe-the-painting | C++ || O (N) || Explanation | c-o-n-explanation-by-gismet-4fes | Approach\nWhen we reach the start of a segment ,let\'s say, at point x, we increase the color sum at that point. When we reach the end of that segment, we decre | Gismet | NORMAL | 2024-07-09T13:16:18.132196+00:00 | 2024-07-09T13:22:55.713556+00:00 | 10 | false | # Approach\nWhen we reach the start of a segment ,let\'s say, at point x, we increase the color sum at that point. When we reach the end of that segment, we decrease, say, at point y, we decrease the color sum at that point. \n\nLet\'s say we have the following segments. Let\'s describe the above process. \n\n`[1, 6, 8], [3, 8, 2], [4, 9, 3]`\n\nWe have an array of size 10, (one larger than the rightmost end of painting, which is 9 in this case)\n\nThe array would like like the following:\n\n`[0, 8, 0, 2, 3, 0, -8, 0, -2, -3]`\n\nSegment 1 persist up to index 6 (its end)\n\nSegment 1 intersect , at point 3, with Segment 2. Up to this point \nwe have sum equal to 8, so we create a segment `[1, 3, 8]`. The start of the next segment is determined as the current point, which is either the start or end of some segment. \n\nAfter point `3`, the start of Segment 2, Segment 1 still continues. And we also have Segment 2 (since it started at point `3`). We add `2` to the sum. Now we have 10. We again encounter another point - the start of the Segment 3. So we create a segment `[3, 4, 10]`. A new segment is created every time we encounter either the start or end of some segment by following `[start, the current point, sum]`. The start is assigned the current point again, which is 4. We add `3` (at index 4) to sum, making it `13`. We reach `-8` at point 6 (which is the end of the Segment 1). We create a segment again `[4, 6, 13]`. The start is assigned `6` (the end of the Segment 1). We add `-8` to sum, making it `5` (which is the color sum of Segment 2 and Segment 3). \n\n`-8` decreased the current sum. It actually means that a Segment with sum `8` just stopped continuing further and we do not need to consider its color value anymore. `-8` might not only mean a single segment but also multiple segments whose sum of color values decrease the current sum by 8. \n\n# Complexity\n- Time complexity:\n`O(n)` (probably with large constant factors)\n\n- Space complexity:\n`O(n)` (again beware of large factors)\n\n# Code\n```\n#define vv std::vector\n#define ll long long\n\nclass Solution {\npublic:\n vector<vector<long long>> splitPainting(vector<vector<int>>& S) {\n\n int n = int(S.size()); // the number of segments\n int end = S[0][1]; // the very end of the painting\n int start = S[0][0]; // the very start of the painting\n for(int i = 1; i < n; i++)\n {\n end = std::max(end, S[i][1]);\n start = std::min(start, S[i][0]);\n }\n\n vv<vv<ll>> ans; // result array\n vv<ll> painting(end + 1, 0); // painting\n std::unordered_set<int> isSegmentEnd; // is it either the start or the end ?\n\n for(int i = 0; i < n; i++)\n {\n painting[S[i][0]] += S[i][2]; // increase segment color\n painting[S[i][1]] += (-1 * S[i][2]); //end of some segment, decrease it\n isSegmentEnd.insert(S[i][0]); // start of some segment\n isSegmentEnd.insert(S[i][1]); // end of some segment\n }\n\n ll sum = painting[start]; // color sum of the first segment\n\n for(int i = start + 1; i < end + 1; i++)\n {\n //is i the start or end point of some segment?\n if(isSegmentEnd.contains(i))\n {\n if(sum != 0)\n ans.push_back({start, i, sum});\n sum += painting[i];\n start = i;\n }\n }\n\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
describe-the-painting | 1943. Describe the Painting.cpp | 1943-describe-the-paintingcpp-by-202021g-8n1e | Code\n\nclass Solution {\npublic:\n vector<vector<long long>> splitPainting(vector<vector<int>>& segments) {\n vector<vector<int>> vals; \n for | 202021ganesh | NORMAL | 2024-07-02T09:52:32.254521+00:00 | 2024-07-02T09:52:32.254559+00:00 | 0 | false | **Code**\n```\nclass Solution {\npublic:\n vector<vector<long long>> splitPainting(vector<vector<int>>& segments) {\n vector<vector<int>> vals; \n for (auto& segment : segments) {\n vals.push_back({segment[0], segment[2]}); \n vals.push_back({segment[1], -segment[2]}); \n }\n sort(vals.begin(), vals.end()); \n int prev = 0; \n long long prefix = 0; \n vector<vector<long long>> ans; \n for (auto& val : vals) {\n if (prev < val[0] && prefix) ans.push_back({prev, val[0], prefix}); \n prev = val[0]; \n prefix += val[1]; \n }\n return ans; \n }\n};\n``` | 0 | 0 | ['C'] | 0 |
describe-the-painting | [Javascript] O(n) time O(n) space | javascript-on-time-on-space-by-alexdovzh-6waf | Solution\n\n/**\n * @param {number[][]} segments\n * @return {number[][]}\n */\nvar splitPainting = function(segments) {\n const colorMap = {}\n let max = | alexdovzhanyn | NORMAL | 2024-07-01T20:02:19.839881+00:00 | 2024-07-01T20:02:19.839910+00:00 | 6 | false | # Solution\n```\n/**\n * @param {number[][]} segments\n * @return {number[][]}\n */\nvar splitPainting = function(segments) {\n const colorMap = {}\n let max = 0\n\n segments.forEach(([start, end, color]) => {\n if (end > max) max = end\n colorMap[start] = (colorMap[start] || 0) + color\n colorMap[end] = (colorMap[end] || 0) - color\n })\n\n let currentColor = 0\n let result = []\n let resIdx = -1\n\n for (let i = 1; i < max; i++) {\n if (colorMap[i] != undefined) {\n currentColor += (colorMap[i] || 0)\n \n if (currentColor) {\n resIdx += 1\n result[resIdx] = [i, i, currentColor]\n }\n }\n \n if (currentColor) {\n result[resIdx][1] += 1\n }\n }\n\n return result\n};\n```\n\n# Intuition\nWe need to keep track of how the colors are changing as we go through the line. When we get to a new color, if that color overlaps the current color, we need to mix them. If we end our segment and reach a segment that has the same color, even if the segments touch, we need to keep them as separate results in the result set because the mixing is different\n\n# Approach\nWe can keep a map of each color start index, and a counter `max` to let us know how long the entire line of the painting is.\n\nFirst, we loop through the segments. For each segment:\n1. Add the color to the `colorMap` at the index where the segment starts.\n2. Subtract the color from the `colorMap` at the index where the segment ends. (This is because the color is no longer being used after this point in the painting).\n3. Check if the end of the segment is greater than our `max`. If it is, update `max`. This will give us the total size of the painting after we\'re done looping.\n\n```javascript\nconst colorMap = {}\nlet max = 0\n\nsegments.forEach(([start, end, color]) => {\n if (end > max) max = end\n colorMap[start] = (colorMap[start] || 0) + color\n colorMap[end] = (colorMap[end] || 0) - color\n})\n```\n\nNext we can initialize some variables:\n\n```javascript\nlet currentColor = 0 // This will be the color we are actively using\nlet result = [] // This will be our result output array\nlet resIdx = -1 // This will be the idx we increment while we go through the painting\n```\n\nFinally, we loop through all the spaces in the painting, starting from 1, all the way to `max`. We can stop at max because we know no other segments will appear after that.\n\nIf the `colorMap` has an entry at the current space in the painting we are checking, that means we must be switching colors. (Either a segment started here or ended here). If we\'re switching colors, that means we must be at a point where we add a new entry to the `result` array. \n\nWe add whatever is in the `colorMap` at our current index to `currentColor`. This might be a positive or negative number. If we had an input, for example, like: `[[1,4,5],[4,7,7],[1,7,9]]` (Example 1), our `colorMap` would look like this:`{ \'1\': 14, \'4\': 2, \'7\': -16 }`.\n\nSo at first, `currentColor` will be 0. Then, `currentColor += (colorMap[i] || 0)` will cause `currentColor` to be 14. Once we get to the 4th space in the painting, `currentColor += (colorMap[i] || 0)` will cause the `currentColor` to be 16.\n\nAs long as `currentColor` is not 0, we want to increment `resIdx` every time we switch colors (if it was 0 that means we have a gap between colors and we dont want to add that to the output).\n\nWhenever we switch colors, we want to initialize `result[resIdx]` to have an array, with `i` as the starting point, `i` as the temporary ending point, and `currentColor` as the color.\n\nThen, for every `i` where we do not change colors, we just want to increment the current `result[idx]` to increment the ending point of the segment:\n\n```javascript\nif (currentColor) {\n result[resIdx][1] += 1\n}\n``` \n\nSo the above gets us:\n\n```javascript\nfor (let i = 1; i < max; i++) {\n if (colorMap[i] != undefined) {\n currentColor += (colorMap[i] || 0)\n \n if (currentColor) {\n resIdx += 1\n result[resIdx] = [i, i, currentColor]\n }\n }\n \n if (currentColor) {\n result[resIdx][1] += 1\n }\n}\n```\n\n# Complexity\n- **Time complexity:**\n Since we only iterate through the input set one time, and then iterate through the numbers between the first index and last index of the whole paiting, the time complexity is $$O(n)$$\n\n- Space complexity:\n$$O(n)$$\n\n | 0 | 0 | ['Hash Table', 'JavaScript'] | 0 |
describe-the-painting | [Python3] O(NlogN) sweep line/prefix sum | python3-onlogn-sweep-lineprefix-sum-by-p-oni6 | Complexity\n- Time complexity:\n Add your time complexity here, e.g. O(n) \nO(nlog(n))\n- Space complexity:\n Add your space complexity here, e.g. O(n) \nO(n)\n | pipilongstocking | NORMAL | 2024-06-17T14:14:51.058616+00:00 | 2024-06-17T14:14:51.058649+00:00 | 15 | false | # Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(nlog(n))$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n# Code\n```\nclass Solution:\n def splitPainting(self, segments: List[List[int]]) -> List[List[int]]:\n d = defaultdict(int)\n for start, end, color in segments:\n d[start] += color\n d[end] -= color\n prefix, candidate, ans = 0, [], []\n for end in sorted(d):\n if prefix:\n ans.append([candidate, end, prefix])\n candidate = end\n prefix += d[end]\n return ans\n``` | 0 | 0 | ['Line Sweep', 'Prefix Sum', 'Python3'] | 0 |
describe-the-painting | scala oneliner | scala-oneliner-by-vititov-x2vm | scala\nobject Solution {\n def splitPainting: Array[Array[Int]] => List[List[Long]] = _.toList\n .flatMap{a => List(a(0) -> a(2), a(1) -> -a(2))}\n .grou | vititov | NORMAL | 2024-06-11T23:50:05.592403+00:00 | 2024-06-11T23:50:05.592425+00:00 | 4 | false | ```scala\nobject Solution {\n def splitPainting: Array[Array[Int]] => List[List[Long]] = _.toList\n .flatMap{a => List(a(0) -> a(2), a(1) -> -a(2))}\n .groupMapReduce(_._1)(_._2.toLong)(_ + _).to(List).sorted\n .scanLeft((0L,0L)){case ((_,c0),(x1,c1)) => x1.toLong -> (c0+c1)}\n .sliding(2,1).map{case l => List(l.head._1,l.last._1,l.head._2)}\n .filterNot(_(2) == 0).toList\n}\n\n``` | 0 | 0 | ['Hash Table', 'Sliding Window', 'Sorting', 'Scala'] | 0 |
describe-the-painting | [Python3] O(M) | python3-om-by-timetoai-iyuf | Approach\n Describe your approach to solving the problem. \nCreate array of changes c, where store each change of color happened. Then resolve it to intervals.\ | timetoai | NORMAL | 2024-06-10T13:13:58.203974+00:00 | 2024-06-10T13:13:58.204008+00:00 | 3 | false | # Approach\n<!-- Describe your approach to solving the problem. -->\nCreate array of changes `c`, where store each change of color happened. Then resolve it to intervals.\n\n# Complexity\n- Time complexity: $$O(max(N, M))$$\nN - total `segments`\nM - max end of segment\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(M)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def splitPainting(self, segments: List[List[int]]) -> List[List[int]]:\n c = [None] * (max(x[1] for x in segments) + 1)\n for s in segments:\n c[s[0]] = s[2] if c[s[0]] is None else c[s[0]] + s[2]\n c[s[1]] = - s[2] if c[s[1]] is None else c[s[1]] - s[2]\n ret = []\n cur = 0\n inter = []\n for i in range(len(c)):\n if c[i] is not None:\n if cur > 0:\n inter[1] = i\n ret.append(inter)\n cur += c[i]\n inter = [i, i, cur]\n if cur > 0:\n inter[1] = len(c)\n ret.append(inter)\n return ret\n\n``` | 0 | 0 | ['Python3'] | 0 |
describe-the-painting | python sorted dictionary | python-sorted-dictionary-by-harrychen199-jt5z | 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 | harrychen1995 | NORMAL | 2024-05-28T19:28:49.911969+00:00 | 2024-05-28T19:28:49.912010+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 def splitPainting(self, segments: List[List[int]]) -> List[List[int]]:\n ans = []\n p = collections.defaultdict(int)\n for s, e , c in segments:\n p[s] +=c\n p[e] -=c\n p = dict(sorted(p.items()))\n curr = 0\n prev = 0\n for k in p:\n if curr > 0:\n ans.append([prev, k, curr])\n curr +=p[k]\n prev = k\n return ans\n``` | 0 | 0 | ['Python3'] | 0 |
describe-the-painting | Sweep line w TreeMap - Java O(N*logN) | O(N) | sweep-line-w-treemap-java-onlogn-on-by-w-ax1x | Intuition\n Describe your first thoughts on how to solve this problem. \nPut every start and end position with color value to a TreeMap. Then sweep line prefix | wangcai20 | NORMAL | 2024-05-28T12:58:23.768046+00:00 | 2024-05-28T12:59:34.460696+00:00 | 18 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nPut every `start` and `end` position with color value to a `TreeMap`. Then sweep line prefix sum colors value, if previous point is not `0`, add the segment of previous point (start) to current point (end).\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(N*logN)$$ -- from TreeMap\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 public List<List<Long>> splitPainting(int[][] segments) {\n // sweep line w Map\n Map<Long, Long> map = new TreeMap<>(Map.of(0l, 0l));\n for (int[] seg : segments) {\n map.merge((long) seg[0], (long) seg[2], Long::sum);\n map.merge((long) seg[1], -1 * (long) seg[2], Long::sum);\n }\n List<List<Long>> res = new LinkedList<>();\n Map.Entry<Long, Long> prev = null;\n for (Map.Entry<Long, Long> entry : map.entrySet()) {\n if (entry.getKey() != 0l) {\n entry.setValue(entry.getValue() + prev.getValue());\n if (prev.getValue() != 0l) // skip if prev closed or it\'s first elem\n res.add(List.of(prev.getKey(), entry.getKey(), prev.getValue()));\n }\n prev = entry;\n }\n return res;\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
describe-the-painting | [C++] Line Sweep | c-line-sweep-by-amanmehara-nrad | Complexity\n- Time complexity: O(nlogn)\n- Space complexity: O(n)\n\n# Code\n\nclass Solution {\npublic:\n vector<vector<long long>> splitPainting(vector<vec | amanmehara | NORMAL | 2024-05-23T04:56:17.373406+00:00 | 2024-05-23T04:56:17.373434+00:00 | 28 | false | # Complexity\n- Time complexity: $$O(nlogn)$$\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<long long>> splitPainting(vector<vector<int>>& segments) {\n vector<tuple<int, int, int>> points;\n for (int i = 0; i < segments.size(); i++) {\n points.push_back({segments[i][0], 1, i});\n points.push_back({segments[i][1], -1, i});\n }\n sort(points.begin(), points.end());\n unordered_set<int> active;\n long long sum = 0;\n int prev = -1;\n vector<vector<long long>> result;\n for (const auto& [x, is_entry, i] : points) {\n if (prev != x) {\n if (prev != -1 && sum) {\n result.push_back({prev, x, sum});\n }\n prev = x;\n }\n if (is_entry < 0) {\n sum -= segments[i][2];\n active.erase(i);\n } else {\n sum += segments[i][2];\n active.insert(i);\n }\n }\n return result;\n }\n};\n``` | 0 | 0 | ['Array', 'Sorting', 'C++'] | 0 |
describe-the-painting | JAVA 98.44%, with Sum Array | java-9844-with-sum-array-by-meringueee-vyyq | 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 | meringueee | NORMAL | 2024-05-23T04:23:33.308344+00:00 | 2024-05-23T04:23:33.308380+00:00 | 14 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public List<List<Long>> splitPainting(int[][] segments) {\n List<List<Long>> r = new ArrayList<>();\n boolean[] v = new boolean[100_001];\n long[] x = new long[100_001];\n int a=0, min=200_000, max=0; long c=0;\n for(int[] s:segments){\n v[s[0]]=v[s[1]]=true;\n x[s[0]]+=s[2]; x[s[1]]-=s[2];\n if(min>s[0])min=s[0];\n if(max<s[1])max=s[1];\n }\n for(int b=min; b<=max; b++){\n if(v[b] || x[b]!=0){\n if(c!=0)r.add(getArr(a,b,c));\n a=b; c+=x[b];\n }\n }\n return r;\n }\n private List<Long> getArr(long a, long b, long c){\n List<Long> l = new ArrayList<>(3);\n l.add(a); l.add(b); l.add(c);\n return l;\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
describe-the-painting | Python, difference array solution with explanation | python-difference-array-solution-with-ex-ra4w | \n### difference array \nIn the original version of difference array, we will use a array to keep track of changed value, but in the problem, we will use anothe | shun6096tw | NORMAL | 2024-05-07T07:49:07.349697+00:00 | 2024-05-07T07:49:07.349720+00:00 | 7 | false | \n### difference array \nIn the original version of difference array, we will use a array to keep track of changed value, but in the problem, we will use another version of difference array (discretization),\n\nIn the problem, we have a lot of intervals, if current color is cur, and we meet a left side of an interval, color will change.\nSo, the changed value is interval\'s color, and we meet a left side, color will be added,\nif we meet a right side, color will be substracted.\n\nwe can mark each position\'s changed value, and sort it.\nAnd do the prefix sum to calculate actual color.\ntc is O(nlogn), sc is O(1) except the answer array.\n\n\n```python\nclass Solution:\n def splitPainting(self, segments: List[List[int]]) -> List[List[int]]:\n points = []\n for x, y, c in segments:\n points.append((x, c))\n points.append((y, -c))\n points.sort()\n cur = 0\n start = points[0][0]\n ans = []\n for x, c in sorted(points):\n if x != start: # enter a new interval or leave a interval\n if cur > 0:\n ans.append([start, x, cur])\n start = x\n cur += c\n return ans\n``` | 0 | 0 | ['Array', 'Sorting', 'Python'] | 0 |
describe-the-painting | python | python-by-ashutosh_leet-w20j | 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 | ashutosh_leet | NORMAL | 2024-05-02T06:09:32.101337+00:00 | 2024-05-02T06:09:32.101361+00:00 | 4 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def splitPainting(self, segments: List[List[int]]) -> List[List[int]]:\n comb=defaultdict(int)\n for start,end,color in segments:\n comb[start]+=color\n comb[end]-=color\n res=[]\n sum1=0\n prev=None\n for i in sorted(comb):\n if prev is not None and sum1!=0:\n res.append([prev,i,sum1])\n sum1+=comb[i]\n prev=i\n return res \n\n \n``` | 0 | 0 | ['Python3'] | 0 |
describe-the-painting | Python easy to read and understand | line-sweep | python-easy-to-read-and-understand-line-83usi | ```\nclass Solution:\n def splitPainting(self, segments: List[List[int]]) -> List[List[int]]:\n d = collections.defaultdict(int)\n for u, v, co | sanial2001 | NORMAL | 2024-04-25T19:04:52.232312+00:00 | 2024-04-25T19:04:52.232335+00:00 | 8 | false | ```\nclass Solution:\n def splitPainting(self, segments: List[List[int]]) -> List[List[int]]:\n d = collections.defaultdict(int)\n for u, v, cost in segments:\n d[u] += cost\n d[v] -= cost\n \n prev, cost = 0, 0\n res = []\n for key in sorted(d):\n if cost:\n res.append((prev, key, cost))\n cost += d[key]\n prev = key\n \n return res | 0 | 0 | ['Python', 'Python3'] | 0 |
describe-the-painting | Python (Simple Hashmap) | python-simple-hashmap-by-rnotappl-dkkk | 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 | rnotappl | NORMAL | 2024-03-22T15:47:19.671251+00:00 | 2024-03-22T15:47:19.671273+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 splitPainting(self, segments):\n dict1, i, result = defaultdict(int), 0, []\n\n for s,e,c in segments:\n dict1[s] += c \n dict1[e] -= c \n\n for j in sorted(dict1):\n if dict1[i]:\n result.append([i,j,dict1[i]])\n dict1[j] += dict1[i]\n i = j\n\n return result\n``` | 0 | 0 | ['Python3'] | 0 |
describe-the-painting | JS || Solution by Bharadwaj | js-solution-by-bharadwaj-by-manu-bharadw-l5fn | Code\n\nvar splitPainting = function (segments) {\n let arr = [];\n segments.forEach(([start, end, val]) => {\n arr.push([start, val]);\n ar | Manu-Bharadwaj-BN | NORMAL | 2024-03-08T09:09:11.362455+00:00 | 2024-03-08T09:09:11.362488+00:00 | 31 | false | # Code\n```\nvar splitPainting = function (segments) {\n let arr = [];\n segments.forEach(([start, end, val]) => {\n arr.push([start, val]);\n arr.push([end, -val]);\n });\n arr.sort((i, j) => i[0] - j[0]);\n\n let res = [];\n let currVal = 0, prevTime;\n arr.forEach(([time, val]) => {\n if (prevTime !== undefined && currVal && prevTime !== time) res.push([prevTime, time, currVal]);\n currVal += val;\n prevTime = time;\n })\n\n return res;\n};\n``` | 0 | 0 | ['JavaScript'] | 1 |
describe-the-painting | Easy to understand JavaScript solution (Prefix Sum) | easy-to-understand-javascript-solution-p-b2fx | Complexity\n- Time complexity:\nO(nlogn)\n\n- Space complexity:\nO(n)\n\n# Code\n\nvar splitPainting = function(segments) {\n const paintMap = segments.reduc | tzuyi0817 | NORMAL | 2024-01-24T09:54:09.236994+00:00 | 2024-01-24T09:54:09.237031+00:00 | 6 | false | # Complexity\n- Time complexity:\n$$O(nlogn)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\nvar splitPainting = function(segments) {\n const paintMap = segments.reduce((map, [start, end, color]) => {\n map[start] = (map[start] ?? 0) + color;\n map[end] = (map[end] ?? 0) - color;\n\n return map;\n }, {});\n const paints = Object.keys(paintMap).sort((a, b) => a - b);\n let currentMix = left = 0;\n\n return paints.reduce((result, right) => {\n currentMix > 0 && result.push([+left, +right, currentMix]);\n left = right;\n currentMix += paintMap[right];\n return result;\n }, []);\n};\n``` | 0 | 0 | ['JavaScript'] | 0 |
describe-the-painting | From POV of React | | push the start and end when ever state changes. | from-pov-of-react-push-the-start-and-end-z38b | Intuition\n Describe your first thoughts on how to solve this problem. \n- My Idea is I will push when ever state changes . State will change when either one el | aryan20022003 | NORMAL | 2024-01-01T07:39:40.603194+00:00 | 2024-01-01T07:39:40.603228+00:00 | 17 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- My Idea is I will push when ever state changes . State will change when either one element enter of one element exit the set.\n- I will just store and check is state changed or not if chaged then save the previous state.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n#define ll long long\nclass Solution {\npublic:\n vector<vector<long long>> splitPainting(vector<vector<int>>& segments) {\n priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> entry, exit;\n ll start = INT_MAX, end = INT_MIN;\n\n for (auto it : segments) {\n entry.push({it[0], it[2]});\n exit.push({it[1], it[2]});\n start = min(start, (ll)it[0]);\n end = max(end, (ll)it[1]); // Fixed typo: "it" instead of "it[1]"\n }\n\n ll prevStart = 0;\n ll sum = 0;\n vector<vector<ll>> ansQueue;\n\n for (ll i = start; i <= end; i++) {\n bool stateActive = false;\n ll tempSum=sum;\n if (exit.size() != 0 && exit.top().first == i) {\n stateActive = true;\n while (exit.size() != 0 && exit.top().first == i) {\n sum -= exit.top().second; // Fixed typo: "enter" instead of "exit"\n exit.pop();\n }\n }\n \n if (entry.size() != 0 && entry.top().first == i) {\n stateActive = true;\n while (entry.size() != 0 && entry.top().first == i) {\n sum += entry.top().second;\n entry.pop();\n }\n }\n\n \n\n if (stateActive && prevStart != 0 && tempSum!=0) { // Fixed condition: "prevStart" instead of "prevStart != 0"\n ansQueue.push_back({prevStart, i, tempSum});\n }\n\n if (stateActive) {\n prevStart = i;\n }\n }\n\n return ansQueue;\n }\n};\n\n``` | 0 | 0 | ['Heap (Priority Queue)', 'C++'] | 0 |
describe-the-painting | NLogN | nlogn-by-user3043sb-kb9n | 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 | user3043SB | NORMAL | 2023-12-05T14:56:50.615831+00:00 | 2023-12-05T14:56:50.615855+00:00 | 7 | 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```\nimport java.util.*;\n\nclass Solution {\n\n public List<List<Long>> splitPainting(int[][] segments) {\n List<List<Long>> ans = new LinkedList<>();\n TreeMap<Integer, Long> idToCnt = new TreeMap<>();\n for (int[] s : segments) {\n idToCnt.put(s[0], idToCnt.getOrDefault(s[0], 0L) + s[2]);\n idToCnt.put(s[1], idToCnt.getOrDefault(s[1], 0L) - s[2]);\n }\n List<Map.Entry<Integer, Long>> list = new ArrayList<>(idToCnt.entrySet());\n long currCnt = 0;\n for (int i = 0; i + 1 < list.size(); i++) {\n currCnt += list.get(i).getValue();\n if (currCnt == 0) continue;\n long start = list.get(i).getKey();\n long end = list.get(i + 1).getKey();\n \n List<Long> seg = new ArrayList<>(3);\n seg.add(start);\n seg.add(end);\n seg.add(currCnt);\n ans.add(seg);\n }\n\n return ans;\n }\n\n}\n\n``` | 0 | 0 | ['Java'] | 0 |
describe-the-painting | c#, Sweep Line | c-sweep-line-by-bytchenko-izh2 | Intuition\n Describe your first thoughts on how to solve this problem. \nHere we have a typical sweeping line algorithm: for each interval [a.. b] (color c) we | bytchenko | NORMAL | 2023-11-23T14:25:32.505933+00:00 | 2023-11-23T14:25:32.505953+00:00 | 11 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nHere we have a typical sweeping line algorithm: for each interval `[a.. b] (color c)` we generate 2 events: `(start : a, add : c)` and `(start : b, add : -c)` which means that starting from `a` we should `c` to color and starting from `b` we should add `-c` to color. The next step is standard: we sort and group all events by `start` and scan the events while generating intervals for the final answer.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Local function to generate events from segments\n- Linq query to sort and group the events\n- Simple loop to generate intervals\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n * log(n))$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n\n# Code\n```\npublic class Solution {\n public IList<IList<long>> SplitPainting(int[][] segments) {\n IEnumerable<(long start, long add)> Intervals() {\n foreach (var segment in segments) {\n yield return (segment[0], segment[2]);\n yield return (segment[1], -segment[2]);\n }\n }\n\n var intervals = Intervals()\n .GroupBy(item => item.start, item => item.add)\n .Select(group => (start : group.Key, add : group.Sum()))\n .OrderBy(item => item.start)\n .ToList();\n\n long color = 0;\n\n List<IList<long>> result = new List<IList<long>>();\n\n for (int i = 1; i < intervals.Count; ++i) \n if ((color += intervals[i - 1].add) > 0)\n result.Add(new List<long>() {intervals[i - 1].start, intervals[i].start, color});\n \n return result;\n }\n}\n``` | 0 | 0 | ['C#'] | 0 |
describe-the-painting | BTreeMap - collect and iterate | btreemap-collect-and-iterate-by-mknawara-l7qr | Code\n\nuse std::collections::BTreeMap;\n\n#[inline]\nfn inc(hm: &mut BTreeMap<i32, i64>, k: i32, v: i64) {\n let v = match hm.get(&k) {\n Some(&x) => | mknawara | NORMAL | 2023-10-31T23:53:01.370472+00:00 | 2023-10-31T23:53:01.370495+00:00 | 4 | false | # Code\n```\nuse std::collections::BTreeMap;\n\n#[inline]\nfn inc(hm: &mut BTreeMap<i32, i64>, k: i32, v: i64) {\n let v = match hm.get(&k) {\n Some(&x) => x + v,\n None => v,\n };\n hm.insert(k, v);\n}\n\nimpl Solution {\n pub fn split_painting(segments: Vec<Vec<i32>>) -> Vec<Vec<i64>> {\n let mut hm: BTreeMap<i32, i64> = BTreeMap::new();\n segments\n .iter()\n .for_each(|segment| match segment.as_slice() {\n [start, end, color] => {\n inc(&mut hm, *start, *color as i64);\n inc(&mut hm, *end, (-1 * color) as i64);\n }\n _ => panic!("shouldn\'t happen"),\n });\n\n let mut iter = hm.iter();\n let (&(mut p), &acc) = iter.next().unwrap();\n let mut acc = acc as i64;\n let mut res: Vec<Vec<i64>> = vec![];\n iter.for_each(|(&e, &k)| {\n if acc > 0 {\n let v = vec![p as i64, e as i64, acc];\n res.push(v);\n }\n p = e;\n acc += k as i64;\n });\n res\n }\n}\n``` | 0 | 0 | ['Rust'] | 0 |
describe-the-painting | C# Solution using PriorityQueue | c-solution-using-priorityqueue-by-jack00-1so7 | 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 | jack0001 | NORMAL | 2023-10-21T22:29:53.792122+00:00 | 2023-10-21T22:29:53.792140+00:00 | 8 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\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```\npublic class Solution {\n public IList<IList<long>> SplitPainting(int[][] segments) {\n int n = segments.Length;\n IList<IList<long>> res = new List<IList<long>>();\n PriorityQueue<(int, int, bool), int> q = new();\n\n long clrSum = 0;\n \n for(int i=0; i<n; ++i){\n int s = segments[i][0];\n int e = segments[i][1];\n q.Enqueue((s, i, true), s);\n q.Enqueue((e, i, false), e);\n }\n\n while(q.Count>1){\n int start = q.Peek().Item1;\n while(q.Count>0 && q.Peek().Item1 == start){\n var (s, idx, isHead) = q.Dequeue();\n int clr = segments[idx][2];\n clrSum += isHead ? clr : -clr;\n }\n\n if(q.Count>0 && clrSum!=0){\n res.Add(new List<long>(){ start, q.Peek().Item1, clrSum }); \n }\n }\n\n return res;\n }\n}\n``` | 0 | 0 | ['C#'] | 0 |
describe-the-painting | Easy C++ Solution | easy-c-solution-by-nehagupta_09-xk1s | \n\n# Code\n\nclass Solution {\npublic:\n vector<vector<long long>> splitPainting(vector<vector<int>>& arr) {\n vector<vector<long long>>ans;\n | NehaGupta_09 | NORMAL | 2023-10-11T10:47:09.438482+00:00 | 2023-10-11T10:47:09.438503+00:00 | 22 | false | \n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<long long>> splitPainting(vector<vector<int>>& arr) {\n vector<vector<long long>>ans;\n unordered_set<int>st;\n int size=0;\n for(int i=0;i<arr.size();i++)\n {\n size=max(size,arr[i][1]);\n st.insert(arr[i][1]);\n }\n size++;\n long long v[100001]={0};\n for(int i=0;i<arr.size();i++)\n {\n v[arr[i][0]]+=arr[i][2];\n v[arr[i][1]]-=arr[i][2];\n }\n for(int i=1;i<size;i++)\n {\n v[i]+=v[i-1];\n }\n int i=1;\n while(i<size)\n {\n int start=i;\n long long col=v[i];\n if(col==0)\n {\n i++;\n continue;\n }\n while(i<size and v[i]==col)\n {\n if(st.find(i)!=st.end() and i!=start)\n {\n ans.push_back({start,i,col});\n start=i;\n }\n i++;\n }\n ans.push_back({start,i,col});\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
describe-the-painting | C++ solution | c-solution-by-pejmantheory-etti | 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 | pejmantheory | NORMAL | 2023-08-30T18:28:47.178507+00:00 | 2023-08-30T18:28:47.178528+00:00 | 17 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public:\n vector<vector<long long>> splitPainting(vector<vector<int>>& segments) {\n vector<vector<long long>> ans;\n int prevIndex = 0;\n long long runningMix = 0;\n map<int, long long> timeline;\n\n for (const vector<int>& segment : segments) {\n const int start = segment[0];\n const int end = segment[1];\n const int color = segment[2];\n timeline[start] += color;\n timeline[end] -= color;\n }\n\n for (const auto& [i, mix] : timeline) {\n if (runningMix > 0)\n ans.push_back({prevIndex, i, runningMix});\n runningMix += mix;\n prevIndex = i;\n }\n\n return ans;\n }\n};\n\n``` | 0 | 0 | ['C++'] | 0 |
describe-the-painting | C# Sweep Line | c-sweep-line-by-zloytvoy-ten5 | 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 | zloytvoy | NORMAL | 2023-08-26T09:38:18.247125+00:00 | 2023-08-26T09:38:18.247147+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:\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```\npublic class Solution {\n public IList<IList<long>> SplitPainting(int[][] segments) \n {\n var events = new Dictionary<int, long>();\n\n foreach(var segment in segments)\n {\n events.TryAdd(segment[0], 0);\n events[segment[0]] += segment[2];\n\n events.TryAdd(segment[1], 0);\n events[segment[1]] -= segment[2];\n }\n\n var sum = 0L;\n var result = new List<IList<long>>();\n var start = -1;\n var keys = events.Keys.ToList();\n keys.Sort();\n foreach(var key in keys)\n {\n if(start == -1)\n {\n start = key;\n }\n else\n {\n if(sum != 0)\n {\n result.Add( new List<long>() {start, key, sum} );\n }\n start = key;\n }\n sum += events[key];\n } \n\n return result;\n }\n}\n``` | 0 | 0 | ['C#'] | 0 |
describe-the-painting | C++ beats 99% O(n) time O(n) space -> Rolling Hash | c-beats-99-on-time-on-space-rolling-hash-tgo6 | Intuition\nUpon inspection, it\'s fairly clear that you set +color on the left, and -color on the right, then when you take the cumulative sum of this array, yo | chroniclesofcode | NORMAL | 2023-08-17T12:25:05.904365+00:00 | 2023-08-17T12:25:05.904385+00:00 | 17 | false | # Intuition\nUpon inspection, it\'s fairly clear that you set +color on the left, and -color on the right, then when you take the cumulative sum of this array, you will have the sum of all mixed colors for every single element (note the bounds of [l,r) allow this, if it was larger you would have to use a map solution instead of an array-based solution).\n\nI then tried to check if sum[i] != sum[i-1], if this holds, then we can add it to ans. However, this does not take into account when 2 colors add to the same sum. I was thinking of a map based approach, but wasn\'t really satisfied with the logn overhead. So I decided to use a rolling hash, since even if two numbers add to the same thing, their hash will be different. So I set hash[l] and hash[r] to be the negative, and took the cumulative sum. I checked if hash[l] != hash[l-1] and if this doesn\'t hold, we add the original sum[i-1] to ans. Anyways, the details are in the code - there\'s a lot of extra stuff as well. \n\nAlso, theoretically there could be a test case this code fails for, since the hash function might provide a collision for two numbers, but this is incredibly unlikely for something of this size.\n\n# Complexity\n- Time complexity:\n$$O(r)$$ where $$r$$ is the rightmost value of the segment, approximately $$n$$.\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\nclass Solution {\npublic:\n long long seg[(int)1e5+1];\n long long hash[(int)1e5+1];\n long long p[(int)1e5+1];\n vector<vector<long long>> splitPainting(vector<vector<int>>& segments) {\n int n = segments.size();\n int mx = 0;\n\n for (int i = 0; i < (int)1e5+1; i++) {\n p[i] = 1;\n }\n int m = 1e9+9;\n int pp = 31;\n \n for (int i = 0; i < n; i++) {\n int l = segments[i][0];\n int r = segments[i][1];\n int c = segments[i][2];\n seg[l] += c;\n seg[r] -= c;\n p[l] *= pp;\n p[l] %= m;\n int addval = ((c + 1) * p[l]) % m; \n hash[l] = (hash[l] + addval) % m;\n hash[r] = (hash[r] - addval) % m;\n\n mx = max(mx, r);\n }\n for (int i = 2; i < mx; i++) {\n seg[i] += seg[i-1];\n hash[i] += hash[i-1];\n if (hash[i] < 0) hash[i] = (hash[i] + m) % m;\n }\n \n vector<vector<long long>> ans;\n int beg = hash[1] <= 0 ? 2 : 1;\n for (int i = 2; i <= mx; i++) {\n if (hash[i] != hash[i-1] && hash[i-1] > 0) {\n ans.push_back({beg, i, seg[i-1]});\n beg = i;\n }\n if (hash[i] <= 0) {\n beg = i+1;\n }\n }\n return ans;\n }\n};\n\n``` | 0 | 0 | ['C++'] | 0 |
describe-the-painting | java Line Sweep | java-line-sweep-by-ymahlawat-fec5 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n\n# Complexity\n- Time complexity:\n- O(nlogn)\n\n- Space complexity: \n- | ymahlawat | NORMAL | 2023-08-09T17:48:25.428265+00:00 | 2023-08-09T17:48:25.428292+00:00 | 13 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n\n# Complexity\n- Time complexity:\n- O(nlogn)\n\n- Space complexity: \n- O(n)\n\n# Code\n```\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.TreeMap;\n\nclass Solution {\n\tpublic List<List<Long>> splitPainting(int[][] segments) {\n\n\t\tList<List<Long>> ans = new ArrayList<>();\n\n\t\tTreeMap<Integer,Long> map = new TreeMap<>();\n\t\tfor (int []a:segments){\n\t\t\tmap.putIfAbsent(a[0],(long)0);\n\t\t\tmap.put(a[0],map.get(a[0])+a[2]);\n\t\t\tmap.putIfAbsent(a[1],(long)0);\n\t\t\tmap.put(a[1],map.get(a[1])-a[2]);\n\t\t}\n\n\t\tint start=map.firstKey();\n\t\tlong sum=map.get(start);\n\t\twhile (true) {\n\n\t\t\tInteger a = map.higherKey(start);\n\t\t\tif (a != null) {\n\t\t\t\tlong val = map.get(a);\n\t\t\n\t\t\t\tSystem.out.println(start+" "+a+" "+sum);\n\t\t\t\tif (sum !=0) {\n\t\t\t\t\tList<Long> temp = new ArrayList<>();\n\t\t\t\t\ttemp.add((long) start);\n\t\t\t\t\ttemp.add((long)a);\n\t\t\t\t\ttemp.add(sum);\n\t\t\t\t\tans.add(temp);\n\t\t\t\t}\n\t\t\t\t\tsum += val;\n\t\t\t} else {\n\t\t\t\treturn ans;\n\t\t\t}\n\t\t\tstart = a;\n\t\t}\n\n\t}\n}\n``` | 0 | 0 | ['Java'] | 0 |
describe-the-painting | TC : O(N*LogN) | SC : O(N) | C++ | Prefix Sum | tc-onlogn-sc-on-c-prefix-sum-by-omkarsas-4mlp | Code\n\nclass Solution {\npublic:\n vector<vector<long long>> splitPainting(vector<vector<int>>& segments) {\n int n = segments.size();\n \n | omkarsase | NORMAL | 2023-07-01T20:22:43.884509+00:00 | 2023-07-01T20:22:43.884530+00:00 | 30 | false | # Code\n```\nclass Solution {\npublic:\n vector<vector<long long>> splitPainting(vector<vector<int>>& segments) {\n int n = segments.size();\n \n vector<vector<long long>> painting;\n map<int, long long> tracker;\n \n for (int i = 0; i < n; i++) {\n tracker[segments[i][0]] += segments[i][2];\n tracker[segments[i][1]] -= segments[i][2];\n }\n \n long long prevNum = 0;\n long long prevSum = 0;\n \n for (auto it = tracker.begin(); it != tracker.end(); it++) {\n if (prevSum > 0) {\n painting.push_back({prevNum, it->first, prevSum});\n }\n \n prevSum += it->second;\n prevNum = it->first;\n }\n \n return painting;\n }\n};\n\n``` | 0 | 0 | ['Ordered Map', 'Prefix Sum', 'C++'] | 0 |
describe-the-painting | C++ Map unique | c-map-unique-by-abhishek6487209-78cm | 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 | Abhishek6487209 | NORMAL | 2023-06-16T04:15:02.568449+00:00 | 2023-06-16T04:15:02.568470+00:00 | 19 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<long long>> splitPainting(vector<vector<int>>& segments) {\n sort(segments.begin(),segments.end()); \n map<int,long long> mp;\n for(vector<int> it:segments){\n mp[it[0]]+=it[2];\n mp[it[1]]-=it[2];\n }\n long long j=0,k=0;\n vector<vector<long long>> ans;\n for(auto x: mp){\n long long prev=j;\n j+=x.second;\n if(prev!=0){\n ans.push_back({k,x.first,prev});\n }\n k=x.first;\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
describe-the-painting | Simple Array Based Line Sweep using prefix sum | simple-array-based-line-sweep-using-pref-r9jf | \n\n# Code\n\nclass Solution {\n public List<List<Long>> splitPainting(int[][] segments) {\n int max = Integer.MIN_VALUE;\n int min = Integer.M | jhapranay | NORMAL | 2023-05-27T19:06:37.878917+00:00 | 2023-05-27T19:06:37.878950+00:00 | 84 | false | \n\n# Code\n```\nclass Solution {\n public List<List<Long>> splitPainting(int[][] segments) {\n int max = Integer.MIN_VALUE;\n int min = Integer.MAX_VALUE;\n List<List<Long>> ans = new ArrayList<>();\n\n for (int[] seg : segments) {\n max = Math.max(max, seg[1]);\n min = Math.min(min, seg[0]);\n }\n long[] holder = new long[max + 2];\n Set<Integer> criticalPoint = new HashSet<>();\n\n for (int[] seg : segments) {\n long prevVal[] = new long[] {holder[seg[0]], holder[seg[1]]};\n holder[seg[0]] += seg[2];\n holder[seg[1]] += -seg[2]; \n // Checking the change of value to add critical points\n if (prevVal[0] != 0 && holder[seg[0]] == 0) {\n criticalPoint.add(seg[0]);\n }\n\n if (prevVal[1] != 0 && holder[seg[1]] == 0) {\n criticalPoint.add(seg[1]);\n }\n }\n\n for (int i = 1; i < holder.length; i++) {\n holder[i] += holder[i - 1];\n }\n int slow = min;\n int fast = min;\n long curr = holder[slow];\n\n while (fast <= max) {\n\n if (fast == max || curr != holder[fast] || criticalPoint.contains(fast)) {\n\n if (holder[slow] != 0) {\n List<Long> temp = new ArrayList<>();\n temp.add((long)slow);\n temp.add((long)fast);\n temp.add(curr);\n ans.add(temp);\n }\n curr = holder[fast];\n slow = fast;\n }\n fast++;\n }\n return ans;\n }\n}\n``` | 0 | 0 | ['Array', 'Line Sweep', 'Prefix Sum', 'Java'] | 0 |
describe-the-painting | Java Line Sweep | java-line-sweep-by-cuber12-fdem | \nclass Solution {\n public List<List<Long>> splitPainting(int[][] segments) {\n // Create a TreeMap to store the segment start and end points as keys | cuber12 | NORMAL | 2023-05-10T15:02:09.022197+00:00 | 2023-05-10T15:02:09.022238+00:00 | 22 | false | ```\nclass Solution {\n public List<List<Long>> splitPainting(int[][] segments) {\n // Create a TreeMap to store the segment start and end points as keys\n // and the accumulated color values as values\n TreeMap<Long, Long> tm = new TreeMap<>();\n \n // Process each segment\n for (int[] seg : segments) {\n // Increment the color value at the segment start point\n tm.put((long) seg[0], tm.getOrDefault((long) seg[0], 0L) + (long) seg[2]);\n \n // Decrement the color value at the segment end point\n tm.put((long) seg[1], tm.getOrDefault((long) seg[1], 0L) - (long) seg[2]);\n }\n \n // Create a list to store the non-overlapping segments of mixed colors\n List<List<Long>> ans = new ArrayList<>();\n \n // Variables to keep track of accumulated color value and segment state\n long acc = 0L;\n boolean st = true;\n List<Long> currentSegment = null;\n \n // Traverse the TreeMap entries\n for (var entry : tm.entrySet()) {\n // Update the accumulated color value\n acc += entry.getValue();\n \n // If the previous segment was not starting, update its end point\n if (!st) {\n currentSegment.set(1, entry.getKey());\n st = !st;\n }\n \n // If the current segment is starting and has a positive accumulated color value,\n // create a new segment and add it to the answer list\n if (st && acc > 0) {\n currentSegment = new ArrayList<>();\n currentSegment.add(entry.getKey());\n currentSegment.add(-1L);\n currentSegment.add(acc);\n ans.add(currentSegment);\n st = !st;\n }\n }\n \n return ans;\n }\n}\n\n``` | 0 | 0 | ['Java'] | 0 |
describe-the-painting | C++ | Easy Solution | Prefix Sum | Using Vector | Using Map | c-easy-solution-prefix-sum-using-vector-72wxo | Intuition\nWe are using prefix sum but both approach differ on the basis of data structure. \nIn first approach , we using vector for prefix sum ,it can work fo | Prathvi_Singh | NORMAL | 2023-05-09T10:49:03.606570+00:00 | 2023-05-09T10:49:03.606603+00:00 | 55 | false | # Intuition\nWe are using prefix sum but both approach differ on the basis of data structure. \nIn first approach , we using vector for prefix sum ,it can work for this problem because here (start ,end<=1e5) .\n In approach second , we using map as data structure for prefix Sum ,it can even work for greater value of (start,end). \n\n\n\n# Code\n```\nUsing vector \n\nclass Solution {\npublic:\n vector<vector<long long>> splitPainting(vector<vector<int>>& segments) {\n vector<long long> vis(1e5+1,0);\n int n=segments.size();\n unordered_map<int,int> m;\n\n for(int i=0;i<n;i++){\n vis[segments[i][0]]+=segments[i][2];\n vis[segments[i][1]]-=segments[i][2];\n m[segments[i][1]]++;\n }\n\n vector<vector<long long>> ans;\n int j=0;\n for(int i=1;i<vis.size();i++){\n \n vis[i]+=vis[i-1];\n \n if(vis[i-1]==0) {\n j=i;\n continue; \n } \n \n if(vis[i]!=vis[i-1] || m.find(i)!=m.end()){\n ans.push_back({j,i,vis[i-1]});\n j=i;\n } \n }\n\n return ans;\n\n }\n};\n\n.................................\nUsing Map \n\nclass Solution {\npublic:\n vector<vector<long long>> splitPainting(vector<vector<int>>& segments) {\n int n=segments.size();\n map<long long,long long> m;\n for(int i=0;i<n;i++){\n m[segments[i][0]]+=segments[i][2];\n m[segments[i][1]]-=segments[i][2];\n }\n vector<vector<long long>> ans;\n int flag=0;\n long long sum=0,prev=0,prev_index=0;\n\n for(auto it:m){\n sum+=it.second;\n if(flag!=0 && prev>0){\n ans.push_back({prev_index,it.first,prev});\n }\n flag=1;\n prev_index=it.first;\n prev=sum;\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['Prefix Sum', 'C++'] | 0 |
describe-the-painting | C++ O(nlogn): A Readable and Easy-to-Understand Solution | c-onlogn-a-readable-and-easy-to-understa-6bvv | Intuition\nWe are only interested in the ends of the segments. Our approach is to sort all the segment ends and then iterate through them to find the answer.\n\ | mani5h | NORMAL | 2023-05-06T09:01:07.251322+00:00 | 2023-05-06T09:01:07.251359+00:00 | 56 | false | # Intuition\nWe are only interested in the ends of the segments. Our approach is to sort all the segment ends and then iterate through them to find the answer.\n\n# Approach\nFirst, we create a struct `segEnd` to store information about each segment end. The struct contains three fields: `isEnd`, `val`, and `color`. isEnd is a boolean that indicates whether the segment end is a start or an end. `val` is the value of the segment end. `color` is the color of the segment.\n\nNext, we create a vector `segmentEnds` to store all the segment ends. For each segment in `segments`, we push its start and end into `segmentEnds`.\n\nAfter that, we sort `segmentEnds` in ascending order of their values. If two segment ends have the same value, we put the one that is an end before the one that is a start.\n\nThen, we iterate through `segmentEnds`. We use a variable `curSum` to keep track of the current sum of colors and a variable `prev` to keep track of the previous segment end value. For each segment end, we update `curSum` and `prev` accordingly. If it is an end, we subtract its color from `curSum`. If it is a start, we add its color to `curSum`. If `prev` is not equal to the current segment end value and `curSum` is not 0, we push {`prev`, `cur`, `curSum`} into the result vector.\n\n# Complexity\n- Time complexity:` O(nlogn)`\n where n is the number of segments.\n- Space complexity:` O(n)`\n where n is the number of segments.\n\n# Code\n```\nclass Solution {\npublic:\n struct segEnd{\n bool isEnd;\n int val;\n int color;\n };\n\n vector<vector<long long>> splitPainting(vector<vector<int>>& segments) {\n vector<vector<long long>> res;\n vector<segEnd> segmentEnds;\n for (int i = 0; i < segments.size(); i++) {\n segmentEnds.push_back(\n {\n 0,\n segments[i][0],\n segments[i][2]\n }\n );\n segmentEnds.push_back(\n {\n 1,\n segments[i][1],\n segments[i][2]\n }\n );\n }\n\n sort(segmentEnds.begin(), segmentEnds.end(), [](const segEnd& a, const segEnd& b) {\n if (a.val == b.val)\n return (a.isEnd < b.isEnd);\n return a.val < b.val;\n });\n\n long long curSum = 0;\n int prev = -1;\n \n for (auto i: segmentEnds) {\n int cur = i.val;\n int col = i.color;\n bool isEnd = i.isEnd;\n\n if (isEnd) {\n if (prev != cur && curSum != 0) {\n res.push_back(vector<long long>({prev, cur, curSum}));\n }\n curSum -= col;\n prev = cur;\n } else {\n if (prev != cur && curSum != 0 && prev != -1) {\n res.push_back(vector<long long>({prev, cur, curSum}));\n }\n curSum += col;\n prev = cur;\n }\n }\n return res;\n }\n};\n``` | 0 | 0 | ['Line Sweep', 'C++'] | 0 |
describe-the-painting | Prefix Sum || Easy C++ Solution | prefix-sum-easy-c-solution-by-lotus18-mtr6 | Code\n\nclass Solution \n{\npublic:\n vector<vector<long long>> splitPainting(vector<vector<int>>& segments) \n {\n int n=1e5+1;\n vector<lo | lotus18 | NORMAL | 2023-04-30T13:37:17.318694+00:00 | 2023-04-30T13:37:17.318739+00:00 | 52 | false | # Code\n```\nclass Solution \n{\npublic:\n vector<vector<long long>> splitPainting(vector<vector<int>>& segments) \n {\n int n=1e5+1;\n vector<long long> prefix(n,0);\n vector<long long> splitt(n,0);\n for(auto segment: segments)\n {\n int st=segment[0]-1, en=segment[1]-1;\n prefix[st]+=segment[2];\n prefix[en]-=segment[2];\n splitt[st]=1;\n splitt[en]=1;\n }\n for(int x=1; x<n; x++)\n {\n prefix[x]=prefix[x-1]+prefix[x];\n }\n vector<vector<long long>> ans;\n int i=0;\n while(i<n)\n {\n long long p=prefix[i];\n int st=i;\n i++;\n while(i<n && prefix[i]==p && !splitt[i]) i++;\n if(i==n) break;\n splitt[i]=0;\n if(p)\n {\n vector<long long> v={st+1,i+1,p};\n ans.push_back(v);\n }\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['Prefix Sum', 'C++'] | 0 |
describe-the-painting | [C++] Sweep Line | c-sweep-line-by-rahul_barnwal-uzgr | \n#define ll long long\nclass Solution {\npublic:\n vector<vector<long long>> splitPainting(vector<vector<int>>& segments) {\n map <ll, ll> mp;\n | Rahul_Barnwal | NORMAL | 2023-04-29T09:09:40.105321+00:00 | 2023-04-29T09:09:40.105365+00:00 | 9 | false | ```\n#define ll long long\nclass Solution {\npublic:\n vector<vector<long long>> splitPainting(vector<vector<int>>& segments) {\n map <ll, ll> mp;\n for(auto &it: segments) {\n ll start = it[0], end = it[1], color = it[2];\n mp[start] += color;\n mp[end] -= color;\n }\n vector <vector<ll>> ans;\n ll a = -1, b = -1, sum = 0;\n for(auto &it: mp) {\n if(a == -1) {\n a = it.first;\n sum += it.second;\n }\n else {\n b = it.first;\n if(sum != 0) ans.push_back({a, b, sum});\n sum += it.second;\n a = b;\n b = -1;\n }\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['C'] | 0 |
describe-the-painting | Python, beats 98% 10 lines. | python-beats-98-10-lines-by-dev_lvl_80-a0wo | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nDefine list of breaking | dev_lvl_80 | NORMAL | 2023-04-19T23:06:45.910357+00:00 | 2023-04-19T23:06:45.910392+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. -->\nDefine list of breaking points, calculate effective color as aggretable meausure which changes at breaking points.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def splitPainting(self, segments: List[List[int]]) -> List[List[int]]:\n changes_points = defaultdict(int)\n ret = []\n for s in segments:\n changes_points[s[0]] += s[2]\n changes_points[s[1]] -= s[2]\n color = 0\n for cr_pos in sorted(changes_points):\n if color != 0:\n ret.append([prev_pos, cr_pos, color])\n prev_pos = cr_pos\n color += changes_points[cr_pos]\n return ret\n``` | 0 | 0 | ['Python3'] | 0 |
describe-the-painting | line sweep ^^ | line-sweep-by-andrii_khlevniuk-7irb | time: O(NlogN); space: O(N)\n\n\n\n\nvector<vector<long long>> splitPainting(vector<vector<int>>& s)\n{\n\tmap<int,long long> m;\n\tfor(const auto & s : s)\n\t\ | andrii_khlevniuk | NORMAL | 2023-04-06T19:13:26.411815+00:00 | 2023-04-08T11:10:29.940760+00:00 | 32 | false | **time: `O(NlogN)`; space: `O(N)`**\n\n\n\n```\nvector<vector<long long>> splitPainting(vector<vector<int>>& s)\n{\n\tmap<int,long long> m;\n\tfor(const auto & s : s)\n\t\tm[s[0]]+=s[2], m[s[1]]-=s[2];\n\n\tvector<vector<long long>> out;\n\tlong long t{}; int p{};\n\tfor(const auto & [i,j] : m)\n\t{\n\t\tif(t) out.push_back({p,i,t});\n\t\tt += j; \n\t\tp = i;\n\t}\n\treturn out;\n}\n```\n**Similar problems :**\n[2406. Divide Intervals Into Minimum Number of Groups](https://leetcode.com/problems/divide-intervals-into-minimum-number-of-groups/discuss/3393422/line-sweep)\n[2381. Shifting Letters II](https://leetcode.com/problems/shifting-letters-ii/discuss/3393419/line-sweep)\n[1943. Describe the Painting](https://leetcode.com/problems/describe-the-painting/discuss/3387661/line-sweep)\n[253. Meeting Rooms II](https://leetcode.com/problems/meeting-rooms-ii/discuss/2115681/few-solutions) | 0 | 0 | ['C', 'C++'] | 0 |
describe-the-painting | C++ | c-by-tinachien-jduc | \nclass Solution {\npublic:\n vector<vector<long long>> splitPainting(vector<vector<int>>& segments) {\n set<int>Set ;\n map<int, long long>Map | TinaChien | NORMAL | 2023-03-22T12:09:26.313438+00:00 | 2023-03-22T12:11:52.598059+00:00 | 12 | false | ```\nclass Solution {\npublic:\n vector<vector<long long>> splitPainting(vector<vector<int>>& segments) {\n set<int>Set ;\n map<int, long long>Map ;\n for(auto& seg : segments){\n int a = seg[0] ;\n int b = seg[1] ;\n int c = seg[2] ;\n Set.insert(a) ;\n Set.insert(b) ;\n Map[a] += c ;\n Map[b] -= c ;\n }\n vector<vector<long long>>ret ;\n long long preSum = 0 ;\n for(auto & m : Map){\n m.second += preSum ;\n preSum = m.second ;\n }\n long long start = -1, end = -1 ;\n long long val = -1 ;\n for(auto& s : Set){\n if(start == -1 && Map[s] <= 0)\n continue ;\n if(start == -1){\n start = s ;\n val = Map[s] ;\n }\n else if(end == -1)\n end = s ;\n if(end != -1){\n ret.push_back({start, end, val}) ;\n if(Map[end] > 0){\n start = end ;\n val = Map[end] ;\n }\n else \n start = -1 ;\n end = -1 ;\n }\n }\n return ret ;\n }\n};\n``` | 0 | 0 | ['Ordered Set'] | 0 |
describe-the-painting | Just a runnable solution | just-a-runnable-solution-by-ssrlive-b38r | Code\n\nimpl Solution {\n pub fn split_painting(segments: Vec<Vec<i32>>) -> Vec<Vec<i64>> {\n let mut mix = vec![0; 100002];\n let mut ends = v | ssrlive | NORMAL | 2023-02-28T13:57:11.922782+00:00 | 2023-02-28T13:57:11.922827+00:00 | 15 | false | # Code\n```\nimpl Solution {\n pub fn split_painting(segments: Vec<Vec<i32>>) -> Vec<Vec<i64>> {\n let mut mix = vec![0; 100002];\n let mut ends = vec![false; 100002];\n let mut res = vec![];\n for s in segments {\n mix[s[0] as usize] += s[2] as i64;\n mix[s[1] as usize] -= s[2] as i64;\n ends[s[0] as usize] = true;\n ends[s[1] as usize] = true;\n }\n let mut sum = 0;\n let mut last_i = 0;\n for i in 1..100002 {\n if ends[i] && sum > 0 {\n res.push(vec![last_i as i64, i as i64, sum]);\n }\n if ends[i] {\n last_i = i;\n }\n sum += mix[i];\n }\n res\n }\n}\n``` | 0 | 0 | ['Rust'] | 0 |
construct-binary-search-tree-from-preorder-traversal | [Java/C++/Python] O(N) Solution | javacpython-on-solution-by-lee215-1nfr | Intuition:\nFind the left part and right part,\nthen recursively construct the tree.\n\n\n# Solution 1:\nBinary search\n\nPython, O(N^2)\npy\n def bstFromPre | lee215 | NORMAL | 2019-03-10T04:03:30.298562+00:00 | 2020-05-25T03:11:10.360139+00:00 | 67,089 | false | # **Intuition**:\nFind the left part and right part,\nthen recursively construct the tree.\n<br>\n\n# **Solution 1**:\nBinary search\n\n**Python, `O(N^2)`**\n```py\n def bstFromPreorder(self, A):\n if not A: return None\n root = TreeNode(A[0])\n i = bisect.bisect(A, A[0])\n root.left = self.bstFromPreorder(A[1:i])\n root.right = self.bstFromPreorder(A[i:])\n return root\n```\n\n**Python, `O(NlogN)`**\n```py\n def bstFromPreorder(self, A):\n def helper(i, j):\n if i == j: return None\n root = TreeNode(A[i])\n mid = bisect.bisect(A, A[i], i + 1, j)\n root.left = helper(i + 1, mid)\n root.right = helper(mid, j)\n return root\n return helper(0, len(A))\n```\n<br>\n\n\n# **Solution 2**\n\nGive the function a bound the maximum number it will handle.\nThe left recursion will take the elements smaller than `node.val`\nThe right recursion will take the remaining elements smaller than `bound`\n\n\n**Complexity**\n`bstFromPreorder` is called exactly `N` times.\nIt\'s same as a preorder traversal.\nTime `O(N)`\nSpace `O(H)`\n\n**Java**\n```java\n int i = 0;\n public TreeNode bstFromPreorder(int[] A) {\n return bstFromPreorder(A, Integer.MAX_VALUE);\n }\n\n public TreeNode bstFromPreorder(int[] A, int bound) {\n if (i == A.length || A[i] > bound) return null;\n TreeNode root = new TreeNode(A[i++]);\n root.left = bstFromPreorder(A, root.val);\n root.right = bstFromPreorder(A, bound);\n return root;\n }\n```\n**C++**\n```cpp\n int i = 0;\n TreeNode* bstFromPreorder(vector<int>& A, int bound = INT_MAX) {\n if (i == A.size() || A[i] > bound) return NULL;\n TreeNode* root = new TreeNode(A[i++]);\n root->left = bstFromPreorder(A, root->val);\n root->right = bstFromPreorder(A, bound);\n return root;\n }\n```\n**Python**\n```python\n i = 0\n def bstFromPreorder(self, A, bound=float(\'inf\')):\n if self.i == len(A) or A[self.i] > bound:\n return None\n root = TreeNode(A[self.i])\n self.i += 1\n root.left = self.bstFromPreorder(A, root.val)\n root.right = self.bstFromPreorder(A, bound)\n return root\n```\n<br>\n\n# Solution 2.1\nSome may don\'t like the global variable `i`.\nWell, I first reused the function in python,\nso I had to use it, making it a "stateful" function.\n\nI didn\'t realize there would be people who care about it.\nIf it\'s really matters,\nWe can discard the usage of global function.\n\n**C++**\n```cpp\n TreeNode* bstFromPreorder(vector<int>& A) {\n int i = 0;\n return build(A, i, INT_MAX);\n }\n\n TreeNode* build(vector<int>& A, int& i, int bound) {\n if (i == A.size() || A[i] > bound) return NULL;\n TreeNode* root = new TreeNode(A[i++]);\n root->left = build(A, i, root->val);\n root->right = build(A, i, bound);\n return root;\n }\n```\n**Java**\n```java\n public TreeNode bstFromPreorder(int[] A) {\n return bstFromPreorder(A, Integer.MAX_VALUE, new int[]{0});\n }\n\n public TreeNode bstFromPreorder(int[] A, int bound, int[] i) {\n if (i[0] == A.length || A[i[0]] > bound) return null;\n TreeNode root = new TreeNode(A[i[0]++]);\n root.left = bstFromPreorder(A, root.val, i);\n root.right = bstFromPreorder(A, bound, i);\n return root;\n }\n```\n**Python**\n```python\n def bstFromPreorder(self, A):\n return self.buildTree(A[::-1], float(\'inf\'))\n\n def buildTree(self, A, bound):\n if not A or A[-1] > bound: return None\n node = TreeNode(A.pop())\n node.left = self.buildTree(A, node.val)\n node.right = self.buildTree(A, bound)\n return node\n``` | 850 | 11 | [] | 74 |
construct-binary-search-tree-from-preorder-traversal | Python stack solution beats 100% on runtime and memory | python-stack-solution-beats-100-on-runti-kike | Idea is simple.\n First item in preorder list is the root to be considered.\n For next item in preorder list, there are 2 cases to consider:\n\t If value is les | cenkay | NORMAL | 2019-03-10T15:09:58.652313+00:00 | 2019-03-10T15:09:58.652376+00:00 | 15,592 | false | * Idea is simple.\n* First item in preorder list is the root to be considered.\n* For next item in preorder list, there are 2 cases to consider:\n\t* If value is less than last item in stack, it is the left child of last item.\n\t* If value is greater than last item in stack, pop it.\n\t\t* The last popped item will be the parent and the item will be the right child of the parent.\n```\nclass Solution:\n def bstFromPreorder(self, preorder: List[int]) -> TreeNode:\n root = TreeNode(preorder[0])\n stack = [root]\n for value in preorder[1:]:\n if value < stack[-1].val:\n stack[-1].left = TreeNode(value)\n stack.append(stack[-1].left)\n else:\n while stack and stack[-1].val < value:\n last = stack.pop()\n last.right = TreeNode(value)\n stack.append(last.right)\n return root\n``` | 257 | 5 | ['Stack', 'Python'] | 20 |
construct-binary-search-tree-from-preorder-traversal | C++ O(n log n) and O(n) | c-on-log-n-and-on-by-votrubac-v2b0 | The first element p[0] in the array corresponds to the root. Then, we find the split point i such as p[i] >= p[0]. Subarray [1, i - 1] corresponds to the left s | votrubac | NORMAL | 2019-03-10T04:10:41.703519+00:00 | 2020-01-15T13:06:08.669185+00:00 | 20,192 | false | The first element ```p[0]``` in the array corresponds to the root. Then, we find the split point ```i``` such as ```p[i] >= p[0]```. Subarray ```[1, i - 1]``` corresponds to the left subtree, ```[i, n - 1]``` - to the right one.\n```\nTreeNode* bstFromPreorder(vector<int> &p, int first = 0, int last = 0) {\n if (last == 0) last = p.size();\n if (first == last) return nullptr;\n auto split = find_if(begin(p) + first, begin(p) + last, [&](int val) { return val > p[first]; });\n auto root = new TreeNode(p[first]);\n root->left = bstFromPreorder(p, first + 1, split - begin(p));\n root->right = bstFromPreorder(p, split - begin(p), last);\n return root;\n}\n```\n**Complexity Analysis**\n- Runtime: *O(n * n)* worst case, *O(n log n)* average case. For each node (*n*), we search for the split point (*log n* average, *n* worst case).\n- Memory: *O(n)* worst case, *O(h)* average case for the stack, where *h* is the height of the tree.\n\n#### O(n) Solution\nIn the solution above, we are searching for a split point to divide the interval. Instead, we can pass the parent value to the recursive function to generate the left sub-tree. The generation will stop when the value in the `preorder` array exceeds the parent value. That will be our split point to start generating the right subtree.\n```CPP\nint idx = 0;\nTreeNode* bstFromPreorder(vector<int>& preorder, int p_val = INT_MAX) {\n if (idx >= preorder.size() || preorder[idx] > p_val)\n return nullptr;\n auto n = new TreeNode(preorder[idx++]);\n n->left = bstFromPreorder(preorder, n->val);\n n->right = bstFromPreorder(preorder, p_val);\n return n;\n}\n``` | 146 | 3 | [] | 16 |
construct-binary-search-tree-from-preorder-traversal | Java Stack Iterative Solution | java-stack-iterative-solution-by-aoi-sil-86ps | \nclass Solution {\n public TreeNode bstFromPreorder(int[] preorder) {\n if (preorder == null || preorder.length == 0) {\n return null;\n | aoi-silent | NORMAL | 2019-03-10T16:37:18.374363+00:00 | 2019-03-10T16:37:18.374421+00:00 | 10,346 | false | ```\nclass Solution {\n public TreeNode bstFromPreorder(int[] preorder) {\n if (preorder == null || preorder.length == 0) {\n return null;\n }\n Stack<TreeNode> stack = new Stack<>();\n TreeNode root = new TreeNode(preorder[0]);\n stack.push(root);\n for (int i = 1; i < preorder.length; i++) {\n TreeNode node = new TreeNode(preorder[i]);\n if (preorder[i] < stack.peek().val) { \n stack.peek().left = node; \n } else {\n TreeNode parent = stack.peek();\n while (!stack.isEmpty() && preorder[i] > stack.peek().val) {\n parent = stack.pop();\n }\n parent.right = node;\n }\n stack.push(node); \n }\n return root;\n }\n}\n``` | 96 | 2 | [] | 7 |
construct-binary-search-tree-from-preorder-traversal | Python 3, Recursive, Easy to understand | python-3-recursive-easy-to-understand-by-g3hb | \nclass Solution:\n def bstFromPreorder(self, preorder: List[int]) -> TreeNode:\n if not preorder:\n return None\n root = TreeNode(p | timzeng | NORMAL | 2020-04-20T07:27:20.839038+00:00 | 2020-05-25T09:32:43.853151+00:00 | 9,106 | false | ```\nclass Solution:\n def bstFromPreorder(self, preorder: List[int]) -> TreeNode:\n if not preorder:\n return None\n root = TreeNode(preorder[0])\n i = 1\n while i<len(preorder) and preorder[i] < root.val:\n i+=1\n root.left = self.bstFromPreorder(preorder[1:i])\n root.right = self.bstFromPreorder(preorder[i:])\n return root\n```\n\nWork through with example `preorder = [8,5,1,7,10,12]`\n- root = preorder[0] = 8\n- root.left = [5,1,7]\n\t- root.left = 5\n\t- root.left.left = [1]\n\t\t- root.left.left = 1\n\t- root.left.right = [7]\n\t\t- root.left.right = 7\n- root.right = [10,12]\n\t- root.right = 10\n\t- root.right.left = None\n\t- root.right.right = [12]\n\t\t- root.right.right = 12\n\n\n***\nCheck on my [repo](https://github.com/zengtian006/LeetCode) to get Leetcode solution(Python) with classification: https://github.com/zengtian006/LeetCode\n***\n\n | 88 | 1 | ['Python3'] | 14 |
construct-binary-search-tree-from-preorder-traversal | JAVA EASIEST SOLUTION -WITH CLEAR EXPLANATION OF LOGIC! | java-easiest-solution-with-clear-explana-7hj9 | ok lets do this!!\nso we are given an array which is the preorder traversal of the some tree!\nwe are used to traverse a tree a but are not privy to reconstruct | naturally_aspirated | NORMAL | 2020-04-20T14:11:35.866514+00:00 | 2020-04-21T04:24:34.708723+00:00 | 11,957 | false | ok lets do this!!\nso we are given an array which is the preorder traversal of the some tree!\nwe are used to traverse a tree a but are not privy to reconstruct the tree from the array!!\nanyways!!!\nso we are given an array whose first element is the root of out tree!!(because of preorder traversal)!\nNOTE:this is not a linear solution!i have posted linear solutions here https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/discuss/589801/JAVA-3-WAYS-TO-DO-THE-PROBLEM!-O(N)-APPROACH\nBUT i strongly suggest you go through this soution below so that you can get the gist of the logic and then move on to the more complex linear solutions i posted!\n\nLETS DO THIS:\n\nso we follow steps:\n1>we create the node\n2>we traverse the array for values which are less than the current node!-- these values will become our left subtree.we stop whenever we get a value larger than the current root of the subtree!\n3>we take the rest of the array(values whuch are greater than the value of the current root)-these are the values which will make out right subtree!\n\nso we make a root!\nmake the left subtree(recursively)\nthen make right subtree(recursively)\n\n\ncode here!!\ndo a couple of dry runs!\nu will get it!\n\n```\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode(int x) { val = x; }\n * }\n */\nclass Solution {\n public TreeNode bstFromPreorder(int[] preorder) {\n return helper(preorder, 0, preorder.length - 1); \n }\n \n private TreeNode helper(int[] preorder, int start, int end) {\n if(start > end) return null;\n \n TreeNode node = new TreeNode(preorder[start]);\n int i;\n for(i=start;i<=end;i++) {\n if(preorder[i] > node.val)\n break;\n }\n \n node.left = helper(preorder, start+1, i-1);\n node.right = helper(preorder, i, end);\n return node;\n \n \n \n }\n \n \n}\n```\n\nhope it helps!!\n\n | 85 | 3 | ['Java'] | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.