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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
max-increase-to-keep-city-skyline | [c++] very easy soln, beats 98% in runtime | c-very-easy-soln-beats-98-in-runtime-by-q7p92 | Approach\n Describe your approach to solving the problem. \n- Find the row and col maximum for each row and col respectively.\n- In order to keep the skyline un | vanshdhawan60 | NORMAL | 2023-09-16T09:37:31.176560+00:00 | 2023-09-16T09:37:31.176578+00:00 | 13 | false | # Approach\n<!-- Describe your approach to solving the problem. -->\n- Find the row and col maximum for each row and col respectively.\n- In order to keep the skyline unchanged, we set the height of each building such that it doesn\'t exceed the max row/col limit when viewed from either side.\n- To do this, we set its size to minimum of the rowmax & colmax.\n- We are required to find the overall unit increase in buildings size so we find the difference and keep accumulating it.\n\n# Complexity\n- Time complexity: $$O(n^2)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n int n = grid.size();\n vector<int> rowmax (n);\n vector<int> colmax (n);\n for (int i=0; i<n; i++) {\n int maxm = 0;\n for (int x: grid[i]) {\n maxm = max (maxm, x);\n }\n rowmax[i] = maxm;\n }\n for (int i=0; i<n; i++) {\n int maxm = 0;\n for (int j=0; j<n; j++) {\n maxm = max (maxm, grid[j][i]);\n }\n colmax[i] = maxm;\n }\n int ans = 0;\n for (int i=0; i<n; i++) {\n for (int j=0; j<n; j++) {\n ans += min (rowmax[i], colmax[j]) - grid[i][j];\n }\n }\n return ans;\n }\n};\n``` | 1 | 0 | ['Array', 'Matrix', 'C++'] | 0 |
max-increase-to-keep-city-skyline | || in java | in-java-by-2manas1-9zuz | 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 | 2manas1 | NORMAL | 2023-08-08T22:23:00.696696+00:00 | 2023-08-08T22:23:00.696766+00:00 | 453 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int maxIncreaseKeepingSkyline(int[][] grid) {\n // make a variable sum, which we will return in end.\n // first element grid[0][0], first find the Max element in row 0 and max element in coloumn 0. Then find Min b/w the 2. -> we do this process for everyelement in the matrix.\n\n // Then we update sum as sum = Min(Max(row),Max(coloumn))- grid[i][j].\n\n // Now we run our normal double for loop, which iterates through every element in the matrix.\n\n //int sum=0;\n\n int n = grid.length;\n int[] rowmax = new int[n];\n int[] colmax = new int[n];\n\n\n for(int i=0;i<n;i++){\n //let them me the max elements initially.\n //this is how we find max row and coloumn element of an element grid[i][j].\n // the max row/coloumn elements are stored in the respecitve arrays which will be later accessed to update sum in every step.\n rowmax[i]=grid[i][0];\n colmax[i]=grid[0][i];\n for(int j=0;j<n;j++){\n rowmax[i]= Math.max(rowmax[i],grid[i][j]);\n colmax[i]= Math.max(colmax[i],grid[j][i]);\n }\n }\n\n\n int sum=0;\n for(int i=0;i<n;i++){\n for(int j=0;j<n;j++){\n sum+= Math.min(rowmax[i], colmax[j])-grid[i][j];\n }\n }\nreturn sum;\n\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
max-increase-to-keep-city-skyline | EASY SOLUTION JAVA || 100% BEATS || GREEDY | easy-solution-java-100-beats-greedy-by-v-o3t0 | Approach\n Describe your approach to solving the problem. \nBy greedy on height, maximum of each row and column are finded and stored on the array rowMax and co | vijayanvishnu | NORMAL | 2023-07-31T13:00:20.737725+00:00 | 2023-07-31T13:00:20.737745+00:00 | 11 | false | # Approach\n<!-- Describe your approach to solving the problem. -->\nBy greedy on height, maximum of each row and column are finded and stored on the array <strong>rowMax</strong> and <strong>colMax</strong>.Difference of minimum(<strong>rowMax</strong>,<strong>colMax</strong>) and current element the maximum possibility in height improvement.\n\n# Complexity\n- Time complexity: $$O(N^2)$$ , on traversing the grid given.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(N)$$ , to hold maximum for rows and columns.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int maxIncreaseKeepingSkyline(int[][] grid) {\n int size = grid.length;\n int rowMax[] = new int[grid.length];\n int colMax[] = new int[grid.length];\n for(int i=0;i<size;i++){\n for(int j=0;j<size;j++){\n rowMax[i] = Math.max(rowMax[i],grid[i][j]);\n colMax[j] = Math.max(colMax[j],grid[i][j]);\n }\n }\n int res = 0;\n for(int i=0;i<size;i++){\n for(int j=0;j<size;j++){\n int rmax = rowMax[i];\n int cmax = colMax[j];\n int val = Math.min(rmax,cmax);\n res += val - grid[i][j];\n }\n }\n return res;\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
max-increase-to-keep-city-skyline | C++ easy solution beats 93% users | c-easy-solution-beats-93-users-by-mandar-mgg7 | \n\n# Code\n\nclass Solution {\npublic:\n int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n int n=grid.size();\n int sum=0;\n | Mandar_0 | NORMAL | 2023-07-24T18:13:14.782416+00:00 | 2023-07-24T18:13:14.782434+00:00 | 12 | false | \n\n# Code\n```\nclass Solution {\npublic:\n int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n int n=grid.size();\n int sum=0;\n vector<int> row;\n vector<int> col;\n\n\n\n for(int i=0;i<n;i++){\n int rowMax=INT_MIN;\n for(int j=0;j<n;j++){\n rowMax=max(rowMax,grid[i][j]);\n } \n row.push_back(rowMax);\n }\n\n for(int j=0;j<n;j++){\n int colMax=INT_MIN;\n for(int i=0;i<n;i++){\n colMax=max(colMax,grid[i][j]);\n } \n col.push_back(colMax);\n }\n\n\n for(int i=0;i<n;i++){\n for(int j=0;j<n;j++){\n sum+=(min(row[i],col[j])-grid[i][j]);\n } \n \n }\n\n \n\n return sum;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
max-increase-to-keep-city-skyline | Simple Using Priority Queue With Hindi Explanation|| Max Heap || Beginner Friendly ✅✅🔥 | simple-using-priority-queue-with-hindi-e-xpo3 | Intuition\n Describe your first thoughts on how to solve this problem. \nAgar hum dhyan se dekhen to hume pata chalega ki har element ki final value wahi hogi j | yxsh14 | NORMAL | 2023-07-10T15:02:18.335490+00:00 | 2023-07-10T15:02:18.335511+00:00 | 152 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAgar hum dhyan se dekhen to hume pata chalega ki har element ki final value wahi hogi jo us row & column k maximum elements main comparatively choti value hai. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nHum is intuition ko use karke har row & column ki max value nikal kar unko do arrays mai store kar lenge or grid ke har element ki value se dono k minimum ko compare karke uska difference store karte jayenge or sare iterations k baad usko return kar denge.\n\n\n# Complexity\n- Time complexity:pri\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n int r=grid.size();\n int c=grid[0].size();\n int ans=0;\n vector<int> row;\n vector<int> col;\n for (int i=0;i<r;i++){\n priority_queue<int> pq;\n for (int j=0;j<c;j++){\n pq.push(grid[i][j]);\n }\n row.push_back(pq.top());\n }\n for (int i=0;i<c;i++){\n priority_queue<int> pq;\n for (int j=0;j<r;j++){\n pq.push(grid[j][i]);\n }\n col.push_back(pq.top());\n }\n for (int i=0;i<r;i++){\n for (int j=0;j<c;j++){\n ans+=min(row[i],col[j])-grid[i][j];\n }\n }\n return ans;\n \n }\n};\n``` | 1 | 0 | ['Heap (Priority Queue)', 'C++'] | 0 |
max-increase-to-keep-city-skyline | Simple Using Priority Queue With Hindi Explanation|| Max Heap || Beginner Friendly ✅✅🔥 | simple-using-priority-queue-with-hindi-e-x12o | Intuition\n Describe your first thoughts on how to solve this problem. \nAgar hum dhyan se dekhen to hume pata chalega ki har element ki final value wahi hogi j | yxsh14 | NORMAL | 2023-07-10T15:02:16.145335+00:00 | 2023-07-10T15:02:16.145353+00:00 | 52 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAgar hum dhyan se dekhen to hume pata chalega ki har element ki final value wahi hogi jo us row & column k maximum elements main comparatively choti value hai. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nHum is intuition ko use karke har row & column ki max value nikal kar unko do arrays mai store kar lenge or grid ke har element ki value se dono k minimum ko compare karke uska difference store karte jayenge or sare iterations k baad usko return kar denge.\n\n\n# Complexity\n- Time complexity:pri\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n int r=grid.size();\n int c=grid[0].size();\n int ans=0;\n vector<int> row;\n vector<int> col;\n for (int i=0;i<r;i++){\n priority_queue<int> pq;\n for (int j=0;j<c;j++){\n pq.push(grid[i][j]);\n }\n row.push_back(pq.top());\n }\n for (int i=0;i<c;i++){\n priority_queue<int> pq;\n for (int j=0;j<r;j++){\n pq.push(grid[j][i]);\n }\n col.push_back(pq.top());\n }\n for (int i=0;i<r;i++){\n for (int j=0;j<c;j++){\n ans+=min(row[i],col[j])-grid[i][j];\n }\n }\n return ans;\n \n }\n};\n``` | 1 | 0 | ['Heap (Priority Queue)', 'C++'] | 0 |
max-increase-to-keep-city-skyline | Easy and Fast Solution ✅ || 0ms - 100% beats ✅ || Fully Explained ✅ | easy-and-fast-solution-0ms-100-beats-ful-7mnc | Approach\n1. Initialize two arrays, rowMax and colMax, of size n to store the maximum height in each row and column, respectively.\n2. Traverse the grid and upd | akobirswe | NORMAL | 2023-07-06T07:45:44.313893+00:00 | 2023-07-06T07:45:44.313918+00:00 | 107 | false | # Approach\n1. Initialize two arrays, `rowMax` and `colMax`, of size `n` to store the maximum height in each row and column, respectively.\n2. Traverse the grid and update the `rowMax` array by finding the maximum height in each row.\n3. Traverse the grid again, but this time update the `colMax` array by finding the maximum height in each column.\n4. Initialize a variable `totalIncrease` to track the maximum total sum that the height of the buildings can be increased by without changing the skyline.\n5. Traverse the grid once more, and for each building at coordinates `(r, c)`, calculate the maximum height that can be increased without affecting the skylines. This can be determined by taking the minimum value between `rowMax[r]` and `colMax[c]`.\n6. Subtract the original height `grid[r][c]` from the calculated maximum height, and add it to `totalIncrease`.\n7. Finally, return the value of `totalIncrease`, which represents the maximum total sum of increased building heights while preserving the skylines.\n\nThis approach ensures that the skylines from all cardinal directions remain unchanged while maximizing the increase in building heights.\n\n# Complexity\n- Time complexity: $$O(n^2)$$\n\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution {\n public int maxIncreaseKeepingSkyline(int[][] grid) {\n int n = grid.length;\n int[] rowMax = new int[n];\n int[] colMax = new int[n];\n \n // Find the maximum height in each row\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n rowMax[i] = Math.max(rowMax[i], grid[i][j]);\n }\n }\n \n // Find the maximum height in each column\n for (int j = 0; j < n; j++) {\n for (int i = 0; i < n; i++) {\n colMax[j] = Math.max(colMax[j], grid[i][j]);\n }\n }\n \n int totalIncrease = 0;\n \n // Calculate the maximum increase in building heights without changing the skylines\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n int maxAllowedHeight = Math.min(rowMax[i], colMax[j]);\n totalIncrease += maxAllowedHeight - grid[i][j];\n }\n }\n \n return totalIncrease;\n }\n}\n``` | 1 | 0 | ['Array', 'Greedy', 'Matrix', 'Java', 'C#'] | 0 |
max-increase-to-keep-city-skyline | Swift solution O(n^2) | swift-solution-on2-by-user0031y-ew7j | 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 | user0031y | NORMAL | 2023-05-02T16:54:20.705187+00:00 | 2023-05-02T16:54:20.705226+00:00 | 15 | 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 func maxIncreaseKeepingSkyline(_ grid: [[Int]]) -> Int {\n\n var myGrid = grid\n var maxXArr = [Int]()\n var maxYArr = [Int]()\n\n var ans = 0\n\n for i in 0..<myGrid.count {\n let maxX = myGrid[i].max() ?? 0\n var temp = [Int]()\n \n for j in 0..<myGrid[i].count {\n let y = myGrid[j][i]\n temp.append(y)\n }\n let maxY = temp.max() ?? 0\n maxXArr.append(maxX)\n maxYArr.append(maxY)\n }\n \n print(maxXArr)\n print(maxYArr)\n \n for i in 0..<myGrid.count {\n for j in 0..<myGrid[i].count {\n let x = maxXArr[i]\n let y = maxYArr[j]\n let value = myGrid[i][j]\n let min = min(x, y)\n myGrid[i][j] = min\n ans += (min - value)\n }\n }\n\n return ans\n }\n}\n``` | 1 | 0 | ['Swift'] | 0 |
max-increase-to-keep-city-skyline | Solution | solution-by-deleted_user-luqy | C++ []\nclass Solution {\npublic:\n int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n vector<int>rowMax;\n vector<int>colMax;\n | deleted_user | NORMAL | 2023-05-01T00:09:48.732845+00:00 | 2023-05-01T01:23:08.742312+00:00 | 865 | false | ```C++ []\nclass Solution {\npublic:\n int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n vector<int>rowMax;\n vector<int>colMax;\n int maxi = -1;\n for(int i = 0; i<grid.size(); i++){\n maxi = -1;\n for(int j = 0; j < grid.size(); j++){\n maxi = max(maxi, grid[i][j]);\n }\n rowMax.push_back(maxi);\n }\n for(int i = 0; i<grid.size(); i++){\n maxi = -1;\n for(int j = 0; j < grid.size(); j++){\n\n maxi = max(maxi, grid[j][i]);\n }\n colMax.push_back(maxi);\n }\n long long int sum = 0;\n for(int i = 0; i < grid.size(); i++){\n for(int j = 0; j < grid.size(); j++){\n if(grid[i][j] >= rowMax[i] && grid[i][j] >= colMax[j]){\n continue;\n }\n else{\n if(rowMax[i] < colMax[j]){\n sum += abs(grid[i][j]-rowMax[i]);\n }\n else\n sum += abs(grid[i][j]-colMax[j]);\n }\n }\n }\n return sum;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int:\n \n N = len(grid)\n M = len(grid[0])\n \n grid_t = zip(*grid)\n \n sk_v = [max(row) for row in grid]\n sk_h = [max(row) for row in grid_t]\n \n res = 0\n for i in range(N):\n for j in range(M):\n diff = min(sk_h[j], sk_v[i]) - grid[i][j]\n res += diff\n return res\n```\n\n```Java []\nclass Solution {\n public int rowFun(int r, int[][] grid){\n int max=grid[r][0];\n for(int i=1;i<grid.length;i++){\n max=Math.max(max, grid[r][i]);\n }\n return max;\n }\n public int colFun(int c, int[][] grid){\n int max=grid[0][c];\n for(int i=1;i<grid.length;i++){\n max=Math.max(max, grid[i][c]);\n }\n return max;\n }\n public int maxIncreaseKeepingSkyline(int[][] grid) {\n int ans=0;\n int[][] max=new int[grid.length][grid[0].length];\n for(int i=0;i<grid[0].length;i++){\n max[i][0]=rowFun(i, grid);\n max[i][1]=colFun(i, grid);\n }\n for(int i=0;i<grid.length;i++){\n for(int j=0;j<grid[0].length;j++){\n ans+=( Math.min(max[i][0], max[j][1]) - grid[i][j] );\n }\n }\n return ans;\n }\n}\n```\n | 1 | 0 | ['C++', 'Java', 'Python3'] | 2 |
max-increase-to-keep-city-skyline | simple and clear c++ soulution for beginners | simple-and-clear-c-soulution-for-beginne-1h7g | \n# Code\n\nclass Solution {\npublic:\n int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n vector<int> west(grid.size(),0);\n vector< | 7_aditi | NORMAL | 2023-03-15T21:27:31.946813+00:00 | 2023-04-01T08:25:16.929116+00:00 | 16 | false | \n# Code\n```\nclass Solution {\npublic:\n int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n vector<int> west(grid.size(),0);\n vector<int> south(grid[0].size(),0);\n int k=0;\n for(int i=0;i<grid.size();i++)\n {\n int max=0;\n for(int j=0;j<grid[0].size();j++)\n {\n if(max<grid[i][j])\n max=grid[i][j];\n }\n west[k]=max;\n k++;\n }\n for(int i=0;i<grid.size();i++)\n {\n for(int j=0;j<grid[0].size();j++)\n {\n if(south[j]<grid[i][j])\n south[j]=grid[i][j];\n }\n }\n int cost=0;\n for(int i=0;i<grid.size();i++)\n {\n for(int j=0;j<grid[0].size();j++)\n {\n int min_ch=min(west[i],south[j]);\n if(min_ch>grid[i][j])\n {\n cost+=(min_ch-grid[i][j]);\n }\n }\n }\n return cost;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
max-increase-to-keep-city-skyline | substract every element from min(that row max , that col max) | substract-every-element-from-minthat-row-5239 | \nclass Solution {\npublic:\n int maxIncreaseKeepingSkyline(vector<vector<int>>& g) {\n \n int n = g.size();\n int m = g[0].size();\n | mr_stark | NORMAL | 2023-02-26T09:25:53.745673+00:00 | 2023-02-26T09:25:53.745716+00:00 | 565 | false | ```\nclass Solution {\npublic:\n int maxIncreaseKeepingSkyline(vector<vector<int>>& g) {\n \n int n = g.size();\n int m = g[0].size();\n \n \n vector<int> c(n);\n vector<int> r(m);\n \n \n for(int i = 0;i<n;i++)\n {\n int mx = INT_MIN;\n for(int j =0;j<m;j++)\n {\n mx = max(mx,g[j][i]);\n }\n \n c[i] = mx;\n \n }\n \n int o=0;\n for(auto i:g)\n {\n r[o++] = *max_element(i.begin(),i.end());\n }\n \n int res = 0;\n for(int i=0;i<n;i++)\n {\n for(int j=0;j<m;j++)\n {\n res+=min(r[i],c[j])-g[i][j];\n }\n }\n return res;\n }\n};\n``` | 1 | 0 | [] | 0 |
max-increase-to-keep-city-skyline | 807. Max Increase to Keep City Skyline | 807-max-increase-to-keep-city-skyline-by-19wp | Intuition\n Describe your first thoughts on how to solve this problem. \n- First Understand the views from different sides of the nn Matrix.\n- Observe carefull | soumyajit_2021 | NORMAL | 2023-02-22T17:05:53.912623+00:00 | 2023-02-22T18:38:17.292461+00:00 | 20 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- First Understand the views from different sides of the n*n Matrix.\n- Observe carefully that if a small height building placed in between two big height buildings then there is no worries we can increse the height of the small building up to the highest one in that Row and in that Column.\n- My approach is to find the highest building in a row and highest building in a column and I store them in two differnt arrays as I have to use them later on.\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Take Two Arrays of same size that is Grid length.\n- Iterate over the matrix and store for each row and each column which one is the highest building and store the respective building height into that rowIndex and columnIndex.\n- Now Iterate over the Matrix at every cell we check the minimum height of the buildings from that row and that column and if that minimum height is greater than the current cell height then we are good to increse so take the differece and add it to the result.\n- Now follow the same for all the cells.\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nIts $$O(n*n)$$ as we are traversing the Matrix. \n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nTechnically the space complexity is $$O(n)$$ for allocating space for those two extra Arrays\n\n# Code\n```\nclass Solution {\n public int maxIncreaseKeepingSkyline(int[][] grid) {\n \n int len = grid.length;\n int[] row = new int[len];\n int[] col = new int[len];\n int sum = 0 ;\n for(int i = 0; i < len ; i++){\n for(int j = 0 ; j < len ; j++){\n row[i] = Math.max(grid[i][j], row[i]);\n col[i] = Math.max(grid[j][i], col[i]);\n }\n }\n for(int i = 0; i < len ; i++){\n for(int j = 0 ; j < len ; j++){\n int req = Math.min(row[i],col[j]);\n if(req > grid[i][j]){\n sum += req - grid[i][j]; \n }\n }\n }\n return sum;\n }\n}\n``` | 1 | 0 | ['Array', 'Greedy', 'Matrix', 'Java'] | 0 |
max-increase-to-keep-city-skyline | [Accepted] Swift | accepted-swift-by-vasilisiniak-98wp | \nclass Solution {\n func maxIncreaseKeepingSkyline(_ grid: [[Int]]) -> Int {\n \n let h = grid.map { $0.max()! }\n let w = grid.indices | vasilisiniak | NORMAL | 2023-02-14T08:32:12.403064+00:00 | 2023-02-14T08:32:12.403125+00:00 | 15 | false | ```\nclass Solution {\n func maxIncreaseKeepingSkyline(_ grid: [[Int]]) -> Int {\n \n let h = grid.map { $0.max()! }\n let w = grid.indices.map { i in grid.map({ $0[i] }).max()! }\n \n return grid\n .indices\n .flatMap { i in grid[i].indices.map { [i, $0] } }\n .map { min(h[$0[0]], w[$0[1]]) - grid[$0[0]][$0[1]] }\n .reduce(0, +)\n }\n}\n``` | 1 | 0 | ['Swift'] | 1 |
max-increase-to-keep-city-skyline | JAVA || Simple Approach || Beats 100% | java-simple-approach-beats-100-by-prince-54n8 | Intuition\n Describe your first thoughts on how to solve this problem. \nFind the maximum height of the buildings for each building in their north and east dire | princeayush04 | NORMAL | 2023-02-06T22:06:55.567175+00:00 | 2023-02-06T22:06:55.567209+00:00 | 20 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFind the maximum height of the buildings for each building in their north and east direction, then take the minimum of these two values and subtract the value with the height of the current building and add the result to the ans.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWhile traversing through the grid in loop find the building with the maximum height in both directions and store it in an array and then traverse again and calculate how much building size we can increase.\n\n# Complexity\n- Time complexity: O(n^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n# Code\n```\nimport static java.lang.Math.*;\nclass Solution {\n public int maxIncreaseKeepingSkyline(int[][] grid) {\n int n = grid.length;\n int[] north = new int[n];\n int[] east = new int[n];\n for(int i = 0; i<n; i++){\n int maxi = 0, maxj = 0;\n for(int j = 0; j<n; j++){\n maxi = max(maxi, grid[i][j]);\n maxj = max(maxj, grid[j][i]);\n }\n north[i] = maxi;\n //distance of the building with max height in \n //north direction\n east[i] = maxj;\n //distance of the building with max height in \n //east direction\n }\n int ans = 0;\n for(int i = 0; i<n; i++){\n for(int j = 0; j<n; j++){\n ans += min(north[i], east[j]) - grid[i][j];\n //Taking the minumum of the buildings with maximum\n //height in north and east direction and subtraction \n //it to our current building height and adding the \n //result in our ans.\n }\n }\n return ans;\n }\n}\n``` | 1 | 0 | ['Java'] | 1 |
max-increase-to-keep-city-skyline | C++ Solution #simpleapproach O(2*n^2) | c-solution-simpleapproach-o2n2-by-andy18-nw6f | 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 | andy1810 | NORMAL | 2023-01-26T17:18:41.269098+00:00 | 2023-01-26T17:18:41.269141+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 O(2*n^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n int sum=0;\n vector<int> row,col;\n for(int i=0;i<grid.size();i++)\n {\n int x=0,y=0;\n for(int j=0;j<grid.size();j++)\n {\n x=max(x,grid[i][j]);\n y=max(y,grid[j][i]);\n }\n row.push_back(x);\n col.push_back(y);\n }\n for(int i=0;i<grid.size();i++)\n {\n for(int j=0;j<grid.size();j++)\n {\n sum+=(min(row[i],col[j]) - grid[i][j]);\n }\n }\n return sum;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
max-increase-to-keep-city-skyline | [ JavaScript ] Best Solution | Faster than 97% | javascript-best-solution-faster-than-97-mjy9g | Code\n\n/**\n * @param {number[][]} grid\n * @return {number}\n */\nvar maxIncreaseKeepingSkyline = function(grid) {\n let dupGrid = transposeMatrix(grid);\n | tajnur | NORMAL | 2022-12-31T20:35:22.066763+00:00 | 2022-12-31T20:35:22.066793+00:00 | 425 | false | # Code\n```\n/**\n * @param {number[][]} grid\n * @return {number}\n */\nvar maxIncreaseKeepingSkyline = function(grid) {\n let dupGrid = transposeMatrix(grid);\n let colMax = [];\n let ans = 0;\n \n dupGrid.forEach(row => {\n colMax.push(Math.max(...row));\n });\n\n grid.forEach((row, i) => {\n let rowMax = Math.max(...row);\n row.forEach((num, j) => {\n ans += Math.min(rowMax, colMax[j]) - num;\n });\n });\n\n return ans;\n};\n\nfunction transposeMatrix(grid) {\n let dupGrid = JSON.parse(JSON.stringify(grid));\n\n grid.forEach((row, i) => {\n row.forEach((num, j) => {\n dupGrid[j][i] = num;\n });\n });\n\n return dupGrid;\n}\n``` | 1 | 0 | ['JavaScript'] | 0 |
max-increase-to-keep-city-skyline | [Beats 94.75%] Easy, straightforward, beginner solution :) | beats-9475-easy-straightforward-beginner-wkxt | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nh_max is the maximum value for each horizontal column\nv_max is the maxim | TwilightXD | NORMAL | 2022-12-30T15:57:33.613850+00:00 | 2023-01-10T14:59:32.992960+00:00 | 57 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nh_max is the maximum value for each horizontal column\nv_max is the maximum value for each vertical column \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 maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int:\n n = len(grid)\n h_max = [max(i) for i in grid]\n v_max = []\n for j in range(n):\n a = [max(x[j] for x in grid)]\n v_max += a\n\n"Alternatively, you can use \nv_max = [max([grid[i][j] for i in range(n)]) for j in range(n)]"\n\n count = 0\n for row in range(n):\n for col in range(n):\n bound = min(h_max[row], v_max[col])\n count += bound - grid[row][col]\n return count\n\n\n\n\n``` | 1 | 0 | ['Array', 'Greedy', 'Matrix', 'Python3'] | 0 |
max-increase-to-keep-city-skyline | Fastest solution || 0ms Runtime || 100% run speed || JAVA | fastest-solution-0ms-runtime-100-run-spe-bwwd | 133/133 cases passed (0 ms)\n- Your runtime beats 100 % of java submissions\n- Your memory usage beats 83.04 % of java submissions (42.3 MB)\n# Code\n\nclass So | PAPPURAJ | NORMAL | 2022-12-07T09:03:40.263553+00:00 | 2022-12-07T09:03:40.263591+00:00 | 174 | false | - 133/133 cases passed (0 ms)\n- Your runtime beats 100 % of java submissions\n- Your memory usage beats 83.04 % of java submissions (42.3 MB)\n# Code\n```\nclass Solution {\n public int maxIncreaseKeepingSkyline(int[][] grid) {\n int m=grid.length,n=grid[0].length;\n int[] r=new int[m];\n int[] c=new int[n];\n int out=0;\n\n \n for(int i=0;i<m;i++){\n for(int j=0;j<n;j++){\n r[i]=Math.max(r[i], grid[i][j]);\n c[j]=Math.max(c[j], grid[i][j]);\n }\n }\n\n \n for(int i=0;i<m;i++){\n for(int j=0;j<n;j++){\n out+=Math.min(r[i], c[j])-grid[i][j];\n }\n }\n return out;\n \n \n }\n}\n``` | 1 | 0 | ['Java'] | 1 |
max-increase-to-keep-city-skyline | CPP SOLUTION || EASY TO UNDERSTAND || SIMPLE AND CLEAN CODE | cpp-solution-easy-to-understand-simple-a-7lib | 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 | Abhishek777888 | NORMAL | 2022-12-07T04:36:11.521660+00:00 | 2022-12-07T04:37:06.006732+00:00 | 976 | 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)$$ -->\n0(N^2)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n\n vector<int>maxRow;\n vector<int>maxCol;\n int maxi=0;\n int ans=0;\n\n for(int i=0;i<grid.size();i++) {\n for(int j=0;j<grid[0].size();j++) {\n maxi=max(maxi,grid[i][j]); }\n maxRow.push_back(maxi);\n maxi=0;\n } \n\n for(int j=0;j<grid.size();j++) {\n for(int i=0;i<grid[0].size();i++){\n maxi=max(maxi,grid[i][j]);}\n maxCol.push_back(maxi);\n maxi=0;\n } \n\n for(int i=0;i<grid.size();i++) {\n for(int j=0;j<grid[0].size();j++) {\n int x=min(maxRow[i],maxCol[j]);\n if(x==grid[i][j])continue;\n ans+=(x-grid[i][j]); }\n }\n \n return ans;\n }\n}; | 1 | 0 | ['C++'] | 1 |
max-increase-to-keep-city-skyline | Very Easy iterative approach || C++ | very-easy-iterative-approach-c-by-sudhan-n3qr | 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 | sudhanwaofficial | NORMAL | 2022-12-06T06:26:55.565737+00:00 | 2022-12-06T06:26:55.565781+00:00 | 229 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n vector<int> row,col;\n // For finding max in row and col\n for(int i=0;i<grid.size();i++){\n int row_max=-1;\n int col_max=-1;\n for(int j=0;j<grid[i].size();j++){\n if(grid[i][j]>row_max) row_max=grid[i][j];\n\n if(grid[j][i]>col_max) col_max=grid[j][i];\n }\n row.push_back(row_max);\n col.push_back(col_max);\n }\n\n int ans=0;\n <!-- finding the sum of the increasable heights -->\n for(int i=0;i<grid.size();i++){\n for(int j=0;j<grid[i].size();j++){\n ans+=min(row[i],col[j])-grid[i][j];\n }\n \n }\n \n return ans;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
max-increase-to-keep-city-skyline | 100% faster java solution | 100-faster-java-solution-by-sai064-u7zq | Intuition\nTook some time to understand the question. Looked at the example testcase. pictured the matrix as in real life scenario and understood the concept. \ | sai064 | NORMAL | 2022-12-04T08:44:39.537120+00:00 | 2022-12-04T08:44:39.537164+00:00 | 410 | false | # Intuition\nTook some time to understand the question. Looked at the example testcase. pictured the matrix as in real life scenario and understood the concept. \nWe just need to increase the heights of the smaller building from each cardinal direction such that it doesn\'t effect the height view.\n\n# Approach\nWe need to make sure the cardinal direction view doesn\'t change, so we have to keep a record of views of east heights, north heights, west heights, south heights.\nwell east and west view of heights will be same as they are opposite to each other. and same as for north and south.\n\nso record the **rows(i.e, north and south)** in maxOfRows [].\nrecord the **columns(i.e, east and west)** in maxOfColumns [].\n\nkeep a counter to record the increase of each building. count = 0;\n\nA building can only be increased to the highest of **minimum of (row,column)**.\nMath.min(maxOfColumns[i],maxOfRows[j])\n\nwe need to subtract already existing height.\nSo, count+=Math.min(maxOfColumns[i],maxOfRows[j])-grid[i][j];\n\n\n# Complexity\n- Time complexity:\n$$O(n^2)$$ - for maxOfRows[]\n$$O(n^2)$$ - for maxOfColumns[]\n$$O(n^2)$$ - to calculate the count\nTime Complexity = $$O(n^2)$$\n\n- Space complexity:\n$$O(n)$$- for maxOfRows[]\n$$O(n)$$- for maxOfColumns[]\nSpace Complexity = $$O(n)$$\n\n# Code\n```\nclass Solution {\n public int maxIncreaseKeepingSkyline(int[][] grid) {\n int count = 0;\n int n = grid.length;\n int maxOfRows[] = new int[n];\n int maxOfColumns[] = new int[n];\n\n for(int i=0;i<n;i++){\n int max = 0;\n for(int j=0;j<n;j++){\n if(max<grid[i][j]){\n max=grid[i][j];\n }\n }\n maxOfRows[i]=max;\n }\n\n for(int j=0;j<n;j++){\n int max = 0;\n for(int i=0;i<n;i++){\n if(max<grid[i][j]){\n max=grid[i][j];\n }\n }\n maxOfColumns[j]=max;\n }\n\n for(int i=0;i<n;i++){\n for(int j=0;j<n;j++){\n count+=Math.min(maxOfColumns[i],maxOfRows[j])-grid[i][j];\n }\n }\n return count;\n \n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
max-increase-to-keep-city-skyline | Explained O(n * n) time and O(n) space solution in Rust and Java. | explained-on-n-time-and-on-space-solutio-4mgy | The secret here is to iterate through the array:\n1. Suppose we are at a position (i, j)\n2. You must know for this position, the height of the tallest box in i | nisaacdz | NORMAL | 2022-10-19T09:29:26.715610+00:00 | 2022-10-19T09:29:26.715687+00:00 | 95 | false | The secret here is to iterate through the array:\n1. Suppose we are at a position (i, j)\n2. You must know for this position, the height of the tallest box in its column, i, as well as in its row, j.\n3. After you find the tallest in both directions, note the minimum of the two values, c.\n4. The max increment you may give to position (i, j) would be so that it would equal c. More specifically, the max_increment for the box at (i, j) would be ``max(0, c - grid(i, j))``\n5. Repeat the procedure for all elements in grid and add the results together.\n\n6. In this solution I first found the maximum for each column and row in O(n ^ 2) time and stored them in ``max_vec``\n7. During the iteration of each element in grid, there would be no need to look \n\nJava Solution\n```\nclass Solution {\n public int maxIncreaseKeepingSkyline(int[][] grid) {\n int n = grid.length, ans = 0;\n \n int[][] max = new int[2][n];\n \n for(int x = 0; x < n; x++){\n for(int y = 0; y < n; y++){\n max[0][x] = Math.max(max[0][x], grid[x][y]);\n max[1][x] = Math.max(max[1][x], grid[y][x]);\n }\n }\n \n for(int i = 0; i < n; i++){\n for(int j = 0; j < n; j++){\n ans += Math.max(0, Math.min(max[0][i], max[1][j]) - grid[i][j]);\n }\n }\n \n return ans;\n }\n}\n```\n\nRust Solution\n```\nimpl Solution {\n pub fn max_increase_keeping_skyline(grid: Vec<Vec<i32>>) -> i32 {\n let n: usize = grid.len();\n let mut max_vec: Vec<Vec<i32>> = vec![vec![0; n]; 2];\n \n for x in 0..n{\n for y in 0..n{\n max_vec[0][x] = max_vec[0][x].max(grid[x][y]);\n max_vec[1][x] = max_vec[1][x].max(grid[y][x]);\n }\n }\n \n println!("{:?}", max_vec);\n \n let mut ans: i32 = 0;\n let mut val: i32 = 0;\n \n for i in 0..n{\n for j in 0..n{\n val = max_vec[0][i].min(max_vec[1][j]) - grid[i][j];\n \n if val > 0{\n ans += val;\n }\n }\n }\n \n ans\n }\n}\n``` | 1 | 0 | ['Java', 'Rust'] | 0 |
max-increase-to-keep-city-skyline | 90% FASTER || O(m+n) SPACE || TIME (m*n) || C++ | 90-faster-omn-space-time-mn-c-by-abhay_1-tnzm | \nclass Solution {\npublic:\n int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n int n = grid.size(),i,j;\n vector<int> col(n,INT_MIN | abhay_12345 | NORMAL | 2022-09-25T09:58:03.723468+00:00 | 2022-09-25T09:58:03.723510+00:00 | 390 | false | ```\nclass Solution {\npublic:\n int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n int n = grid.size(),i,j;\n vector<int> col(n,INT_MIN),row(n,INT_MIN);\n for(i = 0; i < n; i++){\n for(j = 0; j < n; j++){\n row[i] = max(row[i],grid[i][j]);\n col[j] = max(col[j],grid[i][j]);\n }\n }\n \n int ans = 0;\n for(i = 0; i < n; i++){\n for(j = 0; j < n; j++){\n ans += min(row[i],col[j])-grid[i][j];\n }\n }\n return ans;\n }\n};\n``` | 1 | 0 | ['Greedy', 'C', 'Matrix', 'C++'] | 0 |
max-increase-to-keep-city-skyline | ✅C++ Solution | Easy 2 loop approach | c-solution-easy-2-loop-approach-by-devan-gnqm | \nclass Solution {\npublic:\n int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n vector<int> max_r,max_c;\n for(int i=0;i<grid.size() | Devanshul | NORMAL | 2022-09-10T17:46:27.385398+00:00 | 2022-09-10T17:46:27.385441+00:00 | 261 | false | ```\nclass Solution {\npublic:\n int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n vector<int> max_r,max_c;\n for(int i=0;i<grid.size();i++){\n int m_r=INT_MIN,m_c=INT_MIN;\n for(int j=0;j<grid.size();j++){ \n m_r=max(m_r,grid[i][j]);\n m_c=max(m_c,grid[j][i]);\n }\n max_r.push_back(m_r);\n max_c.push_back(m_c); \n }\n int ans=0;\n for(int i=0;i<grid.size();i++){\n for(int j=0;j<grid.size();j++){ \n if(grid[i][j]<min(max_r[i],max_c[j])){\n ans += min(max_r[i],max_c[j])-grid[i][j];\n }\n } \n } \n return ans;\n }\n};\n``` | 1 | 0 | ['C', 'C++'] | 0 |
max-increase-to-keep-city-skyline | Simplest C++ solution | simplest-c-solution-by-akriart-i76f | Just find the minimum of the maximum of each row and column and the problem is solved\n\nclass Solution {\npublic:\n int maxIncreaseKeepingSkyline(vector<vec | akriart | NORMAL | 2022-09-07T13:11:15.384087+00:00 | 2022-09-07T13:13:09.055422+00:00 | 154 | false | Just find the minimum of the maximum of each row and column and the problem is solved\n```\nclass Solution {\npublic:\n int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n vector<vector<int>>ans(grid.size(),vector<int>(grid[0].size(),0));\n vector<int>rowmax(grid.size(),0);\n vector<int>colmax(grid.size(),0);\n int res=0;\n for(int i=0;i<grid.size();i++){\n for(int j=0;j<grid[0].size();j++){\n rowmax[i]=max(rowmax[i],grid[i][j]);\n colmax[i]=max(colmax[i],grid[j][i]);\n }\n }\n for(int i=0;i<grid.size();i++){\n for(int j=0;j<grid[0].size();j++){\n ans[i][j]=min(rowmax[i],colmax[j]);\n res+=ans[i][j]-grid[i][j];\n }\n }\n return res;\n }\n};\n``` | 1 | 0 | ['C'] | 0 |
max-increase-to-keep-city-skyline | Rust Solution (slice bad practice!) | rust-solution-slice-bad-practice-by-morr-9eul | rust\n\nimpl Solution {\n pub fn max_increase_keeping_skyline(grid: Vec<Vec<i32>>) -> i32 {\n let mut res = 0;\n let (mut xaxis, mut yaxis) = ( | morris_tai | NORMAL | 2022-09-07T04:59:15.382378+00:00 | 2022-09-07T05:09:49.889900+00:00 | 72 | false | ```rust\n\nimpl Solution {\n pub fn max_increase_keeping_skyline(grid: Vec<Vec<i32>>) -> i32 {\n let mut res = 0;\n let (mut xaxis, mut yaxis) = (vec![], vec![]);\n let length = grid.len();\n \n for x in 0..length {\n for y in 0..grid.len() {\n xaxis.push(grid[x][y]); // concat every row\n yaxis.push(grid[y][x]); // concat every columns\n }\n }\n\t\t\n for x in 0..length {\n for y in 0..length {\n let ix: usize = x*length;\n let iy: usize = y*length;\n\t\t\t\t// find the smaller from row\'s and column\'s max\n let skyline = *[*&xaxis[ix..ix+length].iter().max().unwrap(),\\\n\t\t\t\t *&yaxis[iy..iy+length].iter().max().unwrap()].iter().min().unwrap();\n\t\t\t\t// subtract intersection with skyline\n let sub = skyline - &xaxis[ix..ix+length][y];\n if sub > 0 {\n res += sub;\n }\n }\n }\n \n return res\n }\n}\n``` | 1 | 0 | [] | 0 |
max-increase-to-keep-city-skyline | C++ Easy to understand Solution | c-easy-to-understand-solution-by-sumanta-ss51 | \nclass Solution {\npublic:\n int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n vector<int> row; // to store max of each row \n vect | SumantaJena | NORMAL | 2022-08-31T07:06:54.243434+00:00 | 2022-08-31T07:06:54.243478+00:00 | 185 | false | ```\nclass Solution {\npublic:\n int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n vector<int> row; // to store max of each row \n vector<int> col; // to store max of each col\n int n=grid.size();\n int sum=0;\n // to find the max of each row \n for(int i=0;i<n;i++){\n int m = *max_element(grid[i].begin(),grid[i].end());\n row.push_back(m);\n }\n // to find the max of each column\n for(int i=0;i<n;i++){\n vector<int> temp;\n for(int j=0;j<n;j++){\n temp.push_back(grid[j][i]);\n }\n int mi = *max_element(temp.begin(),temp.end());\n col.push_back(mi);\n }\n for(int i=0;i<n;i++){\n for(int j=0;j<n;j++){\n int temp_sum= min(row[i],col[j])-grid[i][j];\n sum+=temp_sum;\n }\n }\n return sum;\n }\n};\n```\n\n\n | 1 | 0 | ['C'] | 1 |
print-in-order | 5 Python threading solutions (Barrier, Lock, Event, Semaphore, Condition) with explanation | 5-python-threading-solutions-barrier-loc-80yi | \nRaise two barriers. Both wait for two threads to reach them.\n\nFirst thread can print before reaching the first barrier. Second thread can print before reach | mereck | NORMAL | 2019-07-15T19:21:27.141612+00:00 | 2019-08-26T13:47:48.615055+00:00 | 37,035 | false | \nRaise two barriers. Both wait for two threads to reach them.\n\nFirst thread can print before reaching the first barrier. Second thread can print before reaching the second barrier. Third thread can print after the second barrier.\n\n```\nfrom threading import Barrier\n\nclass Foo:\n def __init__(self):\n self.first_barrier = Barrier(2)\n self.second_barrier = Barrier(2)\n \n def first(self, printFirst):\n printFirst()\n self.first_barrier.wait()\n \n def second(self, printSecond):\n self.first_barrier.wait()\n printSecond()\n self.second_barrier.wait()\n \n def third(self, printThird):\n self.second_barrier.wait()\n printThird()\n ```\n \nStart with two locked locks. First thread unlocks the first lock that the second thread is waiting on. Second thread unlocks the second lock that the third thread is waiting on.\n\n```\nfrom threading import Lock\n\nclass Foo:\n def __init__(self):\n self.locks = (Lock(),Lock())\n self.locks[0].acquire()\n self.locks[1].acquire()\n \n def first(self, printFirst):\n printFirst()\n self.locks[0].release()\n \n def second(self, printSecond):\n with self.locks[0]:\n printSecond()\n self.locks[1].release()\n \n \n def third(self, printThird):\n with self.locks[1]:\n printThird()\n``` \nSet events from first and second threads when they are done. Have the second thread wait for first one to set its event. Have the third thread wait on the second thread to raise its event.\n\n```\nfrom threading import Event\n\nclass Foo:\n def __init__(self):\n self.done = (Event(),Event())\n \n def first(self, printFirst):\n printFirst()\n self.done[0].set()\n \n def second(self, printSecond):\n self.done[0].wait()\n printSecond()\n self.done[1].set()\n \n def third(self, printThird):\n self.done[1].wait()\n printThird()\n\n``` \nStart with two closed gates represented by 0-value semaphores. Second and third thread are waiting behind these gates. When the first thread prints, it opens the gate for the second thread. When the second thread prints, it opens the gate for the third thread.\n\n```\nfrom threading import Semaphore\n\nclass Foo:\n def __init__(self):\n self.gates = (Semaphore(0),Semaphore(0))\n \n def first(self, printFirst):\n printFirst()\n self.gates[0].release()\n \n def second(self, printSecond):\n with self.gates[0]:\n printSecond()\n self.gates[1].release()\n \n def third(self, printThird):\n with self.gates[1]:\n printThird()\n\n ``` \n\nHave all three threads attempt to acquire an RLock via Condition. The first thread can always acquire a lock, while the other two have to wait for the `order` to be set to the right value. First thread sets the order after printing which signals for the second thread to run. Second thread does the same for the third.\n\n```\nfrom threading import Condition\n\nclass Foo:\n def __init__(self):\n self.exec_condition = Condition()\n self.order = 0\n self.first_finish = lambda: self.order == 1\n self.second_finish = lambda: self.order == 2\n\n def first(self, printFirst):\n with self.exec_condition:\n printFirst()\n self.order = 1\n self.exec_condition.notify(2)\n\n def second(self, printSecond):\n with self.exec_condition:\n self.exec_condition.wait_for(self.first_finish)\n printSecond()\n self.order = 2\n self.exec_condition.notify()\n\n def third(self, printThird):\n with self.exec_condition:\n self.exec_condition.wait_for(self.second_finish)\n printThird()\n```\n \n | 749 | 0 | [] | 27 |
print-in-order | [Java] Basic semaphore solution - 8ms, 36MB | java-basic-semaphore-solution-8ms-36mb-b-o4xr | "Semaphore is a bowl of marbles" - Professor Stark\n\n1. Semaphore is a bowl of marbles (or locks in this case). If you need a marble, and there are none, you w | lk00100100 | NORMAL | 2019-07-12T01:19:55.329400+00:00 | 2022-05-15T17:51:46.332889+00:00 | 34,032 | false | "Semaphore is a bowl of marbles" - Professor Stark\n\n1. Semaphore is a bowl of marbles (or locks in this case). If you need a marble, and there are none, you wait. You wait until there is one marble and then you take it. If you release(), you will add one marble to the bowl (from thin air). If you release(100), you will add 100 marbles to the bowl. **run2.release();** will add one **"run2"** marble to the **"run2 bowl"**.\n2. The thread calling **third()** will wait until the end of **second()** when it releases a **\'run3\'** marble. The **second()** will wait until the end of **first() **when it releases a **\'run2\'** marble. Since **first()** never acquires anything, it will never wait. There is a forced wait ordering.\n3. With semaphores, you can start out with 1 marble or 0 marbles or 100 marbles. A thread can take marbles (up until it\'s empty) or put many marbles at a time.\n\nYou can solve this using other solutions (check bottom), but if you wake up a thread and make it spin in a loop and wait for some condition, it is a waste of CPU. You can make the thread go to sleep and wait for someone to notify it to wake up.\n\nUpvote and check out my other concurrency solutions.\n```\nimport java.util.concurrent.*;\nclass Foo {\n Semaphore run2, run3;\n\n public Foo() {\n run2 = new Semaphore(0);\n run3 = new Semaphore(0);\n }\n\n public void first(Runnable printFirst) throws InterruptedException {\n printFirst.run();\n run2.release();\n }\n\n public void second(Runnable printSecond) throws InterruptedException {\n run2.acquire();\n printSecond.run();\n run3.release();\n }\n\n public void third(Runnable printThird) throws InterruptedException {\n run3.acquire(); \n printThird.run();\n }\n}\n```\n\n---\n\nSide note:\n**ruzveld83** has pointed something out.\n"According to JMM there\'s no guarantee that a thread will see values assigned during construction of an object in another thread. There is no guarantee that some thread can\'t see version of Foo that is not fully constructed. It\'s possible to see Foo.run2 or Foo.run3 as nulls. And thread-safety of Semaphore class does not make any difference. The final keyword should fix this. See https://docs.oracle.com/javase/specs/jls/se8/html/jls-17.html#jls-17.5"\n\nI could argue that *maybe* Foo is being synchronized to allow for proper value visibility. But we can\'t see the entire program so... \xAF\\\\_(\u30C4)_/\xAF\n\n---\n\nHere\'s another solution that requires 1 semaphore. It is 19ms. There is some "waking and waiting" due to the loops, so that causes some CPU waste. I should also note that we need **tryAcquire(number)** because it will try to get "all or nothing." So if you **tryAcquire(3)**, it will try to "get all 3 if all present and return true" or "grab nothing and return false." If you use **acquire(3)**, if there isn\'t enough, it will grab 1 or 2 and then wait for the remainder. You may expect it to "get 3 or wait for 3" but it doesn\'t do this and you may be in for a surprise.\n```\nclass Foo {\n\n Semaphore semaphore1;\n public Foo() {\n semaphore1 = new Semaphore(0);\n }\n\n public void first(Runnable printFirst) throws InterruptedException {\n printFirst.run();\n semaphore1.release();\n }\n\n public void second(Runnable printSecond) throws InterruptedException {\n while(!semaphore1.tryAcquire(1));\n \n printSecond.run();\n semaphore1.release(2);\n }\n\n public void third(Runnable printThird) throws InterruptedException {\n while(!semaphore1.tryAcquire(2));\n \n printThird.run();\n }\n}\n```\n---\nFor new learners, you can also solve this using:\n- **volatile** keyword.\n- locks\n- conditions (they are like sub-locks)\n- atomic variables\n- java\'s concurrent data structures\n\nUse what works and is simple. | 348 | 1 | [] | 32 |
print-in-order | Java - Synchronized/Lock/Semaphore/Condition Variable | java-synchronizedlocksemaphorecondition-3vcqk | Synchronized Method:\n\nclass Foo {\n private boolean oneDone;\n private boolean twoDone;\n \n public Foo() {\n oneDone = false;\n two | woshilxd912 | NORMAL | 2020-10-14T06:36:10.374868+00:00 | 2020-10-14T18:50:14.552638+00:00 | 17,736 | false | Synchronized Method:\n```\nclass Foo {\n private boolean oneDone;\n private boolean twoDone;\n \n public Foo() {\n oneDone = false;\n twoDone = false;\n }\n\n public synchronized void first(Runnable printFirst) throws InterruptedException {\n printFirst.run();\n oneDone = true;\n notifyAll();\n }\n\n public synchronized void second(Runnable printSecond) throws InterruptedException {\n while (!oneDone) {\n wait();\n }\n printSecond.run();\n twoDone = true;\n notifyAll();\n }\n\n public synchronized void third(Runnable printThird) throws InterruptedException {\n while (!twoDone) {\n wait();\n }\n printThird.run();\n }\n}\n```\n\nSynchronized on Object:\n```\nclass Foo {\n private Object lock;\n private boolean oneDone;\n private boolean twoDone;\n \n public Foo() {\n lock = new Object();\n oneDone = false;\n twoDone = false;\n }\n\n public void first(Runnable printFirst) throws InterruptedException {\n synchronized (lock) {\n printFirst.run();\n oneDone = true;\n lock.notifyAll();\n }\n }\n\n public void second(Runnable printSecond) throws InterruptedException {\n synchronized (lock) {\n while (!oneDone) {\n lock.wait();\n }\n printSecond.run();\n twoDone = true;\n lock.notifyAll();\n }\n }\n\n public void third(Runnable printThird) throws InterruptedException {\n synchronized (lock) {\n while (!twoDone) {\n lock.wait();\n }\n printThird.run();\n }\n }\n}\n```\nSynchronized on Two Objects (not needed for this question, just put it here in case someone wants to use one object to protect one variable):\n```\nclass Foo {\n private Object lock1;\n private Object lock2;\n private boolean oneDone;\n private boolean twoDone;\n \n public Foo() {\n lock1 = new Object();\n lock2 = new Object();\n oneDone = false;\n twoDone = false;\n }\n\n public void first(Runnable printFirst) throws InterruptedException {\n synchronized (lock1) {\n printFirst.run();\n oneDone = true;\n lock1.notifyAll();\n }\n }\n\n public void second(Runnable printSecond) throws InterruptedException {\n synchronized (lock1) {\n synchronized (lock2) {\n while (!oneDone) {\n lock1.wait();\n }\n printSecond.run();\n twoDone = true;\n lock2.notifyAll();\n }\n }\n }\n\n public void third(Runnable printThird) throws InterruptedException {\n synchronized (lock2) {\n while (!twoDone) {\n lock2.wait();\n }\n printThird.run();\n }\n }\n}\n```\nSemaphore:\n```\nclass Foo {\n private Semaphore s2;\n private Semaphore s3;\n \n public Foo() {\n s2 = new Semaphore(0);\n s3 = new Semaphore(0);\n }\n\n public void first(Runnable printFirst) throws InterruptedException {\n printFirst.run();\n s2.release();\n }\n\n public void second(Runnable printSecond) throws InterruptedException {\n s2.acquire();\n printSecond.run();\n s3.release();\n }\n\n public void third(Runnable printThird) throws InterruptedException {\n s3.acquire();\n printThird.run();\n }\n}\n```\nCondition Variable:\n```\nclass Foo {\n private Lock lock;\n private boolean oneDone;\n private boolean twoDone;\n private Condition one;\n private Condition two;\n \n public Foo() {\n lock = new ReentrantLock();\n one = lock.newCondition();\n two = lock.newCondition();\n oneDone = false;\n twoDone = false;\n }\n\n public void first(Runnable printFirst) throws InterruptedException {\n lock.lock();\n try {\n printFirst.run();\n oneDone = true;\n one.signal();\n } finally {\n lock.unlock();\n }\n }\n\n public void second(Runnable printSecond) throws InterruptedException {\n lock.lock();\n try {\n while (!oneDone) {\n one.await();\n }\n printSecond.run();\n twoDone = true;\n two.signal();\n } finally {\n lock.unlock();\n }\n }\n\n public void third(Runnable printThird) throws InterruptedException {\n lock.lock();\n try {\n while (!twoDone) {\n two.await();\n }\n printThird.run();\n } finally {\n lock.unlock();\n }\n }\n}\n``` | 206 | 1 | ['Java'] | 17 |
print-in-order | [C++]Why most of the solutions using mutex are wrong+solution | cwhy-most-of-the-solutions-using-mutex-a-hvt6 | I actually started learning about threads recently only and even my first attempt was to take 2 mutex and lock/unlock them in order desired by us. That solution | dev1988 | NORMAL | 2019-07-25T14:23:39.718883+00:00 | 2019-07-25T14:23:39.718918+00:00 | 25,158 | false | I actually started learning about threads recently only and even my first attempt was to take 2 mutex and lock/unlock them in order desired by us. That solution is actually accepted in leetcode.\n\nHowever, while researching for difference between mutex and conditional_variable usage, i realised that the way mutex are being used here are totally wrong.\n\nSome points that must be taken note of are: \n* **Mutex** are used for **mutual exclusion** i.e to safe gaurd the critical sections of a code.\n* **Semaphone/condition_variable** are used for **thread synchronisation**(which is what we want to achieve here).\n* **Mutex have ownership assigned with them**, that is to say, *the thread that locks a mutex must only unlock it.* Also, we must not unlock a mutex that has not been locked **(This is what most programs have got wrong)**.\n* If the mutex is not used as said above, **the behavior is undefined**, which however in our case produces the required result.\n\nReferences:\n1. [If the mutex is not currently locked by the calling thread, it causes undefined behavior.](http://www.cplusplus.com/reference/mutex/mutex/unlock/)\n2. [The precondition for calling unlock is holding an ownership of the mutex, according to (std)30.4.1.2](https://stackoverflow.com/questions/43487357/how-stdmutex-got-unlocked-in-different-thread)\n\nI did read few more places the same thing, but i think these do put the point across :)\n\nNow my solution using a condition_variable:\n\n```\nclass Foo {\npublic:\n int count = 0;\n mutex mtx;\n condition_variable cv;\n Foo() {\n count = 1;\n //cv.notify_all();\n }\n\n void first(function<void()> printFirst) {\n \n unique_lock<mutex> lck(mtx);\n\t\t// No point of this wait as on start count will be 1, we need to make the other threads wait.\n // while(count != 1){\n // cv.wait(lck);\n // }\n // printFirst() outputs "first". Do not change or remove this line.\n\n printFirst();\n count = 2;\n cv.notify_all();\n }\n\n void second(function<void()> printSecond) {\n unique_lock<mutex> lck(mtx);\n while(count != 2){\n cv.wait(lck);\n }\n // printSecond() outputs "second". Do not change or remove this line.\n printSecond();\n count = 3;\n cv.notify_all();\n }\n\n void third(function<void()> printThird) {\n unique_lock<mutex> lck(mtx);\n while(count != 3){\n cv.wait(lck);\n }\n // printThird() outputs "third". Do not change or remove this line.\n printThird();\n }\n};\n```\n\n**Disclaimer**: I am still learning :P. So, please do enlighten me if you think my understanding of this topic is wrong/misleading.\nThanks for reading :) | 174 | 2 | ['C'] | 26 |
print-in-order | [C++] Using std::promise | c-using-stdpromise-by-mhelvens-bqgp | C++\nclass Foo {\nprivate:\n std::promise<void> p1;\n std::promise<void> p2;\n\npublic:\n void first(function<void()> printFirst) {\n printFirst();\n p | mhelvens | NORMAL | 2019-07-12T19:17:25.860223+00:00 | 2019-07-12T19:17:25.860279+00:00 | 7,250 | false | ```C++\nclass Foo {\nprivate:\n std::promise<void> p1;\n std::promise<void> p2;\n\npublic:\n void first(function<void()> printFirst) {\n printFirst();\n p1.set_value();\n }\n\n void second(function<void()> printSecond) {\n p1.get_future().wait();\n printSecond();\n p2.set_value();\n }\n\n void third(function<void()> printThird) {\n p2.get_future().wait();\n printThird();\n }\n};\n``` | 86 | 1 | ['C'] | 5 |
print-in-order | Python 3 - Semaphore | python-3-semaphore-by-awice-hzdq | \nfrom threading import Semaphore\n\nclass Foo:\n def __init__(self):\n self.two = Semaphore(0)\n self.three = Semaphore(0)\n\n def first(se | awice | NORMAL | 2019-07-12T20:57:44.266277+00:00 | 2019-07-12T20:57:44.267100+00:00 | 6,202 | false | ```\nfrom threading import Semaphore\n\nclass Foo:\n def __init__(self):\n self.two = Semaphore(0)\n self.three = Semaphore(0)\n\n def first(self, printFirst):\n printFirst()\n self.two.release()\n\n def second(self, printSecond):\n with self.two:\n printSecond()\n self.three.release()\n\n def third(self, printThird):\n with self.three:\n printThird()\n``` | 42 | 0 | [] | 2 |
print-in-order | Python 3 | 56ms | Lock vs Event | python-3-56ms-lock-vs-event-by-andnik-ptz8 | The fastest solution for the problem is to use Lock mechanism. See the following code with comments:\npython3\nimport threading\n\nclass Foo:\n def __init__( | andnik | NORMAL | 2019-09-30T22:35:34.693027+00:00 | 2019-09-30T22:35:34.693069+00:00 | 4,514 | false | The fastest solution for the problem is to use Lock mechanism. See the following code with comments:\n```python3\nimport threading\n\nclass Foo:\n def __init__(self):\n\t\t# create lock to control sequence between first and second functions\n self.lock1 = threading.Lock()\n\t\tself.lock1.acquire()\n\t\t\n\t\t# create another lock to control sequence between second and third functions\n self.lock2 = threading.Lock()\n self.lock2.acquire()\n\n def first(self, printFirst: \'Callable[[], None]\') -> None:\n printFirst()\n\t\t\n\t\t# since second function is waiting for the lock1, let\'s release it\n self.lock1.release()\n\n def second(self, printSecond: \'Callable[[], None]\') -> None:\n\t\t# wait for first funtion to finish\n self.lock1.acquire()\n \n\t\tprintSecond()\n\t\t\n\t\t# let\'s release lock2, so third function can run\n self.lock2.release()\n\n def third(self, printThird: \'Callable[[], None]\') -> None:\n\t\t# wait for second funtion to finish\n self.lock2.acquire()\n\t\t\n printThird()\n```\nNow, when I was solving the problem the result was showing only 76 ms, which is far from the fastest. If you encounter similar issue take into account that you are working with threading and the timing is very unpredictable when CPU decides to switch threads. This can cause different timing results.\n\nAs an alternative you can use other synchronization mechanisms, such as Semaphore or Event. If you peek into CPython code you will see both Event and Semaphore are using Lock inside. That means that technically Lock solution is the fastest.\n\nBut for the reference here is solution with Event synchronization. In my opinion it looks little better:\n\n```python3\nimport threading\n\nclass Foo:\n def __init__(self):\n self.event1 = threading.Event()\n self.event2 = threading.Event()\n\n def first(self, printFirst: \'Callable[[], None]\') -> None:\n printFirst()\n self.event1.set()\n\n def second(self, printSecond: \'Callable[[], None]\') -> None:\n self.event1.wait()\n printSecond()\n self.event2.set()\n\n def third(self, printThird: \'Callable[[], None]\') -> None:\n self.event2.wait()\n printThird()\n``` | 39 | 0 | ['Python', 'Python3'] | 5 |
print-in-order | Java solution beats 100% in both time and space | java-solution-beats-100-in-both-time-and-gye6 | \nclass Foo {\n \n private volatile boolean onePrinted;\n private volatile boolean twoPrinted;\n\n public Foo() {\n onePrinted = false;\n | tgaurav10 | NORMAL | 2019-07-12T17:07:20.976210+00:00 | 2019-07-12T17:08:38.865523+00:00 | 8,479 | false | ```\nclass Foo {\n \n private volatile boolean onePrinted;\n private volatile boolean twoPrinted;\n\n public Foo() {\n onePrinted = false;\n twoPrinted = false; \n }\n\n public synchronized void first(Runnable printFirst) throws InterruptedException {\n \n // printFirst.run() outputs "first". Do not change or remove this line.\n printFirst.run();\n onePrinted = true;\n notifyAll();\n }\n\n public synchronized void second(Runnable printSecond) throws InterruptedException {\n while(!onePrinted) {\n wait();\n }\n // printSecond.run() outputs "second". Do not change or remove this line.\n printSecond.run();\n twoPrinted = true;\n notifyAll();\n }\n\n public synchronized void third(Runnable printThird) throws InterruptedException {\n while(!twoPrinted) {\n wait();\n }\n // printThird.run() outputs "third". Do not change or remove this line.\n printThird.run();\n }\n}\n``` | 30 | 1 | [] | 11 |
print-in-order | [Java] Simple CountDownLatch solution | java-simple-countdownlatch-solution-by-m-4p93 | CountDownLatch seems a good fit for this, from java doc " A synchronization aid that allows one or more threads to wait until, a set of operations being perform | mavslee | NORMAL | 2019-07-24T04:08:53.452306+00:00 | 2019-07-24T04:08:53.452369+00:00 | 3,894 | false | CountDownLatch seems a good fit for this, from java doc " A synchronization aid that allows one or more threads to wait until, a set of operations being performed in other threads completes. "\n\n```\nimport java.util.concurrent.CountDownLatch;\n\nclass Foo {\n \n private final CountDownLatch l2;\n private final CountDownLatch l3;\n \n public Foo() {\n l2 = new CountDownLatch(1);\n l3 = new CountDownLatch(1);\n }\n\n public void first(Runnable printFirst) throws InterruptedException {\n printFirst.run();\n l2.countDown();\n }\n\n public void second(Runnable printSecond) throws InterruptedException {\n l2.await();\n printSecond.run();\n l3.countDown();\n }\n\n public void third(Runnable printThird) throws InterruptedException {\n l3.await();\n printThird.run();\n }\n}\n```\n\n | 27 | 0 | [] | 3 |
print-in-order | C++ 2 mutex | c-2-mutex-by-jysui-g2rw | Idea is grab and release locks in order.\n\nclass Foo { \n mutex m1, m2;\npublic:\n Foo() {\n m1.lock(), m2.lock();\n }\n\n void first(func | jysui | NORMAL | 2019-07-12T03:02:01.905469+00:00 | 2019-07-12T03:02:01.905504+00:00 | 6,261 | false | Idea is grab and release locks in order.\n```\nclass Foo { \n mutex m1, m2;\npublic:\n Foo() {\n m1.lock(), m2.lock();\n }\n\n void first(function<void()> printFirst) {\n // printFirst() outputs "first". Do not change or remove this line.\n printFirst();\n m1.unlock();\n }\n\n void second(function<void()> printSecond) {\n m1.lock();\n // printSecond() outputs "second". Do not change or remove this line.\n printSecond();\n m1.unlock();\n m2.unlock();\n }\n\n void third(function<void()> printThird) {\n m2.lock();\n // printThird() outputs "third". Do not change or remove this line.\n printThird();\n m2.unlock();\n }\n};\n``` | 25 | 7 | [] | 4 |
print-in-order | Python Simple Working solution | python-simple-working-solution-by-simonk-t210 | python\nfrom threading import Lock\n\nclass Foo:\n def __init__(self):\n self.lock1 = Lock()\n self.lock2 = Lock()\n \n self.lock | simonkocurek | NORMAL | 2019-07-25T18:13:10.733565+00:00 | 2019-07-25T18:13:47.268397+00:00 | 2,129 | false | ```python\nfrom threading import Lock\n\nclass Foo:\n def __init__(self):\n self.lock1 = Lock()\n self.lock2 = Lock()\n \n self.lock1.acquire()\n self.lock2.acquire()\n\n\n def first(self, printFirst: \'Callable[[], None]\') -> None:\n printFirst()\n \n self.lock1.release()\n\n\n def second(self, printSecond: \'Callable[[], None]\') -> None:\n self.lock1.acquire() # Wait unti first finishes\n \n printSecond()\n \n self.lock2.release()\n\n def third(self, printThird: \'Callable[[], None]\') -> None:\n self.lock2.acquire() # Wait unti second finishes\n \n printThird()\n``` | 22 | 0 | [] | 1 |
print-in-order | Python3 Solution using 5 primitives (lock, semaphore, condition, event, barrier) | python3-solution-using-5-primitives-lock-py7g | Approach \#1. Lock\n- RLock is not suitable in this case. \n\n\n\n# Approach \#2. Semaphore\n- Semaphore(1) is equivalent to Lock()\n\n\n# Approach \#3. Conditi | idontknoooo | NORMAL | 2022-12-18T21:14:03.333747+00:00 | 2022-12-18T21:16:54.360632+00:00 | 2,371 | false | # Approach \\#1. Lock\n- `RLock` is not suitable in this case. \n\n<iframe src="https://leetcode.com/playground/mgRcT2DB/shared" frameBorder="0" width="600" height="400"></iframe>\n\n# Approach \\#2. Semaphore\n- `Semaphore(1)` is equivalent to `Lock()`\n<iframe src="https://leetcode.com/playground/c4bkiTBr/shared" frameBorder="0" width="600" height="400"></iframe>\n\n# Approach \\#3. Condition\n<iframe src="https://leetcode.com/playground/Z2up2An3/shared" frameBorder="0" width="600" height="500"></iframe>\n\n# Approach \\#4. Event \n<iframe src="https://leetcode.com/playground/hTnE2h6z/shared" frameBorder="0" width="600" height="400"></iframe>\n\n# Approach \\#5. Barrier\n<iframe src="https://leetcode.com/playground/RxQpksKT/shared" frameBorder="0" width="600" height="400"></iframe>\n | 20 | 0 | ['Concurrency', 'Python3'] | 3 |
print-in-order | easiest solution || c-plus-plus || easy to understand || without using mutex 😎😎😎 | easiest-solution-c-plus-plus-easy-to-und-q37n | 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 | youdontknow001 | NORMAL | 2022-11-25T05:03:28.273633+00:00 | 2022-11-25T05:03:28.273668+00:00 | 5,380 | 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 Foo {\n promise<void> p1,p2;\npublic:\n Foo() {\n \n }\n\n void first(function<void()> printFirst) {\n \n // printFirst() outputs "first". Do not change or remove this line.\n printFirst();\n p1.set_value();\n }\n\n void second(function<void()> printSecond) {\n \n // printSecond() outputs "second". Do not change or remove this line.\n p1.get_future().wait();\n printSecond();\n p2.set_value();\n }\n\n void third(function<void()> printThird) {\n \n // printThird() outputs "third". Do not change or remove this line.\n p2.get_future().wait();\n printThird();\n }\n};\n``` | 18 | 0 | ['C++'] | 1 |
print-in-order | C | Minimal code | c-minimal-code-by-kmr_shubh-nufl | \ntypedef struct {\n // User defined data is declared here.\n // using \'volatile\' to prevent compiler from playing god and optimize out this critical va | kmr_shubh | NORMAL | 2022-02-20T14:46:36.373139+00:00 | 2024-06-06T04:02:56.167900+00:00 | 1,559 | false | ```\ntypedef struct {\n // User defined data is declared here.\n // using \'volatile\' to prevent compiler from playing god and optimize out this critical variable\n // this is mutex variable, duh \n volatile int turn;\n} Foo;\n\nvoid wait(Foo* obj, int my_turn) {\n // blocking this thread till my turn\n while(obj->turn != my_turn) pthread_yield(NULL); // Nope Gotta wait \uFF08\u25DE\u2038\u25DF\uFF09\n \n // Aha!! free at last guess I will return now\n}\n\nvoid signal(Foo* obj) {\n ++obj->turn; // pass it to next in line (psst: for the future generations)\n}\n\nFoo* fooCreate() {\n Foo* obj = (Foo*) malloc(sizeof(Foo));\n // Initialize user defined data here.\n obj->turn = 1; // first will be executed first, lol \n return obj;\n}\n\nvoid first(Foo* obj) {\n printFirst();\n signal(obj); // I am done please pass ownership of mutex to next in line ( \u0361\xB0 \u035C\u0296 \u0361\xB0) \n}\n\nvoid second(Foo* obj) {\n wait(obj, 2); // Ok I will wait till my (2) turn (\u2565\uFE4F\u2565)\n printSecond();\n signal(obj); // I am done please pass ownership of mutex to next in line ( \u0361\xB0 \u035C\u0296 \u0361\xB0) \n}\n\nvoid third(Foo* obj) {\n wait(obj, 3); // Ok I will wait till my (3) turn (\u2565\uFE4F\u2565)\n printThird(); \n // Oh! no one else left to signal, I guess this ends with me now, *sigh* \uFF08\u25DE\u2038\u25DF\uFF09\n}\n\nvoid fooFree(Foo* obj) {\n // I am a responsible citizen I clean up after me \n free(obj);\n}\n``` | 17 | 0 | ['C'] | 1 |
print-in-order | C# Semaphore-based solution | c-semaphore-based-solution-by-vlassov-1bjh | \nusing System.Threading;\n\npublic class Foo {\n private readonly Semaphore first = new Semaphore(1, 1);\n private readonly Semaphore second = new Semaph | vlassov | NORMAL | 2020-09-20T22:42:19.215797+00:00 | 2020-09-20T22:42:19.215828+00:00 | 1,417 | false | ```\nusing System.Threading;\n\npublic class Foo {\n private readonly Semaphore first = new Semaphore(1, 1);\n private readonly Semaphore second = new Semaphore(0, 1);\n private readonly Semaphore third = new Semaphore(0, 1);\n\n public void First(Action printFirst) {\n first.WaitOne();\n printFirst();\n second.Release();\n }\n\n public void Second(Action printSecond) {\n second.WaitOne();\n printSecond();\n third.Release();\n }\n\n public void Third(Action printThird) {\n third.WaitOne();\n printThird();\n first.Release();\n }\n}\n``` | 16 | 1 | [] | 1 |
print-in-order | Clean and easy java solution | clean-and-easy-java-solution-by-andreazu-iq79 | \nimport java.util.concurrent.Semaphore;\n\nclass Foo {\n\n final Semaphore hasFirstRun = new Semaphore(0);\n final Semaphore hasSecondRun = new Semaphore | andreazube | NORMAL | 2019-07-12T09:02:56.943744+00:00 | 2019-07-12T09:02:56.943786+00:00 | 2,922 | false | ```\nimport java.util.concurrent.Semaphore;\n\nclass Foo {\n\n final Semaphore hasFirstRun = new Semaphore(0);\n final Semaphore hasSecondRun = new Semaphore(0);\n\n public void first(Runnable printFirst) throws InterruptedException {\n printFirst.run();\n hasFirstRun.release(); // Allows second() to run, and wakes it if it\'s sleeping.\n }\n\n public void second(Runnable printSecond) throws InterruptedException {\n /*\n hasFirstRun is initialized to 0. This means that if second() is executed\n before first(), it can\'t get the lock and goes to sleep. In this case, it\n will be waked up by first().\n \n If second() is executed after first(), then it can acquire the semaphore immediately\n and execute its code.\n */\n hasFirstRun.acquire(); \n printSecond.run();\n hasSecondRun.release();\n }\n\n public void third(Runnable printThird) throws InterruptedException {\n hasSecondRun.acquire(); // same logic as second()\n printThird.run();\n }\n}\n``` | 16 | 0 | ['Java'] | 0 |
print-in-order | [JAVA] Two Methods 【CAS】ans【synchronized】 | java-two-methods-cas-anssynchronized-by-z65wr | 1. CAS\n\nimport java.util.concurrent.atomic.AtomicInteger;\n\nclass Foo {\n\n\tAtomicInteger count = new AtomicInteger();\n\n\tpublic Foo() {\n\t\tcount.set(0) | frankzhang5513 | NORMAL | 2019-07-21T09:45:31.812115+00:00 | 2019-09-05T14:11:11.911223+00:00 | 2,130 | false | **1. CAS**\n```\nimport java.util.concurrent.atomic.AtomicInteger;\n\nclass Foo {\n\n\tAtomicInteger count = new AtomicInteger();\n\n\tpublic Foo() {\n\t\tcount.set(0);\n\t}\n\n\tpublic void first(Runnable printFirst) throws InterruptedException {\n\n\t\twhile (!count.compareAndSet(0, 4)) {\n\t\t\t// printFirst.run() outputs "first". Do not change or remove this line.\n\t\t}\n\t\tprintFirst.run();\n\t\tcount.set(1);\n\t}\n\n\tpublic void second(Runnable printSecond) throws InterruptedException {\n\t\twhile (!count.compareAndSet(1, 4)) {\n\t\t\t// printSecond.run() outputs "second". Do not change or remove this line.\n\t\t}\n\t\tprintSecond.run();\n\t\tcount.set(2);\n\n\t}\n\n\tpublic void third(Runnable printThird) throws InterruptedException {\n\t\twhile (!count.compareAndSet(2, 4)) {\n\t\t\t// printThird.run() outputs "third". Do not change or remove this line.\n\t\t}\n\t\tprintThird.run();\n\t\tcount.set(3);\n\t}\n}\n```\n\n\n**2. Synchronized**\n```\nimport java.util.concurrent.locks.*;\n\nclass Foo {\n\n int count = 0;\n \n public Foo() {\n }\n\n public synchronized void first(Runnable printFirst) throws InterruptedException {\n \n \n printFirst.run();\n count++;\n this.notifyAll();\n\n }\n\n public synchronized void second(Runnable printSecond) throws InterruptedException {\n \n while(count != 1){\n this.wait();\n }\n printSecond.run();\n count++;\n this.notifyAll();\n }\n\n public synchronized void third(Runnable printThird) throws InterruptedException {\n\n while(count != 2){\n this.wait();\n }\n printThird.run();\n count++;\n }\n}\n``` | 12 | 0 | [] | 4 |
print-in-order | [C++] three versions: condition variables, semaphores, simple bools [fastest 124ms] | c-three-versions-condition-variables-sem-g8us | Version 1: One mutex lock + two condition variables\n 124 ms\n faster than 89.41%\n\nclass Foo {\npublic:\n bool firstRan = false;\n bool secondRan = fals | aly5321 | NORMAL | 2019-07-19T18:59:04.000554+00:00 | 2019-07-19T19:22:32.721635+00:00 | 2,718 | false | Version 1: One mutex lock + two condition variables\n* 124 ms\n* faster than 89.41%\n```\nclass Foo {\npublic:\n bool firstRan = false;\n bool secondRan = false;\n pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;\n pthread_cond_t cv1 = PTHREAD_COND_INITIALIZER;\n pthread_cond_t cv2 = PTHREAD_COND_INITIALIZER;\n\t\n Foo() { }\n\n void first(function<void()> printFirst) {\n // printFirst() outputs "first". Do not change or remove this line.\n printFirst();\n \n pthread_mutex_lock(&m);\n firstRan = true;\n pthread_mutex_unlock(&m);\n pthread_cond_broadcast(&cv1);\n }\n\n void second(function<void()> printSecond) {\n pthread_mutex_lock(&m);\n\t\t\n while (!firstRan) { \n pthread_cond_wait(&cv1, &m);\n }\n\t\t\n // printSecond() outputs "second". Do not change or remove this line.\n printSecond();\n \n secondRan = true;\n pthread_mutex_unlock(&m);\n pthread_cond_broadcast(&cv2);\n }\n\n void third(function<void()> printThird) {\n pthread_mutex_lock(&m);\n\t\t\n while (!firstRan) {\n pthread_cond_wait(&cv1, &m);\n }\n while (!secondRan) {\n pthread_cond_wait(&cv2, &m);\n }\n\t\t\n // printThird() outputs "third". Do not change or remove this line.\n printThird();\n pthread_mutex_unlock(&m);\n }\n};\n```\n\nVersion 2: Two semaphores\n* 132 ms\n* Faster than 82.37%\n```\n#include <semaphore.h>\n\nclass Foo {\npublic:\n sem_t s1;\n sem_t s2;\n Foo() {\n sem_init(&s1, 0, 0);\n sem_init(&s2, 0, 0);\n }\n\n void first(function<void()> printFirst) {\n // printFirst() outputs "first". Do not change or remove this line.\n printFirst();\n sem_post(&s1);\n }\n\n void second(function<void()> printSecond) {\n sem_wait(&s1);\n // printSecond() outputs "second". Do not change or remove this line.\n printSecond();\n sem_post(&s2);\n \n }\n\n void third(function<void()> printThird) {\n sem_wait(&s2);\n // printThird() outputs "third". Do not change or remove this line.\n printThird();\n }\n};\n```\n\nVersion 3: Simple bools\n* 1400 ms\n* Faster than 8.13%\n```\nclass Foo {\npublic:\n bool firstRan = false;\n bool secondRan = false;\n Foo() { }\n\n void first(function<void()> printFirst) {\n // printFirst() outputs "first". Do not change or remove this line.\n printFirst();\n \n firstRan = true;\n }\n\n void second(function<void()> printSecond) {\n while(!firstRan) { }\n // printSecond() outputs "second". Do not change or remove this line.\n printSecond();\n secondRan = true;\n }\n\n void third(function<void()> printThird) {\n while (!(firstRan && secondRan)) { }\n // printThird() outputs "third". Do not change or remove this line.\n printThird();\n }\n};\n```\n\nLet me know if anyone finds better ways to do what I did! | 12 | 1 | ['C'] | 9 |
print-in-order | 4 Python solutions | 4-python-solutions-by-faceplant-x49h | Solution 1:\n\nfrom threading import Event\nclass Foo:\ndef __init__(self):\n\tself.done = (Event(),Event())\n\ndef first(self, printFirst):\n\tprintFirst()\n\t | FACEPLANT | NORMAL | 2021-01-21T16:40:32.412474+00:00 | 2021-01-21T16:40:32.412517+00:00 | 1,301 | false | **Solution 1:**\n```\nfrom threading import Event\nclass Foo:\ndef __init__(self):\n\tself.done = (Event(),Event())\n\ndef first(self, printFirst):\n\tprintFirst()\n\tself.done[0].set()\n\ndef second(self, printSecond):\n\tself.done[0].wait()\n\tprintSecond()\n\tself.done[1].set()\n\ndef third(self, printThird):\n\tself.done[1].wait()\n\tprintThird()\n```\n\n**Solution 2:**\n```\nfrom threading import Barrier\nclass Foo:\n def __init__(self):\n self.first_barrier = Barrier(2)\n self.second_barrier = Barrier(2)\n def first(self, printFirst):\n printFirst()\n self.first_barrier.wait()\n def second(self, printSecond):\n self.first_barrier.wait()\n printSecond()\n self.second_barrier.wait()\n def third(self, printThird):\n self.second_barrier.wait()\n printThird()\n```\n\n**Solution 3:**\n```\nfrom threading import Lock\nclass Foo:\n def __init__(self):\n self.locks = (Lock(),Lock())\n self.locks[0].acquire()\n self.locks[1].acquire()\n def first(self, printFirst):\n printFirst()\n self.locks[0].release()\n def second(self, printSecond):\n with self.locks[0]:\n printSecond()\n self.locks[1].release()\n def third(self, printThird):\n with self.locks[1]:\n printThird()\n```\n\n**Solution 4:**\n```\nfrom threading import Semaphore\nclass Foo:\n def __init__(self):\n self.gates = (Semaphore(0),Semaphore(0))\n def first(self, printFirst):\n printFirst()\n self.gates[0].release()\n def second(self, printSecond):\n with self.gates[0]:\n printSecond()\n self.gates[1].release()\n def third(self, printThird):\n with self.gates[1]:\n printThird()\n``` | 11 | 0 | [] | 0 |
print-in-order | C#- Using AutoReset | c-using-autoreset-by-christris-ny2q | csharp\nusing System.Threading; \n\npublic class Foo \n{\n private EventWaitHandle waitFirst;\n private EventWaitHandle waitSecond;\n\n public Foo() | christris | NORMAL | 2020-05-08T13:42:23.759848+00:00 | 2020-05-08T13:42:23.759899+00:00 | 1,071 | false | ```csharp\nusing System.Threading; \n\npublic class Foo \n{\n private EventWaitHandle waitFirst;\n private EventWaitHandle waitSecond;\n\n public Foo() \n {\n waitFirst = new AutoResetEvent(initialState: false);\n waitSecond = new AutoResetEvent(initialState: false);\n }\n\n public void First(Action printFirst) \n { \n // printFirst() outputs "first". Do not change or remove this line.\n printFirst();\n \n waitFirst.Set();\n }\n\n public void Second(Action printSecond) \n {\n waitFirst.WaitOne();\n \n // printSecond() outputs "second". Do not change or remove this line.\n printSecond();\n \n waitSecond.Set();\n }\n\n public void Third(Action printThird) \n {\n waitSecond.WaitOne();\n \n // printThird() outputs "third". Do not change or remove this line.\n printThird();\n }\n}\n``` | 9 | 0 | [] | 0 |
print-in-order | C++ condition variable ~ 96% (also explaining how condition_variable works) | c-condition-variable-96-also-explaining-32adi | How condition_variable works:\n1. First, you need to acquire a mutex using unique_lock. We need a unique_lock because before putting the thread to sleep, condit | dineshkwal | NORMAL | 2019-11-16T11:24:52.801839+00:00 | 2020-06-18T14:33:15.489592+00:00 | 1,384 | false | How `condition_variable` works:\n1. First, you need to acquire a `mutex` using `unique_lock`. We need a unique_lock because before putting the thread to sleep, condition_variable will need to release the mutex and unique_lock provides that flexibility.\n2. Next, you call the `wait` function of condition_variable with the above lock and optionally a `predicate`. It causes the current thread to block (sleep). The thread is unblocked when `notify_all` or `notify_one` is executed on some other thread. \n4. It might also be unblocked *spuriously* that\'s where the predicate comes handy. So, whenever there are spurious wake-ups, condition_variable will acquire the mutex and check the predicate. **If** the predicate returns true, thread will proceed further and mutex will stay acquired, **otherwise** it will release the mutex and sleep again.\n5. When the thread has completed its work, it\'s *generally* a better idea to release the lock before notifying other threads, if need be.\n\n```\nclass Foo {\npublic:\n void first(function<void()> printFirst) {\n // first doesn\'t have to wait for anyone and it doesn\'t acquire any lock either\n printFirst(); \n // firstPrinted is atomic because second might be trying to read while this thread is modifying it.\n firstPrinted = true;\n // notify waiting threads\n cv.notify_all();\n }\n\n void second(function<void()> printSecond) {\n // acquire lock, C++17 way\n unique_lock guard(m);\n // condition to wait for is => first should have printed.\n cv.wait(guard, [this] { return this->firstPrinted == true; });\n // now print\n printSecond();\n // secondPrinted need not be atomic, because its access is already protected by mutex in both second and third. \n secondPrinted = true;\n // release mutex before notifying\n guard.unlock();\n // notify\n cv.notify_one();\n }\n\n void third(function<void()> printThird) {\n // acquire lock\n unique_lock guard(m);\n // condition to wait for is => second should have printed. \n cv.wait(guard, [this] { return secondPrinted == true; });\n // now print\n printThird();\n }\n \nprivate:\n condition_variable cv;\n mutex m;\n atomic_bool firstPrinted = false;\n bool secondPrinted = false;\n};\n``` | 9 | 1 | ['C'] | 1 |
print-in-order | Java 9 different solutions: Exchanger, Barrier, Latch, Lock etc | java-9-different-solutions-exchanger-bar-r4vg | Still learning. There are just so many choices Java gave us to handle multithreading.\n\nI am sure there are more ways to do this. And my knowledge is limited, | gangjig | NORMAL | 2023-11-16T01:16:53.682856+00:00 | 2024-02-19T19:05:23.181592+00:00 | 698 | false | Still learning. There are just so many choices Java gave us to handle multithreading.\n\nI am sure there are more ways to do this. And my knowledge is limited, I will come back to this post and improve and add more comparison once I understand better.\n\nFor synchronized solution:\n\nIf a thread calls wait() but no other threads are performing a corresponding notify() or notifyAll(), those threads will remain in the waiting state indefinitely. Moreover, if your application creates an excessive number of threads that all try to acquire the lock using synchronized blocks, it could lead to resource exhaustion or decreased performance due to excessive context switching.\n\nWe need to put wait() in a loop, also check the condition in the loop. Java does not guarantee that the thread will be woken up only by a notify()/notifyAll() call or the right notify()/notifyAll() call at all. Because of this property the loop-less version might work on your development environment and fail on the production environment unexpectedly.\n\nA thread can also wake up without being notified, interrupted, or timing out, a so-called spurious wakeup. While this will rarely occur in practice, applications must guard against it by testing for the condition that should have caused the thread to be awakened, and continuing to wait if the condition is not satisfied. In other words, waits should always occur in loops, like this one:\n\n synchronized (obj) {\n while (<condition does not hold>)\n obj.wait(timeout);\n ... // Perform action appropriate to condition\n }\nhttps://docs.oracle.com/javase/6/docs/api/java/lang/Object.html#wait(long)\n\n### volatile\nvolatile keyword id quite different from other mechanism. It\'s to tell JVM to put the variable in the main memory of the server, instead of the cache on the cpu. When we have multi threads running on the server, they run on diferent CPUs, then using their own caches, so one CPU may get older value when another CPU already updated the value in its cache. Volatile keyword ensures that any thread reading the variable sees the most recent modification made by any other thread.\n\nWe should understand that this is on web server level, not database level. A often brought up question during interviews is when we have multi web servers trying to update the same data in database, how do we make sure we are getting the latest update. Volatile will have nothing to do with that.\n\nAnother question is about redis, is there a similar mechanism in Redis? answer is no, since redis is single threaded by default, that\'show it\'s built. How to sync up redis servers in different data centers is a totally different challenge.\n```\n public static volatile int methodCompleted;\n public Foo() {\n methodCompleted = 0;\n }\n\n public void first(Runnable printFirst) throws InterruptedException {\n // printFirst.run() outputs "first". Do not change or remove this line.\n printFirst.run();\n methodCompleted = 1;\n }\n\n public void second(Runnable printSecond) throws InterruptedException {\n while(methodCompleted != 1) ;\n // printSecond.run() outputs "second". Do not change or remove this line.\n printSecond.run();\n methodCompleted = 2;\n }\n\n public void third(Runnable printThird) throws InterruptedException {\n while(methodCompleted != 2) ;\n // printThird.run() outputs "third". Do not change or remove this line.\n printThird.run();\n methodCompleted = 3;\n }\n```\n\n### Exchanger\n\n```\nimport java.util.concurrent.Exchanger;\n\npublic class Foo {\n private final Exchanger<Boolean> exchanger12 = new Exchanger<>();\n private final Exchanger<Boolean> exchanger23 = new Exchanger<>();\n\n public Foo() {}\n\n public void first(Runnable printFirst) throws InterruptedException {\n printFirst.run();\n try {\n exchanger12.exchange(true); // Signal that first() has completed\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n }\n\n public void second(Runnable printSecond) throws InterruptedException {\n try {\n exchanger12.exchange(true); // Wait for first() to complete\n printSecond.run();\n exchanger23.exchange(true); // Signal that second() has completed\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n }\n\n public void third(Runnable printThird) throws InterruptedException {\n try {\n exchanger23.exchange(true); // Wait for second() to complete\n printThird.run();\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n }\n}\n\n```\n### CyclicBarrier\n```\nimport java.util.concurrent.BrokenBarrierException;\nimport java.util.concurrent.CyclicBarrier;\n\npublic class Foo {\n private final CyclicBarrier barrier1 = new CyclicBarrier(2);\n private final CyclicBarrier barrier2 = new CyclicBarrier(2);\n\n public Foo() {}\n\n public void first(Runnable printFirst) throws InterruptedException {\n printFirst.run();\n try {\n barrier1.await();\n } catch (BrokenBarrierException e) {}\n\n }\n\n public void second(Runnable printSecond) throws InterruptedException {\n try {\n barrier1.await();\n } catch (BrokenBarrierException e) {}\n printSecond.run();\n try {\n barrier2.await();\n } catch (BrokenBarrierException e) {}\n }\n\n public void third(Runnable printThird) throws InterruptedException {\n try {\n barrier2.await();\n } catch (BrokenBarrierException e) {}\n printThird.run();\n }\n}\n```\n\n### Latch:\n```\nimport java.util.concurrent.CountDownLatch;\n\npublic class Foo {\n private CountDownLatch latch1;\n private CountDownLatch latch2;\n\n public Foo() {\n latch1 = new CountDownLatch(1);\n latch2 = new CountDownLatch(1);\n }\n\n public void first(Runnable printFirst) throws InterruptedException {\n // printFirst.run() outputs "first". Do not change or remove this line.\n printFirst.run();\n latch1.countDown(); // Signal that the first method has been executed\n }\n\n public void second(Runnable printSecond) throws InterruptedException {\n latch1.await(); // Wait until the first method completes\n // printSecond.run() outputs "second". Do not change or remove this line.\n printSecond.run();\n latch2.countDown(); // Signal that the second method has been executed\n }\n\n public void third(Runnable printThird) throws InterruptedException {\n latch2.await(); // Wait until the second method completes\n // printThird.run() outputs "third". Do not change or remove this line.\n printThird.run();\n }\n}\n```\n\n### Lock (same as Mutex):\n```\nclass Foo {\n private volatile int jobCompleted = 0;\n private final Lock lock = new ReentrantLock();\n private final Condition isJobCompleted = lock.newCondition();\n\n private void orderJob(final int jobNumber, Runnable job) throws InterruptedException {\n lock.lock();\n try {\n while (jobCompleted != jobNumber - 1) isJobCompleted.await();\n job.run();\n jobCompleted = jobNumber;\n isJobCompleted.signalAll();\n } finally {\n lock.unlock();\n }\n }\n\n public void first(Runnable printFirst) throws InterruptedException {\n orderJob(1, printFirst);\n }\n\n public void second(Runnable printSecond) throws InterruptedException {\n orderJob(2, printSecond);\n }\n\n public void third(Runnable printThird) throws InterruptedException {\n orderJob(3, printThird);\n }\n}\n```\n\n### AtomicBoolean:\n```\nclass Foo {\n\n private AtomicBoolean firstJobDone = new AtomicBoolean(false);\n private AtomicBoolean secondJobDone = new AtomicBoolean(false);\n\n public Foo() {}\n\n public void first(Runnable printFirst) throws InterruptedException {\n // printFirst.run() outputs "first".\n printFirst.run();\n // mark the first job as done, by increasing its count.\n firstJobDone.set(true);\n }\n\n/*Second and third threads in Java solution based on AtomicInteger will consume CPU cycles while waiting. This may be good to have faster runtime in the test, but in real life it is better to have these threads in WAITING state. For concurrency tasks it makes sense to add one more index - CPU load or something like this (in addition to runtime and memory distributions)\n*/\n public void second(Runnable printSecond) throws InterruptedException {\n while (!firstJobDone.get()) {\n // waiting for the first job to be done.\n }\n // printSecond.run() outputs "second".\n printSecond.run();\n // mark the second as done, by increasing its count.\n secondJobDone.set(true);\n }\n\n public void third(Runnable printThird) throws InterruptedException {\n while (!secondJobDone.get()) {\n // waiting for the second job to be done.\n }\n // printThird.run() outputs "third".\n printThird.run();\n }\n}\n```\n### AtomicBooleans Approach:\n\nAtomicBooleans provide a simple mechanism for ensuring visibility and atomicity in thread-safe operations without explicit synchronization.\nThe AtomicBoolean approach ensures that threads don\'t waste CPU cycles actively waiting for conditions to be met.\nHowever, the while loop continuously polls for the state change, potentially consuming CPU resources.\n\nEverybody has seen these three:\n\n### Semaphore:\n```\nclass Foo {\n // By starting with 0 permits, you ensure that any attempt to acquire a permit \n // using s1.acquire() in the second method will block until s1.release() is called \n Semaphore s1 = new Semaphore(0), s2 = new Semaphore(0);\n public Foo() {\n \n }\n\n public void first(Runnable printFirst) throws InterruptedException {\n \n // printFirst.run() outputs "first". Do not change or remove this line.\n printFirst.run();\n // increases the number of available permits by 1.\n s1.release();\n }\n\n public void second(Runnable printSecond) throws InterruptedException {\n s1.acquire();\n // printSecond.run() outputs "second". Do not change or remove this line.\n printSecond.run();\n s2.release();\n }\n\n public void third(Runnable printThird) throws InterruptedException {\n s2.acquire();\n // printThird.run() outputs "third". Do not change or remove this line.\n printThird.run();\n }\n}\n\n```\n\n\n### Semaphore Approach:\n\nSemaphores are synchronization constructs used to control access to a shared resource.\nThis approach allows threads to block until a signal (in the form of a release) is received, minimizing active CPU polling.\nSemaphores provide a more efficient solution in terms of not actively consuming CPU resources while waiting for conditions to be met.\n\n### AtomicInteger:\n```\nclass Foo {\n\n private AtomicInteger firstJobDone = new AtomicInteger(0);\n private AtomicInteger secondJobDone = new AtomicInteger(0);\n\n public Foo() {}\n\n public void first(Runnable printFirst) throws InterruptedException {\n // printFirst.run() outputs "first".\n printFirst.run();\n // mark the first job as done, by increasing its count.\n firstJobDone.incrementAndGet();\n }\n\n public void second(Runnable printSecond) throws InterruptedException {\n while (firstJobDone.get() != 1) {\n // waiting for the first job to be done.\n }\n // printSecond.run() outputs "second".\n printSecond.run();\n // mark the second as done, by increasing its count.\n secondJobDone.incrementAndGet();\n }\n\n public void third(Runnable printThird) throws InterruptedException {\n while (secondJobDone.get() != 1) {\n // waiting for the second job to be done.\n }\n // printThird.run() outputs "third".\n printThird.run();\n }\n}\n```\n\nAtomicInteger should be similar as AtomicBoolean, just not as clean for this question.\n\n### synchronized:\n```\nclass Foo {\n private boolean oneDone;\n private boolean twoDone;\n \n public Foo() {\n oneDone = false;\n twoDone = false;\n }\n\n public synchronized void first(Runnable printFirst) throws InterruptedException {\n \n // printFirst.run() outputs "first". Do not change or remove this line.\n printFirst.run();\n oneDone = true;\n notifyAll();\n }\n\n public synchronized void second(Runnable printSecond) throws InterruptedException {\n while(!oneDone) wait();\n // printSecond.run() outputs "second". Do not change or remove this line.\n printSecond.run();\n twoDone = true;\n notifyAll();\n }\n\n public synchronized void third(Runnable printThird) throws InterruptedException {\n while(!twoDone) wait();\n // printThird.run() outputs "third". Do not change or remove this line.\n printThird.run();\n }\n}\n```\n\nI put the discussion part of this approach at top of the article, since this is the most popular solution, and basic for us to start from. | 8 | 0 | ['Java'] | 2 |
print-in-order | Python - Simple and Elegant! Event-based | python-simple-and-elegant-event-based-by-oanr | Solution:\n\nfrom threading import Event\n\nclass Foo:\n def __init__(self):\n self.event1, self.event2 = Event(), Event()\n\n def first(self, f):\ | domthedeveloper | NORMAL | 2022-03-24T06:20:57.786767+00:00 | 2022-03-24T06:20:57.786803+00:00 | 1,388 | false | **Solution**:\n```\nfrom threading import Event\n\nclass Foo:\n def __init__(self):\n self.event1, self.event2 = Event(), Event()\n\n def first(self, f):\n f()\n self.event1.set()\n\n def second(self, f):\n self.event1.wait()\n f()\n self.event2.set()\n\n def third(self, f):\n self.event2.wait()\n f()\n``` | 8 | 0 | ['Python', 'Python3'] | 0 |
print-in-order | 3 C++ Solutions: Promises, Condition_variables, Atomic Bools | 3-c-solutions-promises-condition_variabl-dnob | If you liked it please upvote!\n\nC++ promise/future:\n1 of the 2 fastest (second one is the condition_variable)\n\nclass Foo {\nprivate:\n std::promise<void | dshelem | NORMAL | 2021-02-12T13:29:02.843754+00:00 | 2021-08-20T07:28:13.048361+00:00 | 685 | false | If you liked it please upvote!\n\n**C++ promise/future:**\n1 of the 2 fastest (second one is the condition_variable)\n```\nclass Foo {\nprivate:\n std::promise<void> prom_first;\n std::promise<void> prom_second;\n std::future<void> fut_first;\n std::future<void> fut_second;\npublic:\n Foo() {\n fut_first = prom_first.get_future();\n fut_second = prom_second.get_future();\n }\n \n void first(function<void()> printFirst) {\n // printFirst() outputs "first". Do not change or remove this line.\n printFirst();\n prom_first.set_value();\n }\n\n void second(function<void()> printSecond) {\n fut_first.wait();\n // printSecond() outputs "second". Do not change or remove this line.\n printSecond();\n prom_second.set_value();\n }\n\n void third(function<void()> printThird) {\n fut_second.wait();\n // printThird() outputs "third". Do not change or remove this line.\n printThird();\n }\n};\n```\n\n**C++ condition variable**\n1 of the 2 fastest (second one is the promises/futures)\n```\nclass Foo {\nprivate:\n std::mutex mutex1, mutex2, mutex3;\n std::condition_variable cv2, cv3;\n bool second_unlocked = false;\n bool third_unlocked = false;\npublic:\n Foo() { }\n \n void first(function<void()> printFirst) {\n // printFirst() outputs "first". Do not change or remove this line.\n printFirst();\n {\n std::lock_guard lock(mutex1);\n second_unlocked = true;\n }\n cv2.notify_one();\n }\n\n void second(function<void()> printSecond) {\n std::unique_lock lock(mutex2);\n cv2.wait(lock, [this] { return second_unlocked; });\n \n // printSecond() outputs "second". Do not change or remove this line.\n printSecond();\n \n third_unlocked = true;\n lock.unlock();\n cv3.notify_one();\n }\n\n void third(function<void()> printThird) {\n std::unique_lock lock(mutex3);\n cv3.wait(lock, [this] { return third_unlocked; });\n \n // printThird() outputs "third". Do not change or remove this line.\n printThird();\n }\n};\n```\n\n**C++ atomic bools**\nSimplest but obviously the slowest solution\n```\nclass Foo {\nprivate:\n std::atomic<bool> second_unlocked = false, third_unlocked = false;\npublic:\n Foo() { }\n \n void first(function<void()> printFirst) {\n // printFirst() outputs "first". Do not change or remove this line.\n printFirst();\n second_unlocked = true;\n }\n\n void second(function<void()> printSecond) {\n while(!second_unlocked)\n ;\n \n // printSecond() outputs "second". Do not change or remove this line.\n printSecond();\n \n third_unlocked = true;\n }\n\n void third(function<void()> printThird) {\n \n while(!third_unlocked)\n ;\n \n // printThird() outputs "third". Do not change or remove this line.\n printThird();\n }\n};\n``` | 8 | 0 | [] | 4 |
print-in-order | [Java] 4 Different Solutions w/ Explanation | java-4-different-solutions-w-explanation-h0z6 | 0. Analysis\nHere we have 3 threads and all we want to achieve is to make sure the 3 threads run in a specific order. To achieve this, we need coordination amon | isaacjumac | NORMAL | 2020-07-28T16:43:12.278356+00:00 | 2020-07-28T16:47:22.257217+00:00 | 413 | false | ## 0. Analysis\nHere we have 3 threads and all we want to achieve is to make sure the 3 threads run in a specific order. To achieve this, we need coordination among the threads, which means accessing and managing some common objects/resources. I think the most important point to achieve is about **visibility**: the other threads should be able to know the state change of some commonly accessed objects/values used for the coordination.\n\nTo achieve this, we can either use some ready-to-use utility classes in `java.util.concurrent` package, or managing the visibility and status with some Java language features. \n\nBelow are a few possible solutions:\n\n## 1. The volatile keyword\nIn summary, the Java `volatile` keyword **guarantees visibility of changes** to variables across threads (from [this article](http://tutorials.jenkov.com/java-concurrency/volatile.html)), and that\'s literally all we need here so that when` first()` and `second()` increment the `flag` value, the next methods (in other threads) are able to capture the updated value so that the execution condition can be met (i.e., the `while` loop will exit).\n\nSo we have the solution like below:\n```\nclass Foo {\n private static volatile int flag;\n \n public Foo() {\n flag = 1;\n }\n\n public void first(Runnable printFirst) throws InterruptedException {\n // printFirst.run() outputs "first". Do not change or remove this line.\n printFirst.run();\n flag++; // flag that it\'s ready for second() to run\n }\n\n public void second(Runnable printSecond) throws InterruptedException {\n while(flag != 2){} // wait until the flag turns 2\n // printSecond.run() outputs "second". Do not change or remove this line.\n printSecond.run();\n flag++; // flag that it\'s ready for third() to run\n }\n\n public void third(Runnable printThird) throws InterruptedException {\n while(flag != 3){} // wait until the flag turns 3\n // printThird.run() outputs "third". Do not change or remove this line.\n printThird.run();\n }\n}\n```\n\n## 2. AtomicInteger\nThe `AtomicXXX` classes are located in `java.util.concurrent` package. The main feature for those classes is that they ensure ***atomic actions*** on the instances, which in simple terms means that only a single thread will be able to access the object at a time, and the updated value will be visible to other threads. It\'s achieved using CAS (compare and swap) strategy.\n\nSo the solution is like below:\n```\nclass Foo {\n private static AtomicInteger flag;\n \n public Foo() {\n flag = new AtomicInteger(1);\n }\n\n public void first(Runnable printFirst) throws InterruptedException {\n // printFirst.run() outputs "first". Do not change or remove this line.\n printFirst.run();\n flag.incrementAndGet(); // flag that it\'s ready for second() to run\n }\n\n public void second(Runnable printSecond) throws InterruptedException {\n while(flag.get() != 2){} // wait until the flag value turns 2\n // printSecond.run() outputs "second". Do not change or remove this line.\n printSecond.run();\n flag.incrementAndGet(); // flag that it\'s ready for third() to run\n }\n\n public void third(Runnable printThird) throws InterruptedException {\n while(flag.get() != 3){} // wait until the flag value turns 3\n // printThird.run() outputs "third". Do not change or remove this line.\n printThird.run();\n }\n}\n```\n\n## 3. Semaphore\nA `Semaphore` manages a set of virtual permits; the initial number of permits is passed to the Semaphore constructor. Activities can `acquire` permits (as long as some remain) and `release` permits when they are done with them. If no permit is available, acquire blocks until one is (or until interrupted or the operation times out). The `release` method returns a permit to the semaphore. (from the book [Java Concurrency in Practice](https://www.amazon.com/Java-Concurrency-Practice-Brian-Goetz/dp/0321349601))\n\nSo we use 2 Semaphore objects, one to control when the` second()` method can proceed, the other to control when the `third()` method can proceed. Solution is like below:\n\n```\nclass Foo {\n private static Semaphore sem2;\n private static Semaphore sem3;\n \n public Foo() {\n sem2 = new Semaphore(0);\n sem3 = new Semaphore(0);\n }\n\n public void first(Runnable printFirst) throws InterruptedException {\n // printFirst.run() outputs "first". Do not change or remove this line.\n printFirst.run();\n sem2.release(); // release a sem2 permit so that second() can proceed\n }\n\n public void second(Runnable printSecond) throws InterruptedException {\n sem2.acquire(); // will block until any Semaphore permit is available\n // printSecond.run() outputs "second". Do not change or remove this line.\n printSecond.run();\n sem3.release(); // release a sem3 permit so that third() can proceed\n }\n\n public void third(Runnable printThird) throws InterruptedException {\n sem3.acquire(); // will block until any Semaphore permit is available\n // printThird.run() outputs "third". Do not change or remove this line.\n printThird.run();\n }\n}\n```\n\n## 4. CountDownLatch\n`CountDownLatch` is another type of synchronizer. It can delay the progress of threads until it reaches its terminal state, i.e., when it counts down to 0. \n\nMuch like solution 3 with `Semaphore`, we use 2 `CountDownLatch` instances. One to control when the` second()` method can proceed, the other to control when the `third()` method can proceed. Solution is like below:\n\n```\nclass Foo {\n private static CountDownLatch latch2;\n private static CountDownLatch latch3;\n \n public Foo() {\n latch2 = new CountDownLatch(1);\n latch3 = new CountDownLatch(1);\n }\n\n public void first(Runnable printFirst) throws InterruptedException {\n // printFirst.run() outputs "first". Do not change or remove this line.\n printFirst.run();\n latch2.countDown(); // count down latch2 to 0 so that second() can proceed\n }\n\n public void second(Runnable printSecond) throws InterruptedException {\n latch2.await(); // wait until latch2 counts down to 0\n // printSecond.run() outputs "second". Do not change or remove this line.\n printSecond.run();\n latch3.countDown(); // count down latche to 0 so that third() can proceed\n }\n\n public void third(Runnable printThird) throws InterruptedException {\n latch3.await(); // wait until latch3 counts down to 0\n // printThird.run() outputs "third". Do not change or remove this line.\n printThird.run();\n }\n}\n```\n\nHope it helps! | 8 | 0 | [] | 2 |
print-in-order | C : semaphore-based - simple and short | c-semaphore-based-simple-and-short-by-un-w9q1 | \ntypedef struct {\n sem_t sem_a;\n sem_t sem_b;\n} Foo;\n\nFoo* fooCreate() {\n Foo* obj = malloc(sizeof (Foo));\n sem_init(&obj->sem_a, 0, 0);\n | universalcoder12 | NORMAL | 2020-03-16T08:38:24.857577+00:00 | 2020-03-16T08:38:24.857611+00:00 | 733 | false | ```\ntypedef struct {\n sem_t sem_a;\n sem_t sem_b;\n} Foo;\n\nFoo* fooCreate() {\n Foo* obj = malloc(sizeof (Foo));\n sem_init(&obj->sem_a, 0, 0);\n sem_init(&obj->sem_b, 0, 0);\n return obj;\n}\n\nvoid first(Foo* obj) {\n printFirst();\n sem_post(&obj->sem_a);\n}\n\nvoid second(Foo* obj) {\n sem_wait(&obj->sem_a);\n printSecond();\n sem_post(&obj->sem_b);\n}\n\nvoid third(Foo* obj) {\n sem_wait(&obj->sem_b);\n printThird();\n}\n\nvoid fooFree(Foo* obj) {\n free(obj);\n}\n``` | 8 | 0 | ['C'] | 1 |
print-in-order | Naive solution without using built-in libraries | naive-solution-without-using-built-in-li-vn0o | python\nclass Foo:\n def __init__(self):\n self.called = 0\n\n def first(self, printFirst: \'Callable[[], None]\') -> None:\n while self.cal | infmount | NORMAL | 2019-07-12T03:42:32.910768+00:00 | 2019-07-12T03:44:12.000766+00:00 | 973 | false | ```python\nclass Foo:\n def __init__(self):\n self.called = 0\n\n def first(self, printFirst: \'Callable[[], None]\') -> None:\n while self.called != 0:\n continue\n # printFirst() outputs "first". Do not change or remove this line.\n printFirst()\n self.called = 1\n\n\n def second(self, printSecond: \'Callable[[], None]\') -> None:\n while self.called != 1:\n continue\n # printSecond() outputs "second". Do not change or remove this line.\n printSecond()\n self.called = 2\n\n\n def third(self, printThird: \'Callable[[], None]\') -> None:\n while self.called != 2:\n continue\n # printThird() outputs "third". Do not change or remove this line.\n printThird()\n```\n\nNot sure if it meets the goal of this problem, but it passed.. | 8 | 0 | ['Python3'] | 2 |
print-in-order | C++ Mutex, Condition Variable Simple code | c-mutex-condition-variable-simple-code-b-8sy9 | Note\n\n We don\'t need any wait for printing 1. Hence, no condition variable wait\n We don\'t need to notify anyone after printing 3. Hence, no notify after pr | sam04101 | NORMAL | 2023-09-09T12:23:59.644813+00:00 | 2023-09-09T13:08:49.038855+00:00 | 1,781 | false | # Note\n\n* We don\'t need any wait for printing 1. Hence, no condition variable wait\n* We don\'t need to notify anyone after printing 3. Hence, no notify after printing 3.\n* My code doesn\'t work when I do \n`if(currentPrint!=2) cv.wait(lock)`\nbut works only when I do \n`cv.wait(lock,[&](){return currentPrint==2;});`\n\nIt is best to pass the boolean expression as part of wait. Otherwise, there is a timeout.\n\n\n# Code\n```\nclass Foo {\n condition_variable cv;\n mutex mtx;\n int currentPrint;\npublic:\n Foo() {\n currentPrint=1;\n }\n\n void first(function<void()> printFirst) {\n unique_lock<mutex>lock(mtx);\n currentPrint=2;\n printFirst();\n cv.notify_all();\n }\n\n void second(function<void()> printSecond) {\n unique_lock<mutex>lock(mtx);\n cv.wait(lock,[&](){return currentPrint==2;});\n currentPrint=3;\n printSecond();\n cv.notify_one();\n }\n\n void third(function<void()> printThird) {\n unique_lock<mutex>lock(mtx);\n cv.wait(lock,[&](){return currentPrint==3;});\n printThird();\n }\n};\n```\n\n\nPlease let me know if there are any feedbacks on this. Happy coding (^-^)\n | 7 | 0 | ['C++'] | 3 |
print-in-order | Java with two Semaphores | java-with-two-semaphores-by-dknlam-mi5y | \nclass Foo {\n\n private Semaphore second;\n private Semaphore third;\n\n public Foo() {\n second = new Semaphore(0);\n third = new Sema | dknlam | NORMAL | 2021-05-16T18:13:38.455555+00:00 | 2021-05-16T18:14:19.472337+00:00 | 519 | false | ```\nclass Foo {\n\n private Semaphore second;\n private Semaphore third;\n\n public Foo() {\n second = new Semaphore(0);\n third = new Semaphore(0);\n }\n\n public void first(Runnable printFirst) throws InterruptedException {\n // printFirst.run() outputs "first". Do not change or remove this line.\n printFirst.run();\n second.release();\n }\n\n public void second(Runnable printSecond) throws InterruptedException {\n second.acquire();\n // printSecond.run() outputs "second". Do not change or remove this line.\n printSecond.run();\n third.release();\n }\n\n public void third(Runnable printThird) throws InterruptedException {\n third.acquire();\n // printThird.run() outputs "third". Do not change or remove this line.\n printThird.run();\n }\n}\n``` | 7 | 0 | [] | 1 |
print-in-order | [Java] 94% runtime efficiency, using synchronized, wait and notify, explained | java-94-runtime-efficiency-using-synchro-hwuo | Although I consider myself proficient in Java, this was a great refresher on synchronized, wait, and notify. I did some research. Based on Sonar, any wait() c | janinbv | NORMAL | 2020-12-06T08:02:22.897223+00:00 | 2020-12-11T10:03:20.222217+00:00 | 2,217 | false | Although I consider myself proficient in Java, this was a great refresher on synchronized, wait, and notify. I did some research. Based on Sonar, any wait() call should check a condition in a while loop, so I have two booleans to indicate if the first and second have been printed. I declared two objects, firstObject and secondObject to use for synchronization. Method first synchronizes on firstObject and can then run printFirst(), and does a notify on firstObject to signal completion of the first method. Method second is synchronized on firstObject, has a while loop on !first, and waits for the notify on firstObject. When the while loop is exited, it synchronizes on secondObject, prints second, sets second to true, and does a notify on secondObject to signal completion of the second method. Method third does the same things, synchronizing on secondObject, looping while !second, and waits for the notify on secondObject. When the loop is exited, printThird can be run. \n\nIf you like this post, please upvote!\n```\nclass Foo {\n\n public Foo() {\n first = false;\n second = false;\n }\n\n Object firstObject = new Object();\n Object secondObject = new Object();\n \n boolean first = false;\n boolean second = false;\n \n public void first(Runnable printFirst) throws InterruptedException {\n synchronized(firstObject) {\n\t\t // printFirst.run() outputs "first". Do not change or remove this line.\n printFirst.run();\n first = true;\n firstObject.notify();\n }\n }\n\n public void second(Runnable printSecond) throws InterruptedException {\n synchronized(firstObject) {\n while (!first) {\n try {\n // Calling wait() will block this thread until another thread calls notify() on the object.\n firstObject.wait();\n } catch (InterruptedException e) {\n // Happens if someone interrupts your thread.\n }\n }\n synchronized(secondObject) {\n // printSecond.run() outputs "second". Do not change or remove this line.\n printSecond.run();\n second = true;\n secondObject.notify();\n }\n }\n }\n\n public void third(Runnable printThird) throws InterruptedException {\n synchronized(secondObject) {\n while (!second) {\n try {\n // Calling wait() will block this thread until another thread calls notify() on the object.\n secondObject.wait(); \n } catch (InterruptedException e) {\n // Happens if someone interrupts your thread.\n }\n }\n }\n // printThird.run() outputs "third". Do not change or remove this line\n printThird.run();\n }\n} | 7 | 1 | ['Java'] | 2 |
print-in-order | Boring C++ mutex solution | boring-c-mutex-solution-by-casd82-4l72 | \nclass Foo {\n mutex m1;\n mutex m2;\npublic:\n Foo() {\n m1.lock();\n m2.lock();\n }\n\n void first(function<void()> printFirst) | casd82 | NORMAL | 2020-07-30T01:58:55.132823+00:00 | 2020-07-30T01:58:55.132874+00:00 | 924 | false | ```\nclass Foo {\n mutex m1;\n mutex m2;\npublic:\n Foo() {\n m1.lock();\n m2.lock();\n }\n\n void first(function<void()> printFirst) {\n \n // printFirst() outputs "first". Do not change or remove this line.\n printFirst();\n m1.unlock();\n }\n\n void second(function<void()> printSecond) {\n m1.lock();\n // printSecond() outputs "second". Do not change or remove this line.\n printSecond();\n m1.unlock();\n m2.unlock();\n }\n\n void third(function<void()> printThird) {\n m2.lock();\n // printThird() outputs "third". Do not change or remove this line.\n printThird();\n m2.unlock();\n }\n};\n``` | 7 | 1 | ['C'] | 1 |
print-in-order | [JAVA] Simple solution | java-simple-solution-by-ikisis-ojtd | \nclass Foo {\n \n CountDownLatch latchForSecond = new CountDownLatch(1);\n CountDownLatch latchForThird = new CountDownLatch(1);\n\n public Foo() { | ikisis | NORMAL | 2020-07-24T01:55:41.391579+00:00 | 2020-07-24T01:56:33.975101+00:00 | 954 | false | ```\nclass Foo {\n \n CountDownLatch latchForSecond = new CountDownLatch(1);\n CountDownLatch latchForThird = new CountDownLatch(1);\n\n public Foo() {\n \n }\n\n public void first(Runnable printFirst) throws InterruptedException {\n // printFirst.run() outputs "first". Do not change or remove this line.\n printFirst.run();\n latchForSecond.countDown();\n }\n\n public void second(Runnable printSecond) throws InterruptedException {\n latchForSecond.await();\n // printSecond.run() outputs "second". Do not change or remove this line.\n printSecond.run();\n latchForThird.countDown();\n }\n\n public void third(Runnable printThird) throws InterruptedException {\n latchForThird.await();\n // printThird.run() outputs "third". Do not change or remove this line.\n printThird.run();\n }\n}\n``` | 7 | 1 | ['Java'] | 0 |
print-in-order | C++ future-promise | c-future-promise-by-jd-eth-uofd | Using C++ 11 feature and locking the object automatically with future-promise idiom. \n\n\nclass Foo {\npublic:\n Foo() {\n \n }\n std::promise< | jd-eth | NORMAL | 2020-02-25T19:17:19.852607+00:00 | 2020-02-25T19:17:19.852655+00:00 | 685 | false | Using C++ 11 feature and locking the object automatically with future-promise idiom. \n\n```\nclass Foo {\npublic:\n Foo() {\n \n }\n std::promise<void> one, two;\n \n void first(function<void()> printFirst) {\n printFirst();\n one.set_value();\n }\n\n void second(function<void()> printSecond) {\n one.get_future().get();\n printSecond();\n two.set_value();\n }\n\n void third(function<void()> printThird) {\n two.get_future().get();\n printThird();\n\n }\n};\n``` | 7 | 0 | [] | 0 |
print-in-order | C#: 2 solutions with or without thread | c-2-solutions-with-or-without-thread-by-6mwr6 | 1 with thead\n\npublic class Foo {\n\n int count;\n public Foo() {\n count = 0;\n }\n\n public void First(Action printFirst) {\n // pr | code4happy | NORMAL | 2019-07-31T05:09:46.465269+00:00 | 2019-07-31T05:09:46.465303+00:00 | 1,169 | false | #1 with thead\n```\npublic class Foo {\n\n int count;\n public Foo() {\n count = 0;\n }\n\n public void First(Action printFirst) {\n // printFirst() outputs "first". Do not change or remove this line.\n printFirst();\n count++;\n }\n\n public void Second(Action printSecond) {\n // printSecond() outputs "second". Do not change or remove this line.\n while(count < 1) System.Threading.Thread.Sleep(1);\n printSecond();\n count++;\n }\n\n public void Third(Action printThird) {\n while(count < 2) System.Threading.Thread.Sleep(1);\n // printThird() outputs "third". Do not change or remove this line.\n printThird();\n }\n}\n```\n\n#2 without thread\n```\npublic class Foo {\n\n int count;\n public Foo() {\n count = 0;\n }\n\n public void First(Action printFirst) {\n // printFirst() outputs "first". Do not change or remove this line.\n printFirst();\n count++;\n }\n\n public void Second(Action printSecond) {\n // printSecond() outputs "second". Do not change or remove this line.\n while(count < 1) continue;\n printSecond();\n count++;\n }\n\n public void Third(Action printThird) {\n while(count < 2) continue;\n // printThird() outputs "third". Do not change or remove this line.\n printThird();\n }\n}\n``` | 7 | 1 | [] | 3 |
print-in-order | Different python threading solutions (Lock, Barrier, Events, Semaphore, Condition) with explanation | different-python-threading-solutions-loc-0otq | \nStart with two locked locks. First thread unlocks the first lock that the second thread is waiting on. Second thread unlocks the second lock that the third th | aswin_m | NORMAL | 2024-05-11T05:20:54.840304+00:00 | 2024-05-11T05:20:54.840336+00:00 | 721 | false | \nStart with two locked locks. First thread unlocks the first lock that the second thread is waiting on. Second thread unlocks the second lock that the third thread is waiting on.\n\n# code\n```\nfrom threading import Lock\n\nclass Foo:\n def __init__(self):\n self.locks = (Lock(),Lock())\n self.locks[0].acquire()\n self.locks[1].acquire()\n \n def first(self, printFirst):\n printFirst()\n self.locks[0].release()\n \n def second(self, printSecond):\n with self.locks[0]:\n printSecond()\n self.locks[1].release()\n \n \n def third(self, printThird):\n with self.locks[1]:\n printThird()\n```\nRaise two barriers. Both wait for two threads to reach them.\n\nFirst thread can print before reaching the first barrier. Second thread can print before reaching the second barrier. Third thread can print after the second barrier.\n\n# code\n```\nfrom threading import Barrier\n\nclass Foo:\n def __init__(self):\n self.First_barrier = Barrier(2)\n self.Second_barrier = Barrier(2)\n \n def first(self, printFirst):\n printFirst()\n self.First_barrier.wait()\n \n def second(self, printSecond):\n self.First_barrier.wait()\n printSecond()\n self.Second_barrier.wait()\n \n def third(self, printThird):\n self.Second_barrier.wait()\n printThird()\n```\nSet events from first and second threads when they are done. Have the second thread wait for first one to set its event. Have the third thread wait on the second thread to raise its event.\n\n# code\n```\nfrom threading import Event\n\nclass Foo:\n def __init__(self):\n self.events = (Event(),Event())\n \n def first(self, printFirst):\n printFirst()\n self.events[0].set()\n \n def second(self, printSecond):\n self.events[0].wait()\n printSecond()\n self.events[1].set()\n \n def third(self, printThird):\n self.events[1].wait()\n printThird()\n```\nStart with two closed gates represented by 0-value semaphores. Second and third thread are waiting behind these gates. When the first thread prints, it opens the gate for the second thread. When the second thread prints, it opens the gate for the third thread.\n\n# code\n```\nfrom threading import Semaphore\n\nclass Foo:\n def __init__(self):\n self.gates = (Semaphore(0),Semaphore(0))\n \n def first(self, printFirst):\n printFirst()\n self.gates[0].release()\n \n def second(self, printSecond):\n with self.gates[0]:\n printSecond()\n self.gates[1].release()\n \n def third(self, printThird):\n with self.gates[1]:\n printThird()\n```\nHave all three threads attempt to acquire an RLock via Condition. The first thread can always acquire a lock, while the other two have to wait for the order to be set to the right value. First thread sets the order after printing which signals for the second thread to run. Second thread does the same for the third.\n\n# code\n```\nfrom threading import Condition\n\nclass Foo:\n def __init__(self):\n self.exec_condition = Condition()\n self.order = 0\n self.first_finish = lambda: self.order == 1\n self.second_finish = lambda: self.order == 2\n\n def first(self, printFirst):\n with self.exec_condition:\n printFirst()\n self.order = 1\n self.exec_condition.notify(2)\n\n def second(self, printSecond):\n with self.exec_condition:\n self.exec_condition.wait_for(self.first_finish)\n printSecond()\n self.order = 2\n self.exec_condition.notify()\n\n def third(self, printThird):\n with self.exec_condition:\n self.exec_condition.wait_for(self.second_finish)\n printThird() | 6 | 0 | ['Python3'] | 2 |
print-in-order | Using Manual Reset Event Set/Wait Methods | using-manual-reset-event-setwait-methods-htyn | Intuition\nWe need to synchronize the method execution in multi threaded environment so same can be achived using ManualResetEventslim class. \n\n# Approach\nW | aroraneha | NORMAL | 2023-01-02T21:05:42.871157+00:00 | 2023-01-02T21:05:42.871201+00:00 | 1,470 | false | # Intuition\nWe need to synchronize the method execution in multi threaded environment so same can be achived using ManualResetEventslim class. \n\n# Approach\nWe can have two slim events, one to synchronize the call for first and second method to ensure that first always executed before second method. \nAnd second slim event is to make sure that second method gets executed before the third method. \nSo, we can intialize these instance in the constructions with disabled state. Till the time we enable them by calling Set method. The thread will wait on Wait method. \nAfter priting first, we can set the first slim event. If a thread is waiting at Wait method in second method will get notified about its status change and now will resume its work. Same will happen for second slim event. \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```\nusing System.Threading;\n\npublic class Foo {\n\n public ManualResetEventSlim slimEvent { get; set; }\n public ManualResetEventSlim secondslimEvent { get; set; }\n\n public Foo() \n {\n slimEvent = new ManualResetEventSlim(false);\n secondslimEvent = new ManualResetEventSlim(false);\n }\n\n public void First(Action printFirst) \n {\n // printFirst() outputs "first". Do not change or remove this line.\n printFirst();\n slimEvent.Set();\n }\n\n public void Second(Action printSecond) \n {\n slimEvent.Wait();\n \n // printSecond() outputs "second". Do not change or remove this line.\n printSecond();\n secondslimEvent.Set();\n }\n\n public void Third(Action printThird) \n {\n secondslimEvent.Wait();\n // printThird() outputs "third". Do not change or remove this line.\n printThird();\n }\n}\n``` | 6 | 0 | ['C#'] | 1 |
print-in-order | c 0ms 100% | c-0ms-100-by-willdufault-eyr0 | \n\ntypedef struct\n{\n // User defined data may be declared here.\n int turn;\n pthread_mutex_t lock;\n pthread_cond_t cond;\n} Foo;\n\nFoo* fooCre | willdufault | NORMAL | 2022-10-18T03:58:09.231758+00:00 | 2022-10-18T03:58:09.231803+00:00 | 802 | false | \n```\ntypedef struct\n{\n // User defined data may be declared here.\n int turn;\n pthread_mutex_t lock;\n pthread_cond_t cond;\n} Foo;\n\nFoo* fooCreate()\n{\n Foo* obj = (Foo*) malloc(sizeof(Foo));\n // Initialize user defined data here.\n // init mutex and cond\n pthread_mutex_init(&(obj->lock), NULL);\n pthread_cond_init(&(obj->cond), NULL);\n obj->turn = 1;\n return obj;\n}\n\nvoid first(Foo* obj)\n{\n // take lock\n pthread_mutex_lock(&(obj->lock));\n // while not my turn\n while(obj->turn != 1)\n {\n // wait and unlock\n pthread_cond_wait(&(obj->cond), &(obj->lock)); \n }\n // printFirst() outputs "first". Do not change or remove this line.\n printFirst();\n obj->turn = 2;\n // unlock\n pthread_mutex_unlock(&(obj->lock));\n // broadcast\n pthread_cond_broadcast(&(obj->cond));\n}\n\nvoid second(Foo* obj)\n{\n pthread_mutex_lock(&(obj->lock)); \n while(obj->turn != 2)\n {\n pthread_cond_wait(&(obj->cond), &(obj->lock));\n }\n // printSecond() outputs "second". Do not change or remove this line.\n printSecond();\n obj->turn = 3;\n pthread_mutex_unlock(&(obj->lock));\n pthread_cond_broadcast(&(obj->cond));\n}\n\nvoid third(Foo* obj)\n{ \n pthread_mutex_lock(&(obj->lock)); \n while(obj->turn != 3)\n {\n pthread_cond_wait(&(obj->cond), &(obj->lock)); \n }\n // printThird() outputs "third". Do not change or remove this line.\n printThird();\n obj->turn = 1;\n pthread_mutex_unlock(&(obj->lock));\n pthread_cond_broadcast(&(obj->cond));\n}\n\nvoid fooFree(Foo* obj)\n{\n // User defined data may be cleaned up here.\n free(obj);\n}\n```\n\u2B06\uFE0Fplease upvote if helpful :)\u2B06\uFE0F | 6 | 0 | ['C'] | 0 |
print-in-order | Semaphore | semaphore-by-hobiter-rusi | \nclass Foo {\n Semaphore run2, run3;\n\n public Foo() {\n run2 = new Semaphore(0);\n run3 = new Semaphore(0);\n }\n\n public void fir | hobiter | NORMAL | 2020-02-22T04:10:18.290067+00:00 | 2020-02-22T04:10:18.290102+00:00 | 551 | false | ```\nclass Foo {\n Semaphore run2, run3;\n\n public Foo() {\n run2 = new Semaphore(0);\n run3 = new Semaphore(0);\n }\n\n public void first(Runnable printFirst) throws InterruptedException {\n \n // printFirst.run() outputs "first". Do not change or remove this line.\n printFirst.run();\n run2.release();\n\n }\n\n public void second(Runnable printSecond) throws InterruptedException {\n run2.acquire();\n // printSecond.run() outputs "second". Do not change or remove this line.\n printSecond.run();\n run3.release();\n }\n\n public void third(Runnable printThird) throws InterruptedException {\n run3.acquire();\n // printThird.run() outputs "third". Do not change or remove this line.\n printThird.run();\n }\n}\n\n``` | 6 | 0 | [] | 1 |
print-in-order | python3 solution via threading.Event | 36 ms 13 MB | python3-solution-via-threadingevent-36-m-oayj | \nfrom threading import Event\n\n\nclass Foo:\n def __init__(self):\n\t\t# Initialize events for threads\n self.event1 = Event()\n self.event2 | kuderr | NORMAL | 2019-11-30T19:30:34.167237+00:00 | 2020-07-06T12:57:38.417575+00:00 | 1,447 | false | ```\nfrom threading import Event\n\n\nclass Foo:\n def __init__(self):\n\t\t# Initialize events for threads\n self.event1 = Event()\n self.event2 = Event()\n \n\n def first(self, printFirst: \'Callable[[], None]\') -> None:\n printFirst()\n\t\t# set flag\n self.event1.set()\n\n\n def second(self, printSecond: \'Callable[[], None]\') -> None:\n # wait for flag\n\t\tself.event1.wait()\n printSecond()\n\t\t# set flag\n self.event2.set()\n\n\n def third(self, printThird: \'Callable[[], None]\') -> None:\n # wait for flag\n\t\tself.event2.wait()\n printThird()\n``` | 6 | 0 | ['Python', 'Python3'] | 2 |
print-in-order | [C# ] AutoResetEvent (Beats 100%) | c-autoresetevent-beats-100-by-vaibhavdan-nmwc | \n public class Foo\n {\n private static AutoResetEvent event_1 = new AutoResetEvent(false);\n private static AutoResetEvent event_2 = new A | vaibhavdandekar | NORMAL | 2019-11-13T11:10:59.350687+00:00 | 2019-11-13T11:11:31.276195+00:00 | 609 | false | ```\n public class Foo\n {\n private static AutoResetEvent event_1 = new AutoResetEvent(false);\n private static AutoResetEvent event_2 = new AutoResetEvent(false);\n public Foo()\n {\n\n }\n\n public void First(Action printFirst)\n {\n // printFirst() outputs "first". Do not change or remove this line.\n printFirst();\n event_1.Set();\n }\n\n public void Second(Action printSecond)\n {\n event_1.WaitOne();\n // printSecond() outputs "second". Do not change or remove this line.\n printSecond();\n event_2.Set();\n }\n\n public void Third(Action printThird)\n {\n event_2.WaitOne();\n // printThird() outputs "third". Do not change or remove this line.\n printThird();\n }\n }\n``` | 6 | 0 | [] | 1 |
print-in-order | C++: 🚀 😎 One-line Solution with `std::atomic` | c-one-line-solution-with-stdatomic-by-em-2vx1 | Intuition\nWe use a variable (turn) to keep track of turns.\n\n# Approach\nWe use std::atomic to prevent data race. Plus, we use yield to prevent busy waiting.\ | emadpres | NORMAL | 2023-05-11T06:16:37.686891+00:00 | 2023-05-11T06:18:39.940323+00:00 | 1,723 | false | # Intuition\nWe use a variable (`turn`) to keep track of turns.\n\n# Approach\nWe use `std::atomic` to prevent data race. Plus, we use `yield` to prevent busy waiting.\n\n# Code\n```\nclass Foo {\n std::atomic<int> turn = 1;\npublic:\n Foo() {\n \n }\n\n void first(function<void()> printFirst) {\n while(turn!=1)\n this_thread::yield();\n // printFirst() outputs "first". Do not change or remove this line.\n printFirst();\n turn++;\n }\n\n void second(function<void()> printSecond) {\n while(turn!=2)\n this_thread::yield();\n // printSecond() outputs "second". Do not change or remove this line.\n printSecond();\n turn++;\n }\n\n void third(function<void()> printThird) {\n while(turn!=3)\n this_thread::yield();\n // printThird() outputs "third". Do not change or remove this line.\n printThird();\n }\n};\n``` | 5 | 0 | ['C++'] | 1 |
print-in-order | c++ use mutex | c-use-mutex-by-hossam_hassan-wy26 | Intuition\nUse condition variable and count variable and based on the count value , the desigenated thread will be running accordingly \n\n\n\nclass Foo {\npubl | hossam_hassan | NORMAL | 2023-03-10T18:11:43.517480+00:00 | 2023-03-10T18:11:43.517520+00:00 | 2,322 | false | # Intuition\nUse condition variable and count variable and based on the count value , the desigenated thread will be running accordingly \n\n\n```\nclass Foo {\npublic:\n\n std::mutex m; \n std::condition_variable cv;\n int count; \n \n Foo():count{0} {\n \n }\n\n void first(function<void()> printFirst) {\n std::unique_lock<std::mutex> lock(m);\n\n count++;\n // printFirst() outputs "first". Do not change or remove this line.\n printFirst();\n lock.unlock(); \n cv.notify_all();\n }\n\n void second(function<void()> printSecond) {\n std::unique_lock<std::mutex> lock(m);\n cv.wait(lock , [this](){return count == 1 ? true : false;});\n // printSecond() outputs "second". Do not change or remove this line.\n printSecond();\n count++;\n lock.unlock(); \n cv.notify_all();\n\n }\n\n void third(function<void()> printThird) {\n std::unique_lock<std::mutex> lock(m);\n cv.wait(lock , [this](){return count == 2 ? true : false;});\n // printThird() outputs "third". Do not change or remove this line.\n printThird();\n lock.unlock(); \n cv.notify_all();\n }\n};\n``` | 5 | 0 | ['C++'] | 2 |
print-in-order | Easy Java Solution | easy-java-solution-by-raghavdabra-llkn | \nclass Foo {\n\n private final CountDownLatch firstLatch;\n private final CountDownLatch secondLatch;\n\n public Foo() {\n firs | raghavdabra | NORMAL | 2022-10-12T05:18:24.034369+00:00 | 2022-10-12T05:18:24.034407+00:00 | 2,224 | false | ```\nclass Foo {\n\n private final CountDownLatch firstLatch;\n private final CountDownLatch secondLatch;\n\n public Foo() {\n firstLatch = new CountDownLatch(1);\n secondLatch = new CountDownLatch(1);\n }\n\n public void first(Runnable printFirst) throws InterruptedException {\n printFirst.run();\n firstLatch.countDown();\n }\n\n public void second(Runnable printSecond) throws InterruptedException {\n firstLatch.await();\n printSecond.run();\n secondLatch.countDown();\n }\n\n public void third(Runnable printThird) throws InterruptedException {\n secondLatch.await();\n printThird.run();\n }\n }\n``` | 5 | 0 | ['Java'] | 0 |
print-in-order | Java | CountDownLatch simple solution | java-countdownlatch-simple-solution-by-j-8vl7 | \nimport java.util.concurrent.CountDownLatch;\n\nclass Foo {\n\n private final CountDownLatch firstLatch = new CountDownLatch(1);\n private final CountDow | JKonSir | NORMAL | 2022-03-29T12:50:55.849252+00:00 | 2022-03-29T12:51:15.449271+00:00 | 714 | false | ```\nimport java.util.concurrent.CountDownLatch;\n\nclass Foo {\n\n private final CountDownLatch firstLatch = new CountDownLatch(1);\n private final CountDownLatch secondLatch = new CountDownLatch(1);\n\n public Foo() {\n\n }\n\n public void first(Runnable printFirst) throws InterruptedException {\n // printFirst.run() outputs "first". Do not change or remove this line.\n printFirst.run();\n \n firstLatch.countDown();\n }\n\n public void second(Runnable printSecond) throws InterruptedException {\n firstLatch.await();\n // printSecond.run() outputs "second". Do not change or remove this line.\n printSecond.run();\n \n secondLatch.countDown();\n }\n\n public void third(Runnable printThird) throws InterruptedException {\n secondLatch.await();\n // printThird.run() outputs "third". Do not change or remove this line.\n printThird.run();\n }\n}\n``` | 5 | 0 | ['Java'] | 0 |
print-in-order | C++ SHORTEST CODE USING PROMISE CLASS | c-shortest-code-using-promise-class-by-a-9vt9 | \nclass Foo {\n \nprivate: \n promise<void> p1, p2; \n \npublic:\n Foo() {}\n void first(function<void()> printFirst) {\n pr | akarshj950 | NORMAL | 2022-03-06T13:11:13.831235+00:00 | 2022-03-06T13:11:13.831268+00:00 | 559 | false | ```\nclass Foo {\n \nprivate: \n promise<void> p1, p2; \n \npublic:\n Foo() {}\n void first(function<void()> printFirst) {\n printFirst() ;\n p1.set_value() ;\n }\n void second(function<void()> printSecond) {\n p1.get_future().wait() ;\n printSecond() ;\n p2.set_value() ;}\n\n void third(function<void()> printThird) {\n p2.get_future().wait() ;\n printThird() ;}\n};\n``` | 5 | 0 | ['C'] | 1 |
print-in-order | Simple python solution | simple-python-solution-by-radhadman-0u5y | \nclass Foo(object):\n def __init__(self):\n self.x = 0\n \n def first(self, printFirst):\n printFirst()\n self.x += 1\n\n | radhadman | NORMAL | 2021-04-03T18:36:49.398340+00:00 | 2021-04-03T18:36:49.398379+00:00 | 794 | false | ```\nclass Foo(object):\n def __init__(self):\n self.x = 0\n \n def first(self, printFirst):\n printFirst()\n self.x += 1\n\n def second(self, printSecond):\n while self.x < 1:\n pass\n printSecond()\n self.x += 1\n \n def third(self, printThird):\n while self.x < 2:\n pass\n printThird()\n``` | 5 | 0 | [] | 1 |
print-in-order | Python - using events | python-using-events-by-samirdeeb-5mh5 | \nclass Foo:\n def __init__(self):\n self.first_event = threading.Event()\n self.second_event = threading.Event()\n \n def first(self, | samirdeeb | NORMAL | 2021-01-02T04:28:14.201459+00:00 | 2021-01-02T04:28:14.201490+00:00 | 875 | false | ```\nclass Foo:\n def __init__(self):\n self.first_event = threading.Event()\n self.second_event = threading.Event()\n \n def first(self, printFirst: \'Callable[[], None]\') -> None:\n # printFirst() outputs "first". Do not change or remove this line.\n printFirst()\n self.first_event.set()\n\n\n def second(self, printSecond: \'Callable[[], None]\') -> None:\n self.first_event.wait()\n # printSecond() outputs "second". Do not change or remove this line.\n printSecond()\n self.second_event.set()\n \n\n def third(self, printThird: \'Callable[[], None]\') -> None:\n self.second_event.wait()\n # printThird() outputs "third". Do not change or remove this line.\n printThird()\n``` | 5 | 0 | ['Python3'] | 0 |
print-in-order | Java solution with synchronized methods | java-solution-with-synchronized-methods-he5zw | Code with a runtime of 10ms :\n\n\nclass Foo {\n public int count;\n \n public Foo() {\n this.count = 1;\n }\n\n synchronized public void | abdus-samee | NORMAL | 2020-08-24T10:02:45.552761+00:00 | 2020-08-24T10:02:45.552808+00:00 | 1,224 | false | Code with a runtime of 10ms :\n\n```\nclass Foo {\n public int count;\n \n public Foo() {\n this.count = 1;\n }\n\n synchronized public void first(Runnable printFirst) throws InterruptedException {\n while(count != 1) wait();\n \n // printFirst.run() outputs "first". Do not change or remove this line.\n printFirst.run();\n this.count++;\n notifyAll();\n }\n\n synchronized public void second(Runnable printSecond) throws InterruptedException {\n while(this.count != 2) wait();\n \n // printSecond.run() outputs "second". Do not change or remove this line.\n printSecond.run();\n this.count++;\n notifyAll();\n }\n\n synchronized public void third(Runnable printThird) throws InterruptedException {\n while(this.count != 3) wait();\n \n // printThird.run() outputs "third". Do not change or remove this line.\n printThird.run();\n this.count++;\n notifyAll();\n }\n}\n``` | 5 | 1 | ['Java'] | 2 |
print-in-order | Accepted C# using AutoResetEvent | accepted-c-using-autoresetevent-by-maxpu-3puk | \nusing System.Threading; \n\npublic class Foo\n {\n private EventWaitHandle _waitFirst;\n private EventWaitHandle _waitSecond;\n\n p | maxpushkarev | NORMAL | 2019-10-11T06:15:20.300559+00:00 | 2019-10-11T06:15:20.300590+00:00 | 437 | false | ```\nusing System.Threading; \n\npublic class Foo\n {\n private EventWaitHandle _waitFirst;\n private EventWaitHandle _waitSecond;\n\n public Foo()\n {\n _waitFirst = new AutoResetEvent(false);\n _waitSecond = new AutoResetEvent(false);\n }\n\n public void First(Action printFirst)\n {\n\n // printFirst() outputs "first". Do not change or remove this line.\n printFirst();\n _waitFirst.Set();\n }\n\n public void Second(Action printSecond)\n {\n _waitFirst.WaitOne();\n // printSecond() outputs "second". Do not change or remove this line.\n printSecond();\n _waitSecond.Set();\n }\n\n public void Third(Action printThird)\n {\n _waitSecond.WaitOne();\n // printThird() outputs "third". Do not change or remove this line.\n printThird();\n }\n }\n``` | 5 | 0 | [] | 3 |
print-in-order | Simple Java Solution using booleans for locking | simple-java-solution-using-booleans-for-gwdry | class Foo {\n \n private volatile boolean executedFirst,executedSecond;\n public Foo() {}\n \n public void first(Runnable printFirst) | ping_pong | NORMAL | 2019-09-07T05:41:17.023848+00:00 | 2019-09-07T05:41:17.023894+00:00 | 1,026 | false | class Foo {\n \n private volatile boolean executedFirst,executedSecond;\n public Foo() {}\n \n public void first(Runnable printFirst) throws InterruptedException {\n executedFirst = true;\n printFirst.run();\n }\n \n public void second(Runnable printSecond) throws InterruptedException {\n \n while (!executedFirst);\n executedSecond = true;\n printSecond.run();\n }\n \n public void third(Runnable printThird) throws InterruptedException {\n while (!executedSecond);\n printThird.run();\n } | 5 | 0 | [] | 1 |
print-in-order | Java solution using wait() and notifyAll() | java-solution-using-wait-and-notifyall-b-pdfk | A lot of solutions on here are using busy waits or sleeps - which are only slightly better. That is essentially a \'fail\' w.r.t. this question on threads. Here | alexworden | NORMAL | 2019-08-30T15:49:11.179957+00:00 | 2019-08-30T15:53:59.707868+00:00 | 568 | false | A lot of solutions on here are using busy waits or sleeps - which are only slightly better. That is essentially a \'fail\' w.r.t. this question on threads. Here\'s the solution I believe an interviewer would be looking for that uses wait() and notifyAll() with a liveness check inside a synchronized block. The locking object instance used in this code is the instance of Foo. I.e. \'this\'. Using wait() and notifyAll() means that the processors aren\'t spinning and unnecessarily burning through compute power! \n\nAlso - notice that the thread coordination logic happens inside a synchronized block. Without that, there is no guarantee that the JVM memory model will communicate the state of the variables between threads. Always, put this kind of thread-coordination logic inside synchronized blocks. \n\nAlso - the Java seed code for this question is incorrectly using the Runnable interface. You never call run() on a runnable! That is for the JVM to call in a new thread when it is started. \n\n```\nclass Foo {\n private boolean firstDone = false;\n private boolean secondDone = false;\n \n public Foo() {\n \n }\n\n public void first(Runnable printFirst) throws InterruptedException {\n synchronized(this) {\n // printFirst.run() outputs "first". Do not change or remove this line.\n printFirst.run();\n firstDone = true;\n this.notifyAll();\n }\n }\n\n public void second(Runnable printSecond) throws InterruptedException {\n synchronized(this) {\n while (!firstDone) {\n this.wait();\n }\n // printSecond.run() outputs "second". Do not change or remove this line.\n printSecond.run();\n this.secondDone = true;\n this.notifyAll();\n }\n }\n\n public void third(Runnable printThird) throws InterruptedException {\n synchronized(this) {\n while (!secondDone) {\n this.wait();\n }\n // printThird.run() outputs "third". Do not change or remove this line.\n printThird.run();\n this.notifyAll();\n }\n }\n}\n```\n | 5 | 0 | [] | 1 |
print-in-order | Java compareAndSet() | java-compareandset-by-tianchi-seattle-7d9t | java\nimport java.util.concurrent.atomic.AtomicInteger;\nclass Foo {\n\n private AtomicInteger integer;\n \n public Foo() {\n integer = new Atom | tianchi-seattle | NORMAL | 2019-07-31T02:51:10.104503+00:00 | 2019-07-31T02:51:10.104534+00:00 | 839 | false | ```java\nimport java.util.concurrent.atomic.AtomicInteger;\nclass Foo {\n\n private AtomicInteger integer;\n \n public Foo() {\n integer = new AtomicInteger(); \n }\n\n public void first(Runnable printFirst) throws InterruptedException {\n while(!integer.compareAndSet(0, 1));\n printFirst.run();\n }\n\n public void second(Runnable printSecond) throws InterruptedException {\n while(!integer.compareAndSet(1, 2));\n printSecond.run();\n }\n\n public void third(Runnable printThird) throws InterruptedException {\n while(!integer.compareAndSet(2, 3));\n printThird.run();\n }\n}\n``` | 5 | 2 | [] | 5 |
print-in-order | Four approaches: Passive vs Active Blocking | four-approaches-passive-vs-active-blocki-b5xw | Approach #1: Condition specific mutexes\nThis approach uses a mutex for each of the two dependent function calls. At the beginning, all the locks are claimed in | hnorth99 | NORMAL | 2024-02-18T21:58:26.594900+00:00 | 2024-02-18T21:58:26.594930+00:00 | 92 | false | Approach #1: Condition specific mutexes\nThis approach uses a mutex for each of the two dependent function calls. At the beginning, all the locks are claimed in the constructor. This ensures that none of the funcitons of requiring a lock are able to grasp or get ownership of the mutex. When they attempt to (with their .lock() call, their thread is blocked until that mutex is released. The only way a mutex can be released is with a call to .unlock, which is called at the end of first. So when first finishes executing, then the lock can finally be aquired by second (with the call to .lock). This function then releases the third lock so that the third_lock mutex can be aquired by third, and the flow can finish. The downside to this approach is that second and third functions are using busy-waitting/active-waitting/spinning for unlocking, meaning that the threads will continue to consume CPU resources actively while waitting. For more detail, this poor waitting mechanism requires the thread to repeatedly check a condition in a loop waitting for some event to occur -- which doesn\'t relinquish control of the cpu. The advantage of active waitting is that it leads to very fast response times for the thread to re-initiate (as it doesn\'t have to endure the overhead of being put to sleep and then woken up again).\n\n```\nclass Foo {\npublic:\n mutex second_lock;\n mutex third_lock;\n\n Foo() {\n second_lock.lock();\n third_lock.lock(); \n }\n\n void first(function<void()> printFirst) { \n printFirst();\n second_lock.unlock();\n }\n\n void second(function<void()> printSecond) {\n second_lock.lock();\n // printSecond() outputs "second". Do not change or remove this line.\n printSecond();\n third_lock.unlock();\n }\n\n void third(function<void()> printThird) {\n third_lock.lock();\n // printThird() outputs "third". Do not change or remove this line.\n printThird();\n \n }\n};\n```\nApproach #2: Condition variables\nInstead of relying on a mutex for each of the dependent functions, the dependent functions are blocked by condition variables. This utilizes the passive waitting approach so that the waits on the second and third function relinquish cpu control -- hence conserving resources to be utilized on other active threads. \nPlease note that the condition_variables still require a mutex for several reasons\n1. Protecting access to shared data. \nIt is important to note that we still would want synchronization to the writes to the shared memory between the different threads using this object. Relevant to updating first_exec and second_exec.\n2. Atomicity of wait operations\nThe wait operations are reading from shared memory. So, before accessing this shared memory, we want to ensure that the boolean check is on fresh/protected memory. Once the check is performed, the cv wait function is then able to give up the lock until it is signaled to wake up again and re-aqquire the lock. If this action was not atomic, it is possible that the signal to re-perform the check as the conditional variable might not be in a waitting state. This is commonly referred to as a lost wakeup.\n\n```\nclass Foo {\npublic:\n mutex m;\n condition_variable cv2, cv3;\n bool first_exec, second_exec;\n\n Foo() {\n first_exec = false;\n second_exec = false;\n }\n\n void first(function<void()> printFirst) {\n unique_lock<mutex> lock(m); \n printFirst();\n first_exec = true;\n cv2.notify_one();\n }\n\n void second(function<void()> printSecond) {\n unique_lock<mutex> lock(m);\n cv2.wait(lock, [this] { return first_exec; });\n printSecond();\n second_exec = true;\n cv3.notify_one();\n }\n\n void third(function<void()> printThird) {\n unique_lock<mutex> lock(m);\n cv3.wait(lock, [this] { return second_exec; });\n printThird();\n }\n};\n```\nApproach #3: Semaphores\nSemaphores are another synchronization pattern that allow threads to signal eachother about occurences of specific events. Each semaphore maintains a count, which is incremented by signaling ("posting" or "releasing") and decremented by waitting ("aquirring"). When a thread tries to decrement the semaphore while it\'s count is zero, the thread becomes block until another thread increments the semaphore. Please not that semaphores also use passive waitting.\n```\nclass Foo {\npublic:\n sem_t sem2, sem3;\n\n Foo() {\n \t// Note that the second argument here is referred to as the Pshared value. It specificies whether or not \n \t// the semaphore can be used across multiple processes. If it is a non-zero value, the semaphore is allocated in a shared\n \t// memory segment. If it is zero, then it is only used in the defined process. The third argument is the initialized counter \n \t// argument (so zero would mean a call to wait would block in a resource efficent manner)\n sem_init(&sem2, 0, 0);\n sem_init(&sem3, 0, 0);\n }\n\n void first(function<void()> printFirst) {\n printFirst();\n // increment/signal the semaphore so that threads trying to decrement/accquire it can continue\n sem_post(&sem2);\n }\n\n void second(function<void()> printSecond) {\n // wait until this semaphore has a postive value so we can decrement it and continue\n sem_wait(&sem2);\n printSecond();\n sem_post(&sem3);\n }\n\n void third(function<void()> printThird) {\n sem_wait(&sem3);\n printThird();\n }\n};\n```\nApproach 4: Using promises\nAnother way to implement passive waitting, using promises.\n```\nclass Foo {\npublic:\n promise<void> p2, p3;\n Foo() {\n \n }\n\n void first(function<void()> printFirst) { \n printFirst();\n p2.set_value();\n }\n\n void second(function<void()> printSecond) {\n p2.get_future().wait(); \n printSecond();\n p3.set_value();\n }\n\n void third(function<void()> printThird) {\n p3.get_future().wait(); \n printThird();\n }\n};\n``` | 4 | 0 | ['C++'] | 2 |
print-in-order | 🍞🍞🍞 Only used vector, no lock/semaphore/low-level objects | only-used-vector-no-locksemaphorelow-lev-6pho | Approach\nNot a fan of low level stuff (even for easy questions), so here\'s a solution using nothing but a vector.\n\nI made the class have a vector, printed, | TheGElCOgecko | NORMAL | 2023-05-02T03:21:49.340586+00:00 | 2023-07-07T05:41:29.195657+00:00 | 923 | false | # Approach\nNot a fan of low level stuff (even for easy questions), so here\'s a solution using nothing but a vector.\n\nI made the class have a vector, printed, which contains bool values of whether any given print function executed. Since the same instance will be passed to each thread, all threads can update this vector so that other threads can see.\n\nAdditonally, since each thread calls a different function (Thread A calls first(), Thread B second(), Thread C third()), they will all manipulate a different section of the Foo object (Thread A printed[0], Thread B printed[1], Thread C printed[2]), so race conditions are taken into account in this solution.\n\nThis solution has a high run time (beats 9.36% of solutions), and is not anything remotely like any reasonable expected solution. This solution is for the software engineers that ventured into the land of concurrency out of curiosity, like me.\n\n\n# Code\n```\nclass Foo {\nprivate:\n vector<bool> printed; // keeps track of which print funcs executed\npublic:\n Foo() : printed(3, false) {}\n\n void first(function<void()> printFirst) {\n printFirst(); // this should always print first\n printed[0] = true;\n }\n\n void second(function<void()> printSecond) {\n while (!printed[0]) {} // second will never print first, wait for first\n printSecond();\n printed[1] = true;\n }\n\n void third(function<void()> printThird) {\n // no need to explicitly wait for first, since second should never execute before first\n // besides, waiting for first and second creates a race condition, since two threads are reading the same piece of data\n while (!printed[1]) {} // wait for second\n printThird();\n printed[2] = true;\n }\n};\n```\nUPVOTE if this was helpful \uD83C\uDF5E\uD83C\uDF5E\uD83C\uDF5E | 4 | 0 | ['Array', 'Design', 'Concurrency', 'C++'] | 3 |
print-in-order | Java Solution - (Approach 1: Using Object lock, Approach 2: Using Countdown Latch) | java-solution-approach-1-using-object-lo-2i2k | Intuition\nWe need to suspend the thread printing second until first completes, and third until second completes.\n\n# Approach 1 - Using Object lock\nUse synch | mitesh_pv | NORMAL | 2023-01-22T14:53:20.755863+00:00 | 2023-01-22T14:57:37.795876+00:00 | 1,749 | false | # Intuition\nWe need to suspend the thread printing second until first completes, and third until second completes.\n\n# Approach 1 - Using Object lock\nUse `synchronsed` block to guard the block of code, and suspend the thread using `buzy waiting` method until `first`, `second` is not printed in order.\n\n\n# Code\n```java\nclass Foo {\n private int currentNum;\n\n public Foo() {\n this.currentNum = 1;\n }\n\n public void first(Runnable printFirst) throws InterruptedException {\n synchronized (this) {\n while (currentNum != 1) {\n wait();\n }\n // printFirst.run() outputs "first". Do not change or remove this line.\n printFirst.run();\n currentNum++;\n notifyAll();\n }\n }\n\n public void second(Runnable printSecond) throws InterruptedException {\n synchronized (this) {\n while (currentNum != 2) {\n wait();\n }\n // printSecond.run() outputs "second". Do not change or remove this line.\n printSecond.run();\n currentNum++;\n notifyAll();\n }\n }\n\n public void third(Runnable printThird) throws InterruptedException {\n synchronized (this) {\n while (currentNum != 3) {\n wait();\n }\n // printThird.run() outputs "third". Do not change or remove this line.\n printThird.run();\n currentNum++;\n notifyAll();\n }\n }\n}\n```\n\n\n# Approach 2 - Using CountDownLatch\nHere we make use of two countdown latches, \nthe second thread waits on first latch to countDown to 0, and third thread waits on second latch to countDown to 0.\n<br>\nThe code is self explanatory.\n\n# Code\n```java\nclass Foo {\n private CountDownLatch firstLatch;\n private CountDownLatch secondLatch;\n\n public Foo() {\n this.firstLatch = new CountDownLatch(1);\n this.secondLatch = new CountDownLatch(1);\n }\n\n public void first(Runnable printFirst) {\n printFirst.run();\n firstLatch.countDown();\n }\n\n public void second(Runnable printSecond) throws InterruptedException {\n firstLatch.await();\n printSecond.run();\n secondLatch.countDown();\n }\n\n public void third(Runnable printThird) throws InterruptedException {\n secondLatch.await();\n printThird.run();\n }\n}\n``` | 4 | 1 | ['Java'] | 0 |
print-in-order | A simple solution in Java | a-simple-solution-in-java-by-toshpolaty-0s7m | \nclass Foo {\n \n CountDownLatch second;\n CountDownLatch third;\n\n public Foo() {\n second = new CountDownLatch(1);\n third = new C | toshpolaty | NORMAL | 2022-06-13T15:04:01.971082+00:00 | 2022-06-13T15:04:01.971146+00:00 | 1,213 | false | ```\nclass Foo {\n \n CountDownLatch second;\n CountDownLatch third;\n\n public Foo() {\n second = new CountDownLatch(1);\n third = new CountDownLatch(1);\n }\n\n public void first(Runnable printFirst) throws InterruptedException {\n \n // printFirst.run() outputs "first". Do not change or remove this line.\n printFirst.run();\n second.countDown();\n }\n\n public void second(Runnable printSecond) throws InterruptedException {\n second.await();\n // printSecond.run() outputs "second". Do not change or remove this line.\n printSecond.run();\n third.countDown();\n }\n\n public void third(Runnable printThird) throws InterruptedException {\n third.await();\n // printThird.run() outputs "third". Do not change or remove this line.\n printThird.run();\n }\n}\n``` | 4 | 0 | ['Java'] | 0 |
print-in-order | Simple C++ solution with mutex | simple-c-solution-with-mutex-by-dandosh-q8bk | \nclass Foo {\npublic:\n mutex a, b;\n Foo() {\n a.lock();\n b.lock();\n }\n\n void first(function<void()> printFirst) {\n \n | dandosh | NORMAL | 2022-05-11T11:27:42.982501+00:00 | 2022-05-11T11:27:42.982534+00:00 | 456 | false | ```\nclass Foo {\npublic:\n mutex a, b;\n Foo() {\n a.lock();\n b.lock();\n }\n\n void first(function<void()> printFirst) {\n \n // printFirst() outputs "first". Do not change or remove this line.\n printFirst();\n a.unlock();\n }\n\n void second(function<void()> printSecond) {\n \n // printSecond() outputs "second". Do not change or remove this line.\n a.lock();\n printSecond();\n b.unlock();\n }\n\n void third(function<void()> printThird) {\n \n // printThird() outputs "third". Do not change or remove this line.\n b.lock();\n printThird();\n }\n};\n``` | 4 | 0 | ['C'] | 1 |
print-in-order | [Java] Simplest solution using volatile variable | java-simplest-solution-using-volatile-va-zydh | Here, volatile keyword makes the variable threadsafe and making it visible to all threads works.\n\nJava\nclass Foo {\n\n volatile int methodCompleted;\n | black_swordsman_19 | NORMAL | 2022-04-28T00:21:08.509988+00:00 | 2022-04-28T00:21:53.271815+00:00 | 1,074 | false | Here, `volatile` keyword makes the variable threadsafe and making it visible to all threads works.\n\n```Java\nclass Foo {\n\n volatile int methodCompleted;\n \n public Foo() {\n methodCompleted = 0;\n }\n\n public void first(Runnable printFirst) throws InterruptedException {\n printFirst.run();\n methodCompleted = 1;\n }\n\n public void second(Runnable printSecond) throws InterruptedException {\n while (methodCompleted != 1) ;\n printSecond.run();\n methodCompleted = 2;\n }\n\n public void third(Runnable printThird) throws InterruptedException {\n while (methodCompleted != 2) ;\n printThird.run();\n methodCompleted = 3;\n }\n}\n\n``` | 4 | 0 | ['Java'] | 2 |
print-in-order | Java Semaphore solution | java-semaphore-solution-by-xiii-th-tcdj | \nclass Foo {\n \n private final Semaphore second = new Semaphore(0);\n private final Semaphore third = new Semaphore(0);\n\n public void first(Runn | XIII-th | NORMAL | 2022-03-13T05:06:51.886666+00:00 | 2022-03-13T05:06:51.886709+00:00 | 641 | false | ```\nclass Foo {\n \n private final Semaphore second = new Semaphore(0);\n private final Semaphore third = new Semaphore(0);\n\n public void first(Runnable printFirst) throws InterruptedException {\n // printFirst.run() outputs "first". Do not change or remove this line.\n printFirst.run();\n \n second.release();\n }\n\n public void second(Runnable printSecond) throws InterruptedException {\n second.acquire();\n \n // printSecond.run() outputs "second". Do not change or remove this line.\n printSecond.run();\n \n third.release();\n }\n\n public void third(Runnable printThird) throws InterruptedException {\n third.acquire();\n \n // printThird.run() outputs "third". Do not change or remove this line.\n printThird.run();\n }\n}\n``` | 4 | 0 | ['Java'] | 0 |
print-in-order | Python simple solution without any lib | python-simple-solution-without-any-lib-b-kj4u | \tclass Foo:\n\t\tdef init(self):\n\t\t\tself.seq = 0\n\n\t\tdef first(self, printFirst: \'Callable[[], None]\') -> None:\n\t\t\tprintFirst()\n\t\t\tself.seq = | overzh_tw | NORMAL | 2021-12-16T06:30:38.805668+00:00 | 2021-12-16T06:30:38.805710+00:00 | 925 | false | \tclass Foo:\n\t\tdef __init__(self):\n\t\t\tself.seq = 0\n\n\t\tdef first(self, printFirst: \'Callable[[], None]\') -> None:\n\t\t\tprintFirst()\n\t\t\tself.seq = 1\n\n\t\tdef second(self, printSecond: \'Callable[[], None]\') -> None:\n\t\t\twhile self.seq < 1:\n\t\t\t\tcontinue\n\t\t\tprintSecond()\n\t\t\tself.seq = 2\n\n\t\tdef third(self, printThird: \'Callable[[], None]\') -> None:\n\t\t\twhile self.seq < 2:\n\t\t\t\tcontinue\n\t\t\tprintThird() | 4 | 0 | ['Python', 'Python3'] | 1 |
print-in-order | Use semaphores for C++ solution | use-semaphores-for-c-solution-by-maitrey-ltr4 | \n#include <semaphore.h>\nclass Foo {\nprotected:\n sem_t firstDone;\n sem_t secondDone;\npublic:\n Foo() {\n sem_init(&firstDone, 0, 0);\n | maitreya47 | NORMAL | 2021-11-10T22:59:26.669505+00:00 | 2021-11-10T22:59:26.669542+00:00 | 628 | false | ```\n#include <semaphore.h>\nclass Foo {\nprotected:\n sem_t firstDone;\n sem_t secondDone;\npublic:\n Foo() {\n sem_init(&firstDone, 0, 0);\n sem_init(&secondDone, 0, 0);\n }\n\n void first(function<void()> printFirst) {\n \n // printFirst() outputs "first". Do not change or remove this line.\n printFirst();\n sem_post(&firstDone);\n }\n\n void second(function<void()> printSecond) {\n sem_wait(&firstDone);\n // printSecond() outputs "second". Do not change or remove this line.\n printSecond();\n sem_post(&secondDone);\n }\n\n void third(function<void()> printThird) {\n sem_wait(&secondDone);\n // printThird() outputs "third". Do not change or remove this line.\n printThird();\n }\n};\n``` | 4 | 0 | ['C', 'C++'] | 0 |
print-in-order | Java fastest using volatile boolean and while poll | java-fastest-using-volatile-boolean-and-wblu6 | \nclass Foo {\n volatile boolean waitTwo = true;\n volatile boolean waitThree = true;\n\n public Foo() {\n \n }\n\n public void first(Runn | shashidhar71 | NORMAL | 2021-01-09T02:32:38.583774+00:00 | 2021-01-09T02:32:38.583813+00:00 | 623 | false | ```\nclass Foo {\n volatile boolean waitTwo = true;\n volatile boolean waitThree = true;\n\n public Foo() {\n \n }\n\n public void first(Runnable printFirst) throws InterruptedException {\n \n // printFirst.run() outputs "first". Do not change or remove this line.\n printFirst.run();\n waitTwo = false;\n }\n\n public void second(Runnable printSecond) throws InterruptedException {\n \n while(waitTwo){}\n \n // printSecond.run() outputs "second". Do not change or remove this line.\n printSecond.run();\n waitThree = false;\n }\n\n public void third(Runnable printThird) throws InterruptedException {\n \n while(waitThree){}\n \n // printThird.run() outputs "third". Do not change or remove this line.\n printThird.run();\n }\n}\n``` | 4 | 1 | [] | 0 |
print-in-order | Py3 Runtime: 32 ms, faster than 93.93% | py3-runtime-32-ms-faster-than-9393-by-kk-w34b | Using thread lock and lock first and second first at the begining, then release first when printFirst being called, and release second when printSecond being ca | kkfnpdc123 | NORMAL | 2020-10-23T12:07:56.455389+00:00 | 2020-10-23T12:08:31.798894+00:00 | 690 | false | Using thread lock and lock `first` and `second` first at the begining, then release `first` when `printFirst` being called, and release `second` when `printSecond` being called. After all `printThird` will be called.\n\n```class Foo:\n def __init__(self):\n self.tl1 = threading.Lock()\n self.tl2 = threading.Lock()\n self.tl1.acquire()\n self.tl2.acquire()\n\n\n def first(self, printFirst: \'Callable[[], None]\') -> None:\n # printFirst() outputs "first". Do not change or remove this line.\n printFirst()\n self.tl1.release()\n\n\n def second(self, printSecond: \'Callable[[], None]\') -> None:\n self.tl1.acquire()\n # printSecond() outputs "second". Do not change or remove this line.\n printSecond()\n self.tl2.release()\n\n\n def third(self, printThird: \'Callable[[], None]\') -> None:\n self.tl2.acquire()\n # printThird() outputs "third". Do not change or remove this line.\n printThird()\n ```\n\t\t | 4 | 0 | ['Python3'] | 1 |
print-in-order | python loop and flag | python-loop-and-flag-by-karthikasasanka-f5lk | \nclass Foo:\n def __init__(self):\n self.f = True\n self.s = False\n self.t = False\n\n\n def first(self, printFirst: \'Callable[[], | karthikasasanka | NORMAL | 2020-08-07T06:29:46.065691+00:00 | 2020-08-07T06:29:46.065734+00:00 | 260 | false | ```\nclass Foo:\n def __init__(self):\n self.f = True\n self.s = False\n self.t = False\n\n\n def first(self, printFirst: \'Callable[[], None]\') -> None:\n \n # printFirst() outputs "first". Do not change or remove this line.\n printFirst()\n self.s = True\n\n\n def second(self, printSecond: \'Callable[[], None]\') -> None:\n \n # printSecond() outputs "second". Do not change or remove this line.\n while 1:\n if self.s:\n break\n printSecond()\n self.t = True\n\n\n def third(self, printThird: \'Callable[[], None]\') -> None:\n \n # printThird() outputs "third". Do not change or remove this line.\n while 1:\n if self.t:\n break\n printThird()\n``` | 4 | 0 | [] | 0 |
print-in-order | Java Simple Solution using volatile (97% faster) | java-simple-solution-using-volatile-97-f-ms98 | \nclass Foo {\n\n public volatile int order;\n public Foo() {\n order= 0;\n }\n\n public void first(Runnable printFirst) throws InterruptedEx | shubhamk2700 | NORMAL | 2020-08-02T17:28:54.281174+00:00 | 2020-08-02T17:28:54.281234+00:00 | 310 | false | ```\nclass Foo {\n\n public volatile int order;\n public Foo() {\n order= 0;\n }\n\n public void first(Runnable printFirst) throws InterruptedException {\n // printFirst.run() outputs "first". Do not change or remove this line.\n printFirst.run();\n order++;\n }\n\n public void second(Runnable printSecond) throws InterruptedException {\n while(order!=1);\n // printSecond.run() outputs "second". Do not change or remove this line.\n printSecond.run();\n order++;\n }\n\n public void third(Runnable printThird) throws InterruptedException {\n while(order!=2);\n // printThird.run() outputs "third". Do not change or remove this line.\n printThird.run();\n }\n}\n``` | 4 | 0 | [] | 0 |
print-in-order | Python use 2 Queue to synchronize | python-use-2-queue-to-synchronize-by-bai-yr1z | \nfrom Queue import Queue\n\n\nclass Foo(object):\n def __init__(self):\n self.q1 = Queue()\n self.q2 = Queue()\n\n def first(self, printFir | bairongdong1 | NORMAL | 2020-06-26T16:35:55.637938+00:00 | 2020-06-26T16:35:55.637986+00:00 | 243 | false | ```\nfrom Queue import Queue\n\n\nclass Foo(object):\n def __init__(self):\n self.q1 = Queue()\n self.q2 = Queue()\n\n def first(self, printFirst):\n """\n :type printFirst: method\n :rtype: void\n """\n # printFirst() outputs "first". Do not change or remove this line.\n printFirst()\n self.q1.put(1)\n\n\n def second(self, printSecond):\n """\n :type printSecond: method\n :rtype: void\n """\n self.q1.get()\n printSecond()\n self.q2.put(1)\n \n \n def third(self, printThird):\n """\n :type printThird: method\n :rtype: void\n """\n self.q2.get()\n printThird()\n``` | 4 | 0 | [] | 0 |
print-in-order | Simple 6 lines java Explained Solution | simple-6-lines-java-explained-solution-b-daq7 | Intutuion\n1. Use volatile variable which will update variable \'a\' in different caches of multi core system. Note - It is only required if this code runs on m | jaswinder_97 | NORMAL | 2020-05-19T05:48:42.189061+00:00 | 2020-05-19T05:48:42.189114+00:00 | 461 | false | Intutuion\n1. Use volatile variable which will update variable \'a\' in different caches of multi core system. Note - It is only required if this code runs on multi core environment.\n2. Run printFirst.run only when a=1;\n3. Run printSecond.run only when a=2; \n4. Similarly printThird.run only when a=3l\n```\nclass Foo {\n volatile int a;\n public Foo() {\n a=1;\n }\n\n public void first(Runnable printFirst) throws InterruptedException {\n \n // printFirst.run() outputs "first". Do not change or remove this line.\n while(a!=1);\n printFirst.run();\n a=2;\n }\n\n public void second(Runnable printSecond) throws InterruptedException {\n \n // printSecond.run() outputs "second". Do not change or remove this line.\n while(a!=2);\n printSecond.run();\n a=3;\n }\n\n public void third(Runnable printThird) throws InterruptedException {\n \n // printThird.run() outputs "third". Do not change or remove this line.\n while(a!=3);\n printThird.run();\n }\n}\n``` | 4 | 0 | [] | 0 |
print-in-order | C++ w/ promise 124ms <92.14%, 9.4MB <100% | c-w-promise-124ms-9214-94mb-100-by-jonli-t8g0 | Runtime: 124 ms, faster than 92.14% of C++ online submissions for Print in Order.\n* Memory Usage: 9.4 MB, less than 100.00% of C++ online submissions for Print | jonlist | NORMAL | 2020-01-19T23:30:01.612733+00:00 | 2020-01-20T02:48:36.823571+00:00 | 628 | false | * Runtime: 124 ms, faster than 92.14% of C++ online submissions for Print in Order.\n* Memory Usage: 9.4 MB, less than 100.00% of C++ online submissions for Print in Order.\n\nThis is a simple task. I did try writing one solution with a condition_variable and one using future/promise.\nThe performance was fairly close, with promise performing slightly better.\n\nIf the task was larger in some dimension, I could walk through the program to show where time is being wasted. This is as simple as it gets and there ought to be a tight cluster of results, where relative performance is honestly random.\n\nMy reason for using promise is that it avoids synchronizing mutex locks between many threads, but there isn\'t much tradeoff between memory or performance no matter what you choose.\n\n```\nclass Foo {\npublic:\n Foo() {}\n\n void first(function<void()> printFirst) {\n \n // printFirst() outputs "first". Do not change or remove this line.\n printFirst();\n p1.set_value(1);\n }\n\n void second(function<void()> printSecond) {\n p1.get_future().wait();\n // printSecond() outputs "second". Do not change or remove this line.\n printSecond();\n p2.set_value(1);\n }\n\n void third(function<void()> printThird) {\n p2.get_future().wait();\n // printThird() outputs "third". Do not change or remove this line.\n printThird();\n }\n \n promise<bool> p1;\n promise<bool> p2;\n};\n```\n | 4 | 0 | ['C'] | 1 |
print-in-order | Intuitive Java Solution With Explanation | intuitive-java-solution-with-explanation-57u4 | Idea\nUse Guarded Block\nhttps://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html\n\nBasically, adding synchronized keyword to all the metho | naveen_kothamasu | NORMAL | 2019-08-10T03:40:56.354812+00:00 | 2019-10-06T01:21:35.674799+00:00 | 618 | false | **Idea**\nUse `Guarded Block`\nhttps://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html\n\nBasically, adding `synchronized` keyword to all the methods will require any thread to acquire intrisic lock of the object of `Foo` (which is used by all the three thread below).\nNow on this lock, we can conditionally block the threads based on current `counter` value. Only unblock the thread for which the condition that it was waiting for is met and rest of the threads will be blocked (their execution is suspended by the `wait()` call). \n\n```\nclass Foo {\n int counter = 1;\n public Foo() {\n \n }\n\n public synchronized void first(Runnable printFirst) throws InterruptedException {\n while(counter != 1){\n wait();\n }\n // printFirst.run() outputs "first". Do not change or remove this line.\n printFirst.run();\n ++counter;\n notifyAll();\n }\n\n public synchronized void second(Runnable printSecond) throws InterruptedException {\n while(counter != 2){\n wait();\n }\n // printSecond.run() outputs "second". Do not change or remove this line.\n printSecond.run();\n ++counter;\n notifyAll();\n }\n\n public synchronized void third(Runnable printThird) throws InterruptedException {\n while(counter != 3){\n wait();\n }\n // printThird.run() outputs "third". Do not change or remove this line.\n printThird.run();\n ++counter;\n notifyAll();\n }\n}\n``` | 4 | 0 | [] | 3 |
print-in-order | C# AutoResetEvent 116ms | c-autoresetevent-116ms-by-code-world-5dyq | \nusing System.Threading;\n\npublic class Foo {\n EventWaitHandle evnt1 = null;\n EventWaitHandle evnt2 = null;\n public Foo() {\n evnt1 = new A | code-world | NORMAL | 2019-08-01T01:44:56.185963+00:00 | 2019-08-01T01:44:56.186020+00:00 | 470 | false | ```\nusing System.Threading;\n\npublic class Foo {\n EventWaitHandle evnt1 = null;\n EventWaitHandle evnt2 = null;\n public Foo() {\n evnt1 = new AutoResetEvent(false);\n evnt2 = new AutoResetEvent(false);\n }\n\n public void First(Action printFirst) {\n \n // printFirst() outputs "first". Do not change or remove this line.\n printFirst();\n evnt1.Set();\n }\n\n public void Second(Action printSecond) {\n \n evnt1.WaitOne();\n // printSecond() outputs "second". Do not change or remove this line.\n printSecond();\n evnt2.Set();\n }\n\n public void Third(Action printThird) {\n evnt2.WaitOne();\n // printThird() outputs "third". Do not change or remove this line.\n printThird();\n evnt2.Set();\n }\n}\n``` | 4 | 0 | [] | 0 |
print-in-order | simplest solution | simplest-solution-by-code4happy-tjfk | No fancy multiple threading blablalba\n\npublic class Foo {\n\n int count;\n public Foo() {\n count = 0;\n }\n\n public void First(Action pri | code4happy | NORMAL | 2019-07-31T05:16:49.298125+00:00 | 2019-07-31T05:21:57.936963+00:00 | 889 | false | No fancy multiple threading blablalba\n```\npublic class Foo {\n\n int count;\n public Foo() {\n count = 0;\n }\n\n public void First(Action printFirst) {\n // printFirst() outputs "first". Do not change or remove this line.\n printFirst();\n count++;\n }\n\n public void Second(Action printSecond) {\n // printSecond() outputs "second". Do not change or remove this line.\n while(count < 1) continue;\n printSecond();\n count++;\n }\n\n public void Third(Action printThird) {\n while(count < 2) continue;\n // printThird() outputs "third". Do not change or remove this line.\n printThird();\n }\n}\n``` | 4 | 7 | [] | 6 |
print-in-order | Java using Semaphores | java-using-semaphores-by-kabutar-vroz | \nimport java.util.concurrent.Semaphore;\nclass Foo {\n\n private final Semaphore second;\n private final Semaphore third;\n \n public Foo() { | kabutar | NORMAL | 2019-07-20T22:45:38.943713+00:00 | 2019-07-20T22:45:38.943746+00:00 | 374 | false | ```\nimport java.util.concurrent.Semaphore;\nclass Foo {\n\n private final Semaphore second;\n private final Semaphore third;\n \n public Foo() { \n second = new Semaphore(0);\n third = new Semaphore(0);\n \n }\n\n public void first(Runnable printFirst) throws InterruptedException { \n // printFirst.run() outputs "first". Do not change or remove this line.\n printFirst.run();\n second.release();\n }\n\n public void second(Runnable printSecond) throws InterruptedException {\n second.acquire();\n // printSecond.run() outputs "second". Do not change or remove this line.\n printSecond.run();\n third.release();\n }\n\n public void third(Runnable printThird) throws InterruptedException {\n third.acquire();\n // printThird.run() outputs "third". Do not change or remove this line.\n printThird.run(); \n }\n}\n``` | 4 | 0 | [] | 0 |
print-in-order | Python 3 Submission with threading.Condition, beats 100% & 100% | python-3-submission-with-threadingcondit-khmb | \nimport threading\n\n\nclass Foo:\n def __init__(self):\n self.condition = threading.Condition()\n self.first_was_printed = False\n sel | bombadil | NORMAL | 2019-07-12T08:22:27.837905+00:00 | 2019-07-12T08:29:48.737776+00:00 | 516 | false | ```\nimport threading\n\n\nclass Foo:\n def __init__(self):\n self.condition = threading.Condition()\n self.first_was_printed = False\n self.second_was_printed = False\n\n def first(self, printFirst: \'Callable[[], None]\') -> None:\n with self.condition:\n printFirst() \n self.first_was_printed = True\n self.condition.notifyAll()\n\n def second(self, printSecond: \'Callable[[], None]\') -> None:\n with self.condition:\n self.condition.wait_for(\n lambda: self.first_was_printed\n )\n printSecond()\n self.second_was_printed = True\n self.condition.notifyAll()\n\n def third(self, printThird: \'Callable[[], None]\') -> None:\n with self.condition:\n self.condition.wait_for(\n lambda: self.second_was_printed\n )\n printThird()\n self.condition.notifyAll()\n``` | 4 | 0 | [] | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.