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
build-a-matrix-with-conditions
Java Topological Sort - 14ms - 50.7MB
java-topological-sort-14ms-507mb-by-chen-dgqw
As the best approach in 210. Course Schedule II, we can replace HashMap with ArrayList[].\n\nclass Solution {\n public int[][] buildMatrix(int k, int[][] row
chenlize96
NORMAL
2022-08-28T04:31:56.528196+00:00
2022-08-28T05:43:22.509666+00:00
66
false
As the best approach in 210. Course Schedule II, we can replace HashMap with ArrayList[].\n```\nclass Solution {\n public int[][] buildMatrix(int k, int[][] rowConditions, int[][] colConditions) {\n Map<Integer, List<Integer>> mapR = new HashMap<>();\n Map<Integer, List<Integer>> mapC = new HashMap<>();\n int[] indR = new int[k];\n int[] indC = new int[k];\n List<Integer> oR = new ArrayList<>();\n List<Integer> oC = new ArrayList<>();\n for (int i = 0; i < rowConditions.length; i++) {\n int f = rowConditions[i][0];\n int s = rowConditions[i][1];\n mapR.putIfAbsent(f, new ArrayList<>());\n mapR.get(f).add(s);\n indR[s - 1]++;\n }\n for (int i = 0; i < colConditions.length; i++) {\n int f = colConditions[i][0];\n int s = colConditions[i][1];\n mapC.putIfAbsent(f, new ArrayList<>());\n mapC.get(f).add(s);\n indC[s - 1]++;\n }\n for (int i = 0; i < indR.length; i++) {\n if (indR[i] == 0) {\n oR.add(i + 1);\n }\n }\n for (int i = 0; i < oR.size(); i++) {\n if (!mapR.containsKey(oR.get(i))) {\n continue;\n }\n for (int num : mapR.get(oR.get(i))) {\n if (--indR[num - 1] == 0) {\n oR.add(num);\n }\n }\n }\n for (int i = 0; i < indC.length; i++) {\n if (indC[i] == 0) {\n oC.add(i + 1);\n }\n }\n for (int i = 0; i < oC.size(); i++) {\n if (!mapC.containsKey(oC.get(i))) {\n continue;\n }\n for (int num : mapC.get(oC.get(i))) {\n if (--indC[num - 1] == 0) {\n oC.add(num);\n }\n }\n }\n if (oR.size() != k || oC.size() != k) {\n return new int[0][0];\n }\n int[][] ans = new int[k][k];\n Map<Integer, Integer> rel = new HashMap<>();\n for (int i = 0; i < k; i++) {\n ans[k - 1][i] = oC.get(i);\n rel.put(oC.get(i), i);\n }\n for (int i = 0; i < oR.size() - 1; i++) {\n int tmp = oR.get(i);\n int col = rel.get(tmp);\n ans[i][col] = tmp;\n ans[k - 1][col] = 0;\n }\n return ans; \n }\n}\n```
2
0
['Topological Sort']
0
build-a-matrix-with-conditions
C#
c-by-adchoudhary-d401
Code
adchoudhary
NORMAL
2025-03-04T05:08:28.244231+00:00
2025-03-04T05:08:28.244231+00:00
4
false
# Code ```csharp [] public class Solution { public int[][] BuildMatrix(int k, int[][] rowConditions, int[][] colConditions) { // Store the topologically sorted sequences. List<int> orderRows = TopoSort(rowConditions, k); List<int> orderColumns = TopoSort(colConditions, k); // If no topological sort exists, return an empty array. if (orderRows.Count == 0 || orderColumns.Count == 0) return new int[0][]; int[][] matrix = new int[k][]; for (int i = 0; i < k; i++) { matrix[i] = new int[k]; for (int j = 0; j < k; j++) { if (orderRows[i] == orderColumns[j]) matrix[i][j] = orderRows[i]; } } return matrix; } private List<int> TopoSort(int[][] edges, int n) { // Build adjacency list List<List<int>> adj = new List<List<int>>(); for (int i = 0; i <= n; i++) adj.Add(new List<int>()); foreach (int[] edge in edges) adj[edge[0]].Add(edge[1]); List<int> order = new List<int>(); // 0: not visited, 1: visiting, 2: visited int[] visited = new int[n + 1]; bool[] hasCycle = { false }; // Perform DFS for each node for (int i = 1; i <= n; i++) { if (visited[i] == 0) { Dfs(i, adj, visited, order, hasCycle); // Return empty if cycle detected if (hasCycle[0]) return new List<int>(); } } // Reverse to get the correct order order.Reverse(); return order; } private void Dfs(int node, List<List<int>> adj, int[] visited, List<int> order, bool[] hasCycle) { visited[node] = 1; // Mark node as visiting foreach (int neighbor in adj[node]) { if (visited[neighbor] == 0) { Dfs(neighbor, adj, visited, order, hasCycle); // Early exit if a cycle is detected if (hasCycle[0]) return; } else if (visited[neighbor] == 1) { // Cycle detected hasCycle[0] = true; return; } } // Mark node as visited visited[node] = 2; // Add node to the order order.Add(node); } } ```
1
0
['C#']
0
build-a-matrix-with-conditions
C++ code using topological sort (using Kahn's algorithm)
c-code-using-topological-sort-using-kahn-cifs
IntuitionYou can think of each conditions in rowconditions and colconditions as a edge between two vertices.Make a topological sort the all the elements based o
ankurkarn
NORMAL
2025-02-21T18:11:53.206265+00:00
2025-02-21T18:16:14.392472+00:00
15
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> You can think of each conditions in rowconditions and colconditions as a edge between two vertices. Make a topological sort the all the elements based on the rowconditions and colconditions. According to it, find the position of each element in required matrix. # Approach <!-- Describe your approach to solving the problem. --> Here i tried to find topological sort using kahn's algorithm. A valid topological sort if not possible if a cycle is present in the graph. So if valid toplogical sort is not possible, then return empty vector. After finding valid topological sort, find the row and column for each element by using the element present at different indices. Fill the elements in the ans vector and return it. Note that there was no need to clear the queue after finding the first vector "row" because the toposort function works until the queue is cleared, so queue becomes empty automatically. # Complexity - Time complexity: O(k+E) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(k^2) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { void toposort(unordered_map<int,int>& indegree,unordered_map<int, vector<int>>& adj, queue<int>& q, vector<int>& vec){ while(!q.empty()){ int k = q.front(); q.pop(); vec.push_back(k); for(int i : adj[k]){ indegree[i]--; if(indegree[i] == 0) q.push(i); } } } public: vector<vector<int>> buildMatrix(int k, vector<vector<int>>& rowConditions, vector<vector<int>>& colConditions) { unordered_map<int, vector<int>> adjr, adjc; unordered_map<int, int> indr, indc; vector<int> row, col; queue<int> q; vector<vector<int>> ans(k, vector<int>(k, 0)), empty; vector<pair<int,int>> last(k, {0,0}); for(int i = 1;i<=k;i++){ indr[i] = 0; indc[i] = 0; } for(auto i : rowConditions){ adjr[i[0]].push_back(i[1]); indr[i[1]]++; } for(auto i : colConditions){ adjc[i[0]].push_back(i[1]); indc[i[1]]++; } for(auto i : indr){ if(i.second == 0) q.push(i.first); } toposort(indr, adjr, q, row); if(row.size() != k) return empty; for(auto i : indc){ if(i.second == 0) q.push(i.first); } toposort(indc, adjc, q, col); if(col.size() != k) return empty; for(int i = 0;i<k;i++){ last[row[i] - 1].first = i; } for(int i = 0;i<k;i++){ last[col[i] - 1].second = i; } for(int i = 0;i<k;i++){ ans[last[i].first][last[i].second] = i+1; } return ans; } }; ```
1
0
['C++']
0
build-a-matrix-with-conditions
C++ || Graph || Topological Sort || AVS
c-graph-topological-sort-avs-by-vishal14-ym8e
null
Vishal1431
NORMAL
2025-01-03T15:04:25.144896+00:00
2025-01-03T15:04:25.144896+00:00
17
false
```cpp [] class Solution { public: vector<vector<int>> buildMatrix(int k, vector<vector<int>>& rowConditions,vector<vector<int>>& colConditions) { // Store the topologically sorted sequences. vector<int> orderRows = topoSort(rowConditions, k); vector<int> orderColumns = topoSort(colConditions, k); // If no topological sort exists, return empty array. if (orderRows.empty() or orderColumns.empty()) return {}; vector<vector<int>> matrix(k, vector<int>(k, 0)); for (int i = 0; i < k; i++) { for (int j = 0; j < k; j++) { if (orderRows[i] == orderColumns[j]) { matrix[i][j] = orderRows[i]; } } } return matrix; } vector<int> topoSort(vector<vector<int>>& edges, int n) { vector<vector<int>> adj(n + 1); vector<int> order; // 0: not visited, 1: visiting, 2: visited vector<int> visited(n + 1, 0); bool hasCycle = false; // Build adjacency list for (auto& x : edges) { adj[x[0]].push_back(x[1]); } // Perform DFS for each node for (int i = 1; i <= n; i++) { if (visited[i] == 0) { dfs(i, adj, visited, order, hasCycle); // Return empty if cycle detected if (hasCycle) return {}; } } // Reverse to get the correct order reverse(order.begin(), order.end()); return order; } void dfs(int node, vector<vector<int>>& adj, vector<int>& visited, vector<int>& order, bool& hasCycle) { visited[node] = 1; // Mark node as visiting for (int neighbor : adj[node]) { if (visited[neighbor] == 0) { dfs(neighbor, adj, visited, order, hasCycle); // Early exit if a cycle is detected if (hasCycle) return; } else if (visited[neighbor] == 1) { // Cycle detected hasCycle = true; return; } } // Mark node as visited visited[node] = 2; // Add node to the order order.push_back(node); } }; ```
1
0
['Graph', 'Topological Sort', 'C++']
0
build-a-matrix-with-conditions
Topological sort
topological-sort-by-georgynet-4934
Complexity\n- Time complexity: O(K^2)\n\n- Space complexity: O(K)\n\n# Code\n\nclass Solution\n{\n /**\n * @param int[][] $rowConditions\n * @param i
georgynet
NORMAL
2024-07-22T15:50:39.352271+00:00
2024-07-22T15:50:39.352307+00:00
4
false
# Complexity\n- Time complexity: $$O(K^2)$$\n\n- Space complexity: $$O(K)$$\n\n# Code\n```\nclass Solution\n{\n /**\n * @param int[][] $rowConditions\n * @param int[][] $colConditions\n * @return int[][]\n */\n public function buildMatrix(int $k, array $rowConditions, array $colConditions): array\n {\n $sortedRow = $this->topologicalSort($k, $rowConditions);\n $sortedCol = $this->topologicalSort($k, $colConditions);\n\n if (count($sortedRow) === 0 || count($sortedCol) === 0) {\n return [];\n }\n\n $r = array_fill(0, $k, 0);\n $result = array_fill(0, $k, $r);\n\n\n for ($i = 0; $i < $k; $i++) {\n $isMatched = false;\n for ($j = 0; $j < $k; $j++) {\n if ($sortedRow[$i] === $sortedCol[$j]) {\n $result[$i][$j] = $sortedCol[$j];\n $isMatched = true;\n }\n }\n\n if ($isMatched === false) {\n return [];\n }\n }\n\n return $result;\n }\n\n /**\n * @param int $k\n * @param int[][] $conditions\n * @return int[]\n */\n private function topologicalSort(int $k, array $conditions): array\n {\n $wights = array_fill(1, $k, 0);\n\n $indexed = [];\n foreach ($conditions as $condition) {\n $indexed[$condition[0]][] = $condition[1];\n ++$wights[$condition[1]];\n }\n\n $sorted = [];\n do {\n asort($wights);\n\n $firstKey = array_key_first($wights);\n if ($wights[$firstKey] !== 0) {\n return [];\n }\n\n unset($wights[$firstKey]);\n\n $sorted[] = $firstKey;\n\n $next = $indexed[$firstKey] ?? [];\n foreach ($next as $wight) {\n --$wights[$wight];\n }\n } while (count ($wights) > 0);\n\n return $sorted;\n }\n}\n```
1
0
['PHP']
0
build-a-matrix-with-conditions
C++ || Topological Sorting || Khan's Algorithm || Cycle Detection
c-topological-sorting-khans-algorithm-cy-niuo
Code\n\nclass Solution {\npublic:\n bool check_cycle(vector<vector<int>> &arr, int n,vector<vector<int>> &g,vector<int> &ans){\n g.resize(n+1);\n
Paras_Punjabi
NORMAL
2024-07-22T14:38:16.372149+00:00
2024-07-22T14:38:16.372180+00:00
9
false
# Code\n```\nclass Solution {\npublic:\n bool check_cycle(vector<vector<int>> &arr, int n,vector<vector<int>> &g,vector<int> &ans){\n g.resize(n+1);\n vector<int> in(n+1,0);\n for(auto item : arr){\n in[item[1]]++;\n g[item[0]].push_back(item[1]);\n }\n queue<int> q;\n for(int i=1;i<in.size();i++){\n if(in[i] == 0) q.push(i);\n }\n while(!q.empty()){\n auto p = q.front();\n q.pop();\n ans.push_back(p);\n for(auto item : g[p]){\n if(in[item]>0){\n in[item]--;\n if(in[item] == 0) q.push(item);\n }\n }\n }\n return ans.size() != n;\n }\n\n vector<vector<int>> buildMatrix(int k, vector<vector<int>>& r, vector<vector<int>>& c) {\n vector<vector<int>> ans,gr,gc;\n vector<int> row,col;\n sort(r.begin(),r.end());\n r.erase(unique(r.begin(),r.end()),r.end());\n\n sort(c.begin(),c.end());\n c.erase(unique(c.begin(),c.end()),c.end());\n\n if(check_cycle(r,k,gr,row) or check_cycle(c,k,gc,col)) return ans;\n ans.resize(k,vector<int>(k,0));\n unordered_map<int,int> mpr,mpc;\n for(int i=0;i<row.size();i++){\n mpr[row[i]]=i;\n mpc[col[i]]=i;\n }\n for(int i=1;i<=k;i++){\n ans[mpr[i]][mpc[i]]=i;\n }\n return ans;\n }\n};\n```
1
0
['Topological Sort', 'Queue', 'Ordered Map', 'C++']
1
build-a-matrix-with-conditions
Simple toposort question
simple-toposort-question-by-techtinkerer-vpnq
\n\n# Complexity\n- Time complexity:O(n^2)// n^2 can be the maximum number of edges\n Add your time complexity here, e.g. O(n) \n\n- Space complexity:O(n)\n Add
TechTinkerer
NORMAL
2024-07-22T11:52:35.163894+00:00
2024-07-22T11:52:35.163914+00:00
4
false
\n\n# Complexity\n- Time complexity:O(n^2)// n^2 can be the maximum number of edges\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> solve(vector<vector<int>> adj){\n int n=adj.size();\n vector<int> indegree(n,0);\n for(auto i:adj){\n for(auto j:i){\n indegree[j]++;\n }\n\n }\n\n queue<int> q;\n\n for(auto i=0;i<n;i++){\n if(indegree[i]==0)\n q.push(i);\n }\n\n vector<int> ans;\n\n while(!q.empty()){\n int x=q.front();\n ans.push_back(x);\n q.pop();\n for(auto i:adj[x]){\n indegree[i]--;\n if(indegree[i]==0)\n q.push(i);\n }\n }\n\n if(ans.size()<n)\n return {};\n return ans;\n }\n vector<vector<int>> buildMatrix(int k, vector<vector<int>>& rc, vector<vector<int>>& cc) {\n vector<vector<int>> ans(k,vector<int> (k,0));\n\n vector<vector<int>> adj1(k),adj2(k);\n\n for(auto i:rc){\n adj1[--i[0]].push_back(--i[1]);\n }\n for(auto i:cc){\n adj2[--i[0]].push_back(--i[1]);\n }\n\n auto v1=solve(adj1),v2=solve(adj2);\n\n if(v1.empty() || v2.empty())\n return {};\n unordered_map<int,int> row,col;\n for(int i=0;i<k;i++){\n row[++v1[i]]=i;\n col[++v2[i]]=i;\n }\n\n for(int i=1;i<=k;i++){\n ans[row[i]][col[i]]=i;\n }\n\n return ans;\n\n\n \n\n \n }\n};\n```
0
0
['Array', 'Graph', 'Topological Sort', 'Matrix', 'C++']
0
build-a-matrix-with-conditions
java solution using Topological sort | Graph ☑☑☑
java-solution-using-topological-sort-gra-1bk3
\n// use for calculation index\nclass Node{\n int i,j;\n public Node(int i,int j){\n this.i=i;\n this.j=j;\n }\n}\n\nclass Solution {\n
I_am_SOURAV
NORMAL
2024-07-22T06:56:00.870864+00:00
2024-07-22T06:56:00.870908+00:00
9
false
```\n// use for calculation index\nclass Node{\n int i,j;\n public Node(int i,int j){\n this.i=i;\n this.j=j;\n }\n}\n\nclass Solution {\n \n // detect cycle for directed graph\n public boolean checkCycle(int u,Map<Integer,List<Integer>> adj,boolean []visited,boolean []curStack){\n visited[u]=true;\n curStack[u]=true;\n // if u is not present in that time we hae not cycle that\'s why return false\n if(!adj.containsKey(u)){\n curStack[u]=false;\n return false;\n }\n for(int v:adj.get(u)){\n if(!visited[v] && checkCycle(v,adj,visited,curStack)){\n return true;\n }else if(curStack[v]){\n return true;\n }\n }\n curStack[u]=false;\n return false;\n }\n\n // creating stack for topological sort list\n public void solve(int u,Map<Integer,List<Integer>> adj,boolean visited[],Stack<Integer> store){\n visited[u]=true;\n if(adj.containsKey(u)){\n for(int v:adj.get(u)){\n if(!visited[v]){\n solve(v,adj,visited,store);\n }\n }\n }\n store.push(u);\n }\n \n public List<Integer> topologicalSort(int[][] condition,int k){\n Map<Integer,List<Integer>> adj = new HashMap<>();\n boolean visited[]= new boolean[k+1];\n Stack<Integer> store = new Stack<>();\n \n //create graph\n for(int []arr:condition){\n if(adj.containsKey(arr[0])){\n adj.get(arr[0]).add(arr[1]);\n }else{\n List<Integer> temp = new ArrayList<>();\n temp.add(arr[1]);\n adj.put(arr[0],temp);\n }\n }\n \n // checking graph has cycle. if we have cycle return empty list\n List<Integer> topoList = new ArrayList<>();\n boolean curStack[] = new boolean[k+1];\n for(int i=1;i<=k;i++){\n if(!visited[i] && checkCycle(i,adj,visited,curStack)){\n return topoList;\n }\n }\n \n //traversing for stack that use for topological sort List\n visited= new boolean[k+1];\n for(int i=1;i<=k;i++){\n if(!visited[i]){\n solve(i,adj,visited,store);\n }\n }\n \n //revering stack to get topological sorted list\n while(store.size()>0){\n topoList.add(store.pop());\n }\n return topoList;\n }\n \n public int[][] buildMatrix(int k, int[][] rowConditions, int[][] colConditions) {\n int[][] ans = new int[k][k];\n \n // getting topological list\n List<Integer> rowNums = topologicalSort(rowConditions,k);\n List<Integer> colNums = topologicalSort(colConditions,k);\n if(rowNums.isEmpty() || colNums.isEmpty()){\n return new int[0][0];\n }\n System.out.println(rowNums.size());\n System.out.println(colNums.size());\n // calculating [row][col] for one element\n HashMap<Integer,Node> index = new HashMap<>();\n for(int i=0;i<k;i++){\n index.put(rowNums.get(i),new Node(i,-1));\n }\n for(int i=0;i<k;i++){\n index.get(colNums.get(i)).j=i;\n }\n for(int key:index.keySet()){\n Node node = index.get(key);\n ans[node.i][node.j]=key;\n }\n \n return ans;\n }\n}\n```
1
0
['Array', 'Graph', 'Topological Sort', 'Matrix', 'Java']
0
build-a-matrix-with-conditions
Kotlin. Beats 100% (476 ms). IntArrays to sort row and col positions.
kotlin-beats-100-476-ms-intarrays-to-sor-9jkc
\n\n# Code\n\nclass Solution {\n fun buildMatrix(k: Int, rowConditions: Array<IntArray>, colConditions: Array<IntArray>): Array<IntArray> {\n val rows
mobdev778
NORMAL
2024-07-22T06:49:35.264728+00:00
2024-07-22T06:49:35.264753+00:00
6
false
![image.png](https://assets.leetcode.com/users/images/b17bf514-4417-4bfc-af38-c07a0fd3acb8_1721630927.6569366.png)\n\n# Code\n```\nclass Solution {\n fun buildMatrix(k: Int, rowConditions: Array<IntArray>, colConditions: Array<IntArray>): Array<IntArray> {\n val rows = IntArray(k + 1)\n for (i in 0 until k) {\n rows[i + 1] = i\n }\n if (sort(k, rowConditions, rows)) {\n return EMPTY\n }\n\n val cols = IntArray(k + 1)\n for (i in 0 until k) {\n cols[i + 1] = i\n }\n if (sort(k, colConditions, cols)) {\n return EMPTY\n }\n\n val matrix = Array(k) { IntArray(k) }\n for (i in 1..k) {\n matrix[rows[i]][cols[i]] = i\n }\n return matrix\n }\n\n private fun sort(k: Int, conditions: Array<IntArray>, positions: IntArray): Boolean {\n var swapped = false\n for (i in 0 until k) {\n swapped = false\n for ((low, hi) in conditions) {\n val lowPos = positions[low]\n val hiPos = positions[hi]\n if (lowPos > hiPos) {\n swapped = true\n positions[low] = hiPos\n positions[hi] = lowPos\n }\n }\n if (!swapped) break\n }\n return swapped\n }\n\n companion object {\n val EMPTY = Array(0) { IntArray(0) }\n }\n}\n```
1
0
['Kotlin']
0
build-a-matrix-with-conditions
Very Easy C++ Solution || TOPOSORT
very-easy-c-solution-toposort-by-harshit-nvbd
\n\n# Code\n\nclass Solution {\n vector<int> ts(int V, vector<vector<int>> &adj) {\n vector<int> indegree(V + 1, 0);\n vector<int> ans;\n
harshitgupta_2643
NORMAL
2024-07-22T06:09:51.351181+00:00
2024-07-22T06:09:51.351226+00:00
6
false
\n\n# Code\n```\nclass Solution {\n vector<int> ts(int V, vector<vector<int>> &adj) {\n vector<int> indegree(V + 1, 0);\n vector<int> ans;\n queue<int> q;\n\n for (int i = 1; i <= V; ++i) {\n for (auto it : adj[i]) {\n indegree[it]++;\n }\n }\n\n for (int i = 1; i <= V; ++i) {\n if (indegree[i] == 0) {\n q.push(i);\n }\n }\n\n while (!q.empty()) {\n int node = q.front();\n q.pop();\n\n ans.push_back(node);\n\n for (auto neigh : adj[node]) {\n indegree[neigh]--;\n if (indegree[neigh] == 0) {\n q.push(neigh);\n }\n }\n }\n\n if (ans.size() != V) return {};\n return ans;\n }\n\npublic:\n vector<vector<int>> buildMatrix(int k, vector<vector<int>>& rowConditions, vector<vector<int>>& colConditions) {\n vector<vector<int>> rowAdj(k + 1);\n vector<vector<int>> colAdj(k + 1);\n\n for (auto it : rowConditions) {\n int u = it[0];\n int v = it[1];\n rowAdj[u].push_back(v);\n }\n\n for (auto it : colConditions) {\n int u = it[0];\n int v = it[1];\n colAdj[u].push_back(v);\n }\n\n vector<int> row = ts(k, rowAdj);\n if (row.empty()) return {};\n vector<int> col = ts(k, colAdj);\n if (col.empty()) return {};\n\n vector<int> rowPos(k + 1), colPos(k + 1);\n for (int i = 0; i < k; ++i) {\n rowPos[row[i]] = i;\n colPos[col[i]] = i;\n }\n\n vector<vector<int>> ans(k, vector<int>(k, 0));\n for (int i = 1; i <= k; ++i) {\n ans[rowPos[i]][colPos[i]] = i;\n }\n\n return ans;\n }\n};\n\n```
1
0
['C++']
0
build-a-matrix-with-conditions
DarkNerd || TopoLogical Sort
darknerd-topological-sort-by-darknerd-hc53
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
darknerd
NORMAL
2024-07-22T06:07:20.486162+00:00
2024-07-22T06:07:20.486189+00:00
5
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n void buildGraph(vector<vector<int>>& vec, unordered_map<int, vector<int>>& graph){\n int n=vec.size();\n for(int i=0; i<n; i++){\n graph[vec[i][0]].push_back(vec[i][1]);\n }\n }\n\n void topo(int& k, unordered_map<int, vector<int>>& graph, vector<int>& ans){\n int indegree[k+1];\n memset(indegree, 0, sizeof(indegree));\n for(auto& [parent, child]:graph){\n for(int& i:child){\n indegree[i]++;\n }\n }\n queue<int> que;\n for(int i=1; i<=k; i++){\n if(indegree[i] == 0){\n que.push(i);\n }\n }\n while(!que.empty()){\n int temp = que.front();\n que.pop();\n\n ans.push_back(temp);\n\n for(int& i:graph[temp]){\n indegree[i]--;\n if(indegree[i] == 0){\n que.push(i);\n }\n }\n }\n }\n\n\npublic:\n vector<vector<int>> buildMatrix(int k, vector<vector<int>>& row, vector<vector<int>>& col) {\n unordered_map<int, vector<int>> rowg;\n unordered_map<int, vector<int>> colg;\n\n buildGraph(row, rowg);\n buildGraph(col, colg);\n\n vector<int> r;\n vector<int> c;\n\n topo(k, rowg, r);\n topo(k, colg, c);\n\n if(r.empty() || c.empty() || r.size() != k || c.size() != k){\n return {};\n }\n\n vector<vector<int>> res(k, vector<int>(k, 0));\n for(int i=0; i<k; i++){\n for(int j=0; j<k; j++){\n if(r[i] == c[j]){\n res[i][j]=r[i];\n }\n }\n }\n\n return res;\n }\n};\n```
1
0
['C++']
0
build-a-matrix-with-conditions
Topological sorting
topological-sorting-by-houssemdev25-2koy
Code\n\nclass Solution {\n public int[][] buildMatrix(int k, int[][] rowConditions, int[][] colConditions) {\n List<Integer> sortedByRow = topological
houssemdev25
NORMAL
2024-07-21T23:09:05.032661+00:00
2024-07-21T23:09:05.032687+00:00
8
false
# Code\n```\nclass Solution {\n public int[][] buildMatrix(int k, int[][] rowConditions, int[][] colConditions) {\n List<Integer> sortedByRow = topologicalSort(rowConditions, k);\n List<Integer> sortedByCol = topologicalSort(colConditions, k);\n\n if (sortedByRow.isEmpty() || sortedByCol.isEmpty()) {\n return new int[0][0];\n }\n\n int[][] cellsIndexed = new int[k + 1][2];\n for (int row = 0; row < sortedByRow.size(); row++) {\n int cellAtRow = sortedByRow.get(row);\n cellsIndexed[cellAtRow][0] = row;\n }\n for (int col = 0; col < sortedByCol.size(); col++) {\n int cellAtCol = sortedByCol.get(col);\n cellsIndexed[cellAtCol][1] = col;\n }\n\n int[][] ans = new int[k][k];\n for (int cell = 1; cell <= k; cell++) {\n int[] cellCoordinates = cellsIndexed[cell];\n ans[cellCoordinates[0]][cellCoordinates[1]] = cell;\n }\n\n return ans;\n }\n\n private List<Integer> topologicalSort(int[][] conditions, int k) {\n Map<Integer, List<Integer>> adjacency = new HashMap<>();\n\n for (int[] condition : conditions) {\n adjacency.putIfAbsent(condition[0], new ArrayList<>());\n adjacency.get(condition[0]).add(condition[1]);\n }\n\n int[] indegreeLookup = new int[k + 1];\n for (int[] condition : conditions) {\n indegreeLookup[condition[1]]++;\n }\n\n Queue<Integer> q = new ArrayDeque<>();\n for (int vertex = 1; vertex <= k; vertex++) {\n if (indegreeLookup[vertex] == 0) {\n q.offer(vertex);\n }\n }\n\n List<Integer> ans = new ArrayList<>();\n while (!q.isEmpty()) {\n int vertex = q.poll();\n ans.add(vertex);\n\n List<Integer> adjacents = adjacency.getOrDefault(vertex, new ArrayList<>());\n for (int adjacentVertex : adjacents) {\n indegreeLookup[adjacentVertex]--;\n if (indegreeLookup[adjacentVertex] == 0) {\n q.offer(adjacentVertex);\n }\n }\n }\n \n return ans.size() < k ? new ArrayList<>() : ans;\n }\n}\n```
1
0
['Java']
0
build-a-matrix-with-conditions
Topological Sort, Easy C++ Solution.
topological-sort-easy-c-solution-by-es22-270y
Intuition\n Describe your first thoughts on how to solve this problem. \nSince the problem is related to which row or column appears before the other.. we need
es22btech11008
NORMAL
2024-07-21T21:10:40.422776+00:00
2024-07-21T21:10:40.422807+00:00
9
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSince the problem is related to which row or column appears before the other.. ***we need to get the order of which element comes before which element***. Only **topological sort** gives such order. So first get the order of the rows and columns then place them in the matrix.\n\n**Note:-** If you didnt get the idea of topological sort... It is similar to the question : https://leetcode.com/problems/course-schedule-ii/description/ so first you can try out this then it will be very easy to understand and solve the current problem. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Use ***topological sort*** and get the ordering or the row and column elements. \n2. Then from row ordering you will get the row index and from the column ordering you will get the column index, so in this way you can fill the matrix.\n3. ***KeyPoint to note is that roworder and columnorder will have the same elements, so you can find rowindex and columnindex by searching for a specific element in both the orderings.***\n \nNote:- If the topological sort didnt work properly (cycle is present) in either rowconditions or colconditions then return an empty 2D array. \n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(k^2 + E)\nWhere E is the number of edges in the conditions.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(k^2 + E)\nWhere E is the number of edges in the conditions.\n\n# Code\n```\nclass Solution {\npublic:\n\n void order(vector<int>& ans,vector<vector<int>>& conditions,int k){\n vector<vector<int>>adj(k+1);\n for(int i = 0;i<conditions.size();i++) {\n adj[conditions[i][0]].push_back(conditions[i][1]);\n }\n vector<int>indegree(k+1,0);\n for(int i = 0;i<=k;i++) {\n for(auto j : adj[i]) {\n indegree[j]++;\n }\n }\n queue<int>q;\n for(int i =1;i<=k;i++) {\n if(indegree[i]==0) {\n q.push(i);\n }\n }\n while(!q.empty()){\n int x = q.front();\n q.pop();\n ans.push_back(x);\n for(auto neighbour : adj[x]){\n indegree[neighbour]--;\n if(indegree[neighbour]==0) {\n q.push(neighbour);\n }\n }\n }\n if(ans.size()!=k){\n ans.clear();\n } \n }\n\n vector<vector<int>> buildMatrix(int k, vector<vector<int>>& rowConditions, vector<vector<int>>& colConditions) {\n vector<vector<int>>ans(k,vector<int>(k,0));\n vector<vector<int>>invalid;\n vector<int>roworder;\n order(roworder,rowConditions,k);\n vector<int>columnorder;\n order(columnorder,colConditions,k);\n if(roworder.empty() || columnorder.empty()){\n return invalid;\n }\n \n for(int i = 1;i<=k;i++){\n int row;\n int col;\n for(int j = 0;j<roworder.size();j++){\n if(roworder[j]==i){\n row = j;\n break;\n }\n }\n for(int j =0;j<columnorder.size();j++){\n if(columnorder[j]==i){\n col = j;\n break;\n }\n }\n ans[row][col] = i;\n }\n return ans;\n }\n};\n```
1
0
['Topological Sort', 'C++']
0
build-a-matrix-with-conditions
Well-Structured Graph Solution with Topological Sorting
well-structured-graph-solution-with-topo-4w4z
Intuition\nWe need to build a matrix that satisfies two conditions:\n\n1. Numbers should follow specific row orders.\n2. Numbers should follow specific column o
alyonazhabina
NORMAL
2024-07-21T21:10:13.169956+00:00
2024-07-21T21:10:13.169988+00:00
2
false
# Intuition\nWe need to build a matrix that satisfies two conditions:\n\n1. Numbers should follow specific row orders.\n2. Numbers should follow specific column orders.\n\nTo do this, we first convert these conditions into graphs and then perform topological sorting to find the order of numbers. Finally, we use this order to fill the matrix.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Create Graphs: Convert row and column conditions into graphs to track dependencies.\n2. Topological Sorting: Use topological sorting to find the valid order of numbers for rows and columns.\n3. Build Matrix: Create a matrix and fill it based on the sorted numbers for rows and columns.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n * m)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n * m)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {number} k\n * @param {number[][]} rowConditions\n * @param {number[][]} colConditions\n * @return {number[][]}\n */\nvar buildMatrix = function (k, rowConditions, colConditions) {\n const { graph: graphRow, startingPoints: startingPointsRow, degree: degreeRow } = createGraph(rowConditions, k)\n const { graph: graphCol, startingPoints: startingPointsCol, degree: degreeCol } = createGraph(colConditions, k)\n\n const row = traverseGraph(startingPointsRow, degreeRow, graphRow)\n const col = traverseGraph(startingPointsCol, degreeCol, graphCol)\n\n if (row.length !== k || col.length !== k) return []\n\n const matrix = createMatrix(k, 0)\n\n return fillMatrix(matrix, row, col)\n}\n\nfunction createMatrix (n, valueToFill) {\n return Array.from({ length: n }, () => new Array(n).fill(valueToFill))\n}\n\nfunction createGraph (rowConditions, k) {\n const degree = new Array(k + 1).fill(0)\n const graph = {}//value -> [to]\n const startingPoints = new Set([])\n\n for (let i = 1; i <= k; i++) {\n startingPoints.add(i)\n }\n\n rowConditions.forEach(rowCondition => {\n const [to, from] = rowCondition\n\n if (!graph[from]) {\n graph[from] = {}\n }\n\n if (!graph[from][to]) {\n graph[from][to] = true\n startingPoints.delete(to)\n degree[to]++\n }\n })\n\n return { graph, startingPoints: [...startingPoints], degree }\n}\n\nfunction fillMatrix (matrix, row, col) {\n for (let i = matrix.length - 1; i >= 0; i--) {\n for (let j = matrix[0].length - 1; j >= 0; j--) {\n if (row[i] === col[j]) {\n matrix[matrix.length - i - 1][matrix[0].length - j - 1] = row[i]\n }\n }\n }\n\n return matrix\n}\n\nfunction traverseGraph (start, degree, graph) {\n const added = new Set([])\n const result = []\n\n const queue = [...start]\n\n while (queue.length) {\n const popped = queue.shift()\n\n if (!added.has(popped)) {\n result.push(popped)\n added.add(popped)\n }\n\n const adjVertices = graph[popped]\n\n if (adjVertices) {\n for (let vertex in adjVertices) {\n degree[vertex]--\n\n if (degree[vertex] === 0) {\n queue.push(Number(vertex))\n }\n }\n }\n }\n\n return result\n}\n\n```
1
0
['Graph', 'Topological Sort', 'JavaScript']
0
build-a-matrix-with-conditions
Solution in C
solution-in-c-by-yshkcr-vlpy
this was difficult lol\n\n# Intuition\nit\'s slightly similar to yesterday\'s problem but i still had to bang my head around to wrap all that and actually under
yshkcr
NORMAL
2024-07-21T18:46:59.309468+00:00
2024-07-21T18:46:59.309485+00:00
4
false
this was **difficult** lol\n\n# Intuition\nit\'s slightly similar to yesterday\'s problem but i still had to bang my head around to wrap all that and actually understand the problem. even though i could see think and come up with a solution on paper i knew this was going to be really difficult to code especially in C.\n\n# Approach\nthanks to neetcode for his approach with topological sort to identify cycles and also gpt for solving out of bound and minor\nissues\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```\nbool dfs(int src, int k, int** adj, int* sizes, bool* visit, bool* path, int* order, int* orderSize) {\n if (src < 1 || src > k) return true;\n if (path[src]) return false;\n if (visit[src]) return true;\n \n visit[src] = true;\n path[src] = true;\n \n for (int i = 0; i < sizes[src]; i++) {\n int nei = adj[src][i];\n if (nei < 1 || nei > k) continue;\n if (!dfs(nei, k, adj, sizes, visit, path, order, orderSize)) {\n return false;\n }\n }\n \n path[src] = false;\n order[*orderSize] = src;\n (*orderSize)++;\n return true;\n}\n\nint* tsort(int k, int** conditions, int conditionsSize, int* conditionsColSize) {\n int** adj = (int**)malloc((k + 1) * sizeof(int*));\n if (!adj) return NULL;\n \n int* sizes = (int*)calloc(k + 1, sizeof(int));\n if (!sizes) {\n return NULL;\n }\n \n for (int i = 0; i <= k; i++) {\n adj[i] = (int*)malloc((k + 1) * sizeof(int));\n\n }\n \n for (int i = 0; i < conditionsSize; i++) {\n int src = conditions[i][0], dst = conditions[i][1];\n if (src >= 1 && src <= k && dst >= 1 && dst <= k && sizes[src] < k) {\n adj[src][sizes[src]++] = dst;\n }\n }\n \n bool* visit = (bool*)calloc(k + 1, sizeof(bool));\n bool* path = (bool*)calloc(k + 1, sizeof(bool));\n int* order = (int*)malloc((k + 1) * sizeof(int));\n if (!visit || !path || !order) {\n \n return NULL;\n }\n \n int orderSize = 0;\n bool hasCycle = false;\n \n for (int src = 1; src <= k; src++) {\n if (!dfs(src, k, adj, sizes, visit, path, order, &orderSize)) {\n hasCycle = true;\n break;\n }\n }\n \n int* result = NULL;\n if (!hasCycle) {\n result = (int*)malloc(k * sizeof(int));\n if (result) {\n for (int i = 0; i < k; i++) {\n result[i] = order[k - 1 - i];\n }\n }\n }\n\n \n return result;\n}\n\nint** buildMatrix(int k, int** rowConditions, int rowConditionsSize, int* rowConditionsColSize, \n int** colConditions, int colConditionsSize, int* colConditionsColSize, \n int* returnSize, int** returnColumnSizes) {\n if (k <= 0 || k > 400) {\n *returnSize = 0;\n *returnColumnSizes = NULL;\n return NULL;\n }\n \n int* rows = tsort(k, rowConditions, rowConditionsSize, rowConditionsColSize);\n int* cols = tsort(k, colConditions, colConditionsSize, colConditionsColSize);\n \n if (!rows || !cols) {\n *returnSize = 0;\n *returnColumnSizes = NULL;\n \n return NULL;\n }\n \n int* val_rows = (int*)malloc((k + 1) * sizeof(int));\n int* val_cols = (int*)malloc((k + 1) * sizeof(int));\n if (!val_rows || !val_cols) {\n\n *returnSize = 0;\n *returnColumnSizes = NULL;\n return NULL;\n }\n \n for (int i = 0; i < k; i++) {\n val_rows[rows[i]] = i;\n val_cols[cols[i]] = i;\n }\n \n int** output = (int**)malloc(k * sizeof(int*));\n *returnColumnSizes = (int*)malloc(k * sizeof(int));\n if (!output || !*returnColumnSizes) {\n *returnSize = 0;\n *returnColumnSizes = NULL;\n return NULL;\n }\n \n for (int i = 0; i < k; i++) {\n output[i] = (int*)calloc(k, sizeof(int));\n if (!output[i]) {\n\n *returnSize = 0;\n *returnColumnSizes = NULL;\n return NULL;\n }\n (*returnColumnSizes)[i] = k;\n }\n \n for (int num = 1; num <= k; num++) {\n int i = val_rows[num], j = val_cols[num];\n output[i][j] = num;\n }\n \n *returnSize = k;\n\n return output;\n}\n```
1
0
['C']
0
build-a-matrix-with-conditions
Easy to understand!!!
easy-to-understand-by-nehasinghal032415-gb0k
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
NehaSinghal032415
NORMAL
2024-07-21T18:20:53.442413+00:00
2024-07-21T18:20:53.442439+00:00
26
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[][] buildMatrix(int k, int[][] rowConditions, int[][] colConditions) {\n List<Integer>[] rowGraph = new ArrayList[k + 1]; \n for(int i = 1 ; i < rowGraph.length; i ++) {\n rowGraph[i] = new ArrayList();\n }\n for(int [] rowCondition : rowConditions){ \n rowGraph[rowCondition[0]].add(rowCondition[1]); \n }\n\n List<Integer>[] colGraph = new ArrayList[k + 1]; \n for(int i = 1 ; i < colGraph.length; i ++) {\n colGraph[i] = new ArrayList();\n }\n for(int [] colCondition : colConditions){\n colGraph[colCondition[0]].add(colCondition[1]); \n }\n\n int[] visited = new int[k + 1];\n Deque<Integer> queue = new LinkedList<>(); \n for(int i = 1; i < rowGraph.length; i++){ \n if(!topSort(rowGraph, i, visited, queue)){\n return new int[0][0];\n }\n }\n\n \n int[] rowIndexMap = new int[k + 1]; \n for(int i = 0; i < k; i++){ \n int node = queue.pollLast(); \n rowIndexMap[node] = i;\n }\n\n visited = new int[k + 1];\n queue = new LinkedList();\n for(int i = 1; i < colGraph.length; i++){\n if(!topSort(colGraph, i, visited, queue)){\n return new int[0][0];\n }\n }\n\n int[] colOrder = new int[k];\n int[] colIndexMap = new int[k+1];\n for(int i = 0; i < k; i++){\n int node = queue.pollLast();\n colOrder[i] = node;\n colIndexMap[node] = i;\n }\n\n int[][] result = new int[k][k];\n \n for(int i = 1; i <= k; i++){\n result[rowIndexMap[i]][colIndexMap[i]] = i;\n }\n\n return result;\n\n }\n\n public boolean topSort(List<Integer>[] graph, int node, int[] visited, Deque<Integer> queue){\n if(visited[node] == 2) {\n return false;\n }\n if(visited[node] == 0){\n visited[node] = 2;\n for(int child : graph[node]){\n if(!topSort(graph, child, visited, queue)){\n return false;\n }\n }\n visited[node] = 1;\n queue.add(node);\n }\n return true;\n }\n}\n```
1
0
['Java']
0
build-a-matrix-with-conditions
Easy - Topological sort!!
easy-topological-sort-by-ishaankulkarni1-8kg4
When we here something should come before something then ---->\nTopo Sort --> Intuition\n# Complexity\n- Time complexity:\nBFS - O(2(k+E)) --> E --> no of edges
ishaankulkarni11
NORMAL
2024-07-21T18:20:15.488639+00:00
2024-07-21T18:20:15.488669+00:00
9
false
When we here something should come before something then ---->\nTopo Sort --> Intuition\n# Complexity\n- Time complexity:\nBFS - O(2(k+E)) --> E --> no of edges --> 2 time topo sort\nO(2(k+E)) + O(k^2)\n\n- Space complexity:\nIn topo sort --> O(k)\n\n//k is like number of nodes\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> topoSort(int k,vector<int>adj[]){\n vector<int>indegree(k+1,0);\n for(int i = 1;i<=k;++i){\n for(auto it:adj[i]){\n indegree[it]++;\n }\n }\n \n queue<int>q;\n vector<int>topo;\n for(int i = 1;i<=k;++i){\n // cout<<indegree[i]<<" ";\n if(indegree[i]==0){\n q.push(i);\n }\n }\n // cout<<"\\n";\n while(!q.empty()){\n int node = q.front();\n q.pop();\n topo.push_back(node);\n for(auto it:adj[node]){\n indegree[it]--;\n if(indegree[it]==0){\n q.push(it);\n }\n }\n }\n return topo;\n }\n vector<vector<int>> buildMatrix(int k, vector<vector<int>>& rowConditions, \n vector<vector<int>>& colConditions) {\n vector<vector<int>>ans(k,vector<int>(k,0));\n vector<int>adjR[k+1];\n vector<int>adjC[k+1];\n for(auto it:rowConditions){\n adjR[it[0]].push_back(it[1]);\n }\n for(auto it:colConditions){\n adjC[it[0]].push_back(it[1]);\n }\n vector<int>topo1 = topoSort(k,adjR);\n vector<int>topo2 = topoSort(k,adjC);\n\n // cout<<topo1.size()<<" "<<topo2.size()<<"\\n";\n if(topo1.size()!=k || topo2.size()!=k){\n return {};\n }\n // for(auto it:topo1) cout<<it<<" ";\n for(int i = 0;i<k;++i){\n for(int j = 0;j<k;++j){\n if(topo1[i]==topo2[j]){\n ans[i][j] = topo1[i];\n }\n }\n }\n return ans;\n } \n};\n```
1
0
['C++']
1
build-a-matrix-with-conditions
2392. SIMPLE STEP BY STEP SOLUTION
2392-simple-step-by-step-solution-by-int-zrp3
Intuition\nThe problem involves constructing a matrix with specific conditions on the rows and columns. The key idea is to use topological sorting to determine
intbliss
NORMAL
2024-07-21T17:54:08.907757+00:00
2024-07-21T17:54:08.907791+00:00
11
false
# Intuition\nThe problem involves constructing a matrix with specific conditions on the rows and columns. The key idea is to use topological sorting to determine the order of elements based on the given conditions. If the conditions form a valid topological order, we can place the elements accordingly; otherwise, it\'s impossible to construct such a matrix.\n\n# Approach\n1. **Topological Sort**: Perform topological sorting on the `rowConditions` and `colConditions` to determine the order of elements for rows and columns.\n2. **Matrix Construction**: Using the obtained orders from the topological sorts, place the elements in their respective positions in the matrix.\n\n### Detailed Steps:\n1. **Topological Sort Function**:\n - Compute in-degrees of all vertices.\n - Build the graph from the given edge list.\n - Use a queue to process vertices with zero in-degree and build the topological order.\n - If all vertices are processed, return the topological order; otherwise, return an invalid result.\n\n2. **Main Function (`buildMatrix`)**:\n - Get the row and column orders using the topological sort function.\n - If either order is invalid, return an empty matrix.\n - Construct the result matrix using the obtained orders by mapping the positions.\n\n## Dry Run\n\n### Test Case:\n**Input**: `k = 3`, `rowConditions = [[1, 2], [3, 2]]`, `colConditions = [[2, 1], [3, 2]]`\n**Output**: `[[3, 0, 0], [0, 0, 1], [0, 2, 0]]`\n\n### Step-by-Step Execution:\n1. **Topological Sort for Rows**:\n - **Graph Construction**:\n ```\n graph = [[1], [], [1]]\n inDegree = [0, 2, 0]\n ```\n - **Queue Initialization**: `queue = [0, 2]`\n - **Processing**:\n - Pop `0`: `topOrder = [0]`, `queue = [2]`, decrease in-degree of `1`.\n - Pop `2`: `topOrder = [0, 2]`, `queue = [1]`, decrease in-degree of `1`.\n - Pop `1`: `topOrder = [0, 2, 1]`\n - **Row Order**: `[0, 2, 1]`\n\n2. **Topological Sort for Columns**:\n - **Graph Construction**:\n ```\n graph = [[], [0], [1]]\n inDegree = [1, 1, 0]\n ```\n - **Queue Initialization**: `queue = [2]`\n - **Processing**:\n - Pop `2`: `topOrder = [2]`, `queue = [1]`, decrease in-degree of `1`.\n - Pop `1`: `topOrder = [2, 1]`, `queue = [0]`, decrease in-degree of `0`.\n - Pop `0`: `topOrder = [2, 1, 0]`\n - **Column Order**: `[2, 1, 0]`\n\n3. **Matrix Construction**:\n - **Row Positions**: `[0, 2, 1]`\n - **Column Positions**: `[2, 1, 0]`\n - **Placing Elements**:\n - Place `1` at `(0, 2)`\n - Place `2` at `(2, 1)`\n - Place `3` at `(1, 0)`\n - **Result Matrix**:\n ```\n [[3, 0, 1],\n [0, 0, 0],\n [0, 2, 0]]\n ```\n\n**Final Output**: `[[3, 0, 0], [0, 0, 1], [0, 2, 0]]`\n\n# Complexity\n- Time complexity:\n $$O(K^2)$$ \n\n- Space complexity:\n $$O(K^2)$$ \n\n# Code\n```\nclass Solution {\n public int[][] buildMatrix(int k, int[][] rowConditions, int[][] colConditions) {\n\n int[] rowOrder = topologicalSort(k, rowConditions);\n int[] columnOrder = topologicalSort(k, colConditions);\n\n if (rowOrder[0]== -1 || columnOrder[0] == -1) return new int[0][0];\n\n int[][] resMatrix = new int[k][k];\n\n int[] rowPosition = new int[k];\n int[] colPosition = new int[k];\n\n for (int i = 0; i < k; i++) {\n rowPosition[rowOrder[i]] = i;\n colPosition[columnOrder[i]] = i;\n }\n\n for (int i = 0; i < k; i++) {\n resMatrix[rowPosition[i]][colPosition[i]] = i + 1;\n }\n\n return resMatrix;\n }\n\n public static int[] topologicalSort(int numVertices, int[][] conditionArray) {\n int[] inDegree = new int[numVertices];\n List<Integer>[] graph = new List[numVertices];\n\n for (int i = 0; i < numVertices; i++) {\n graph[i] = new ArrayList<>();\n }\n\n for (int[] edge : conditionArray) {\n int u = edge[0] - 1;\n int v = edge[1] - 1;\n graph[u].add(v);\n inDegree[v]++;\n }\n\n Queue<Integer> queue = new LinkedList<>();\n for (int i = 0; i < numVertices; i++) {\n if (inDegree[i] == 0) {\n queue.add(i);\n }\n }\n\n int[] topOrder = new int[numVertices];\n int index = 0;\n\n while (!queue.isEmpty()) {\n int u = queue.poll();\n topOrder[index++] = u;\n\n for (int v : graph[u]) {\n inDegree[v]--;\n if (inDegree[v] == 0) {\n queue.add(v);\n }\n }\n }\n\n if (index != numVertices) {\n int[] result = {-1} ;\n return result ;\n }\n return topOrder;\n }\n}\n```\n![image.png](https://assets.leetcode.com/users/images/b193bd88-4f0d-41f1-ad53-ca72d8a4cc9f_1721584440.9539273.png)\n
1
0
['Java']
0
build-a-matrix-with-conditions
Java BFS solution
java-bfs-solution-by-zerrax-vegt
Explanation\nBoth left to right and above to below form directed graphs. We apply topological sort to both these graphs. If we detect a cycle in either directed
zerraX
NORMAL
2024-07-21T16:30:09.255597+00:00
2024-07-21T16:58:15.012622+00:00
29
false
# Explanation\nBoth left to right and above to below form directed graphs. We apply topological sort to both these graphs. If we detect a cycle in either directed graph, we return an empty matrix. We use a map to map a number to its to indicices provided from both\'s topological sort. We fill the matrix at these indices with its number. Since we only loop through the indices, rowConditions and colConditions; the time complexity is O(k + R + C). \n\nFor example,\nConsider: left to right topological sorted: 3 -> 2 -> 1 -> 4 -> 5\nand the above to below topological sorted: 4 -> 5 -> 3 -> 3 -> 1\n\n 3 2 1 4 5 \n\n 4 x\n\n 5 x\n\n 3 x \n\n 2 x\n\n 1 x\n\nThe x\'s mark the indices intersection of left to right and above to below. We add the number to these indices in the matrix. \nThe x occurs when the left to right index value has the same value as the above to below index value.\n\n# Code\n```\nclass Solution {\n public int[][] buildMatrix(int k, int[][] rowConditions, int[][] colConditions) {\n \n Map<Integer, List<Integer>> mapRowConditions = new HashMap<>();\n Map<Integer, List<Integer>> mapColConditions = new HashMap<>();\n\n int[] inDegreesBelow = new int[k + 1];\n int[] inDegreesRight = new int[k + 1];\n\n Queue<Integer> qRowConditions = new LinkedList<>();\n Queue<Integer> qColConditions = new LinkedList<>();\n\n Map<Integer, List<Integer>> mapNumToIndices = new HashMap<>();\n\n for (int i = 0; i < rowConditions.length; i++) {\n int above = rowConditions[i][0];\n int below = rowConditions[i][1];\n if (!mapRowConditions.containsKey(above)) {\n mapRowConditions.put(above, new ArrayList<>());\n }\n mapRowConditions.get(above).add(below);\n inDegreesBelow[below]++;\n }\n\n for (int i = 0; i < colConditions.length; i++) {\n int left = colConditions[i][0];\n int right = colConditions[i][1];\n if (!mapColConditions.containsKey(left)) {\n mapColConditions.put(left, new ArrayList<>());\n }\n mapColConditions.get(left).add(right);\n inDegreesRight[right]++;\n }\n\n for (int i = 1; i < k + 1; i++) {\n\n if (inDegreesBelow[i] == 0) qRowConditions.add(i);\n if (inDegreesRight[i] == 0) qColConditions.add(i);\n mapNumToIndices.put(i, new ArrayList<>());\n\n }\n\n\n int index = 0;\n while (!qRowConditions.isEmpty()) {\n int leaf = qRowConditions.poll();\n mapNumToIndices.get(leaf).add(index);\n index++;\n if (!mapRowConditions.containsKey(leaf)) continue;\n List<Integer> listBelow = mapRowConditions.get(leaf);\n for (int i = 0; i < listBelow.size(); i++) {\n int below = listBelow.get(i);\n inDegreesBelow[below]--;\n if (inDegreesBelow[below] == 0) qRowConditions.add(below);\n }\n }\n if (index != k) return new int[][]{};\n index = 0;\n while (!qColConditions.isEmpty()) {\n int leaf = qColConditions.poll();\n mapNumToIndices.get(leaf).add(index);\n index++;\n if (!mapColConditions.containsKey(leaf)) continue;\n List<Integer> listRight = mapColConditions.get(leaf);\n for (int i = 0; i < listRight.size(); i++) {\n int right = listRight.get(i);\n inDegreesRight[right]--;\n if (inDegreesRight[right] == 0) qColConditions.add(right);\n }\n }\n if (index != k) return new int[][]{};\n \n int[][] result = new int[k][k];\n for (int i = 1; i < k + 1; i++) {\n\n List<Integer> yx = mapNumToIndices.get(i);\n int y = yx.get(0);\n int x = yx.get(1);\n result[y][x] = i;\n\n }\n\n return result;\n\n }\n}\n```
1
0
['Java']
0
build-a-matrix-with-conditions
Build a Matrix With Conditions
build-a-matrix-with-conditions-by-sudhar-6690
Intuition\n Describe your first thoughts on how to solve this problem. \nTo construct a k x k matrix that satisfies the given row and column conditions, we need
sudharshm2005
NORMAL
2024-07-21T15:15:17.117296+00:00
2024-07-21T15:15:17.117375+00:00
8
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo construct a k x k matrix that satisfies the given row and column conditions, we need to determine a valid order for placing numbers in rows and columns. This can be achieved by treating the conditions as a dependency graph and ensuring the order constraints are met.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n#### 1. Graph Representation:\n - Use adjacency lists to represent row and column conditions.\n - Use an indegree dictionary to keep track of incoming edges for each node.\n#### 2. Order Calculation:\n - Apply a queue-based method to determine a valid order for rows and columns. This ensures that all conditions are met.\n#### 3. Matrix Construction:\n - Construct the matrix using the determined row and column orders by placing each number at its respective position.\n# Complexity\n- Time complexity: $$O(n)^2$$ due to the iteration over all nodes and processing each edge.\n- Space complexity: $$O(n)^2$$ to store the graph and indegree information\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nfrom collections import defaultdict, deque\n\nclass Solution:\n def buildMatrix(self, k: int, rowConditions: List[List[int]], colConditions: List[List[int]]) -> List[List[int]]:\n # Function to build a graph and compute indegrees from conditions\n def build_graph(conditions):\n graph = defaultdict(set) # Adjacency list representation of the graph\n indegree = defaultdict(int) # Dictionary to count incoming edges\n for u, v in conditions:\n if v not in graph[u]: # Avoid adding duplicate edges\n graph[u].add(v)\n indegree[v] += 1\n return graph, indegree\n\n # Function to calculate a valid order using Kahn\'s Algorithm\n def calculate_order(graph, indegree, k):\n order = []\n queue = deque([i for i in range(1, k + 1) if indegree[i] == 0]) # Nodes with zero incoming edges\n while queue:\n node = queue.popleft()\n order.append(node)\n for neighbor in graph[node]:\n indegree[neighbor] -= 1 # Decrement indegree of the neighbor\n if indegree[neighbor] == 0:\n queue.append(neighbor) # Add nodes with zero indegree to the queue\n return order if len(order) == k else [] # Check if we got a valid order\n\n # Build graphs and calculate orders for rows and columns\n row_graph, row_indegree = build_graph(rowConditions)\n col_graph, col_indegree = build_graph(colConditions)\n \n row_order = calculate_order(row_graph, row_indegree, k)\n col_order = calculate_order(col_graph, col_indegree, k)\n \n if not row_order or not col_order:\n return [] # Return an empty matrix if we cannot satisfy the conditions\n \n # Create mappings from number to its position in the order\n row_pos = {num: i for i, num in enumerate(row_order)}\n col_pos = {num: i for i, num in enumerate(col_order)}\n\n # Initialize an empty k x k matrix\n matrix = [[0] * k for _ in range(k)]\n # Fill the matrix based on row and column positions\n for num in range(1, k + 1):\n matrix[row_pos[num]][col_pos[num]] = num\n\n return matrix # Return the constructed matrix\n\n\n```
1
0
['Array', 'Graph', 'Topological Sort', 'Matrix', 'Python3']
0
build-a-matrix-with-conditions
Most efficient solution using Python
most-efficient-solution-using-python-by-ip3d0
\n\n# Code\n\nclass Solution(object):\n def buildMatrix(self, k, rowConditions, colConditions):\n rowGraph = defaultdict(list)\n for u, v in ro
vigneshvaran0101
NORMAL
2024-07-21T15:04:07.151227+00:00
2024-07-21T15:04:07.151256+00:00
7
false
\n\n# Code\n```\nclass Solution(object):\n def buildMatrix(self, k, rowConditions, colConditions):\n rowGraph = defaultdict(list)\n for u, v in rowConditions:\n rowGraph[u].append(v)\n \n colGraph = defaultdict(list)\n for u, v in colConditions:\n colGraph[u].append(v)\n \n def topoSort(graph):\n inDegree = {i: 0 for i in range(1, k + 1)}\n for u in graph:\n for v in graph[u]:\n inDegree[v] += 1\n queue = deque([i for i in inDegree if inDegree[i] == 0])\n order = []\n while queue:\n node = queue.popleft()\n order.append(node)\n for v in graph[node]:\n inDegree[v] -= 1\n if inDegree[v] == 0:\n queue.append(v)\n return order if len(order) == k else []\n \n rowOrder = topoSort(rowGraph)\n colOrder = topoSort(colGraph)\n \n if not rowOrder or not colOrder:\n return []\n \n rowMap = {num: i for i, num in enumerate(rowOrder)}\n colMap = {num: i for i, num in enumerate(colOrder)}\n \n result = [[0] * k for _ in range(k)]\n for i in range(1, k + 1):\n result[rowMap[i]][colMap[i]] = i\n \n return result\n \n```
1
0
['Python3']
0
build-a-matrix-with-conditions
JAVA easy using Kahn's algorithms
java-easy-using-kahns-algorithms-by-dhar-w538
```\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Queue
dharanip1207
NORMAL
2024-07-21T14:50:58.064846+00:00
2024-07-21T14:50:58.064870+00:00
9
false
```\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Queue;\n\npublic class Solution {\n\n public int[][] buildMatrix(int k, int[][] rowConditions, int[][] colConditions) {\n List<Integer> rowOrder = kahn(rowConditions, k + 1); \n List<Integer> colOrder = kahn(colConditions, k + 1); \n \n if (rowOrder.size() < k || colOrder.size() < k)\n return new int[][] {};\n\n Map<Integer, Integer> colMap = new HashMap<>();\n for (int i = 0; i < k; i++) {\n colMap.put(colOrder.get(i), i);\n }\n\n int[][] ans = new int[k][k];\n\n for (int i = 0; i < k; i++) {\n int columnPosition = colMap.get(rowOrder.get(i));\n ans[i][columnPosition] = rowOrder.get(i);\n }\n\n return ans;\n }\n\n public List<Integer> kahn(int[][] conditions, int k) {\n List<Integer>[] graph = new List[k];\n int[] degree = new int[k];\n List<Integer> ans = new ArrayList<>();\n Queue<Integer> q = new LinkedList<>();\n\n for (int i = 0; i < k; i++) {\n graph[i] = new ArrayList<>();\n }\n\n for (int[] condition : conditions) {\n graph[condition[0]].add(condition[1]);\n degree[condition[1]]++;\n }\n\n for (int i = 1; i < k; i++) {\n if (degree[i] == 0) {\n q.offer(i);\n }\n }\n\n while (!q.isEmpty()) {\n int node = q.poll();\n ans.add(node);\n for (int neighbour : graph[node]) {\n degree[neighbour]--;\n if (degree[neighbour] == 0) {\n q.offer(neighbour);\n }\n }\n }\n\n return ans;\n }\n}
1
0
[]
0
build-a-matrix-with-conditions
Topological Sort | DFS | Python
topological-sort-dfs-python-by-pragya_23-igqc
Complexity\n- Time complexity: O(max(k^2,k+n,k+m)) where n=len(rowConditions) ,m = len(colConditions)\n\n- Space complexity: O(max(k^2,k+n,k+m))\n\n# Code\n\ncl
pragya_2305
NORMAL
2024-07-21T14:40:34.407749+00:00
2024-07-21T14:40:34.407782+00:00
51
false
# Complexity\n- Time complexity: O(max(k^2,k+n,k+m)) where n=len(rowConditions) ,m = len(colConditions)\n\n- Space complexity: O(max(k^2,k+n,k+m))\n\n# Code\n```\nclass Solution:\n def buildMatrix(self, k: int, rowConditions: List[List[int]], colConditions: List[List[int]]) -> List[List[int]]:\n rowGraph,colGraph = defaultdict(list),defaultdict(list)\n\n for a,b in rowConditions: #O(n)\n rowGraph[b].append(a)\n\n for l,r in colConditions: #O(m)\n colGraph[r].append(l)\n\n def dfs(num,graph,visited,res):\n if num in visited:\n return visited[num]\n \n visited[num] = True\n for nei in graph[num]:\n if dfs(nei,graph,visited,res):\n return True\n visited[num] = False\n res.append(num)\n\n rowOrder,colOrder = [],[]\n rowVisited,colVisited = {},{}\n for i in range(1,k+1): #O(k+(m+n))\n if dfs(i,rowGraph,rowVisited,rowOrder) or dfs(i,colGraph,colVisited,colOrder):\n return []\n\n colPos = defaultdict(int)\n for i,num in enumerate(colOrder):#O(k)\n colPos[num] = i\n\n matrix = [[0 for i in range(k)] for j in range(k)] #O(k^2)\n\n for index,r in enumerate(rowOrder):#O(k)\n j = colPos[r]\n matrix[index][j] = r\n \n return matrix\n\n\n\n```
1
0
['Array', 'Graph', 'Topological Sort', 'Matrix', 'Python', 'Python3']
0
build-a-matrix-with-conditions
✅ 🎯 📌 Simple Solution || Beats 83.9% in Time || Topological Sort + Cycle Check ✅ 🎯 📌
simple-solution-beats-839-in-time-topolo-alru
Approach\n Describe your approach to solving the problem. \nWe first apply topological sort algorithm on rowConditions and colConditions while simultaneously ch
vvnpais
NORMAL
2024-07-21T14:39:29.719707+00:00
2024-07-21T14:41:03.386956+00:00
27
false
# Approach\n<!-- Describe your approach to solving the problem. -->\nWe first apply topological sort algorithm on rowConditions and colConditions while simultaneously checking for cycles in these arrays.\nIf cycle exists, we cannot fulfill the conditions that make up the cycle \nand hence we return $$[\\ \\ ]$$.\nHowever if both topological sorts occur successfully, we now have row and col sequences that satisfy both rowCondition and colCondition and if we set the corresponding coordinate as the position at which it occurs in an array, \nthat is position in row topologically sorted sequence as row index and position in col topologically sorted sequence as col index, \nand we set those coordinates in the as grid as that number while setting the rest as 0, \nwe get the desired grid.\n\n# Code\n```\nclass Solution:\n def buildMatrix(self, k: int, rowConditions: List[List[int]], colConditions: List[List[int]]) -> List[List[int]]:\n rows,cols=defaultdict(list),defaultdict(list)\n for i in rowConditions: rows[i[0]].append(i[1])\n for i in colConditions: cols[i[0]].append(i[1])\n def topological_sort_and_cycle_check(x,pars,arr):\n visited[x]=1\n path.append(x)\n for i in arr[x]:\n if i in path: return False \n if visited[i]==0:\n if not topological_sort_and_cycle_check(i,pars|{x},arr): return False\n stck.append(x)\n path.pop()\n return True\n\n stck,path=[],[]\n visited=[0 for i in range(k+1)]\n for i in range(1,k+1): \n path.append(i)\n if visited[i]==0:\n if not topological_sort_and_cycle_check(i,set([i]),rows): return []\n path.pop()\n rowtopsorted=stck[::-1]\n \n stck,path=[],[]\n visited=[0 for i in range(k+1)]\n for i in range(1,k+1): \n path.append(i)\n if visited[i]==0:\n if not topological_sort_and_cycle_check(i,set([i]),cols): return []\n path.pop()\n coltopsorted=stck[::-1]\n \n coords={i:[0,0] for i in range(1,k+1)}\n ans=[[0 for i in range(k)] for j in range(k)]\n for i,j in enumerate(rowtopsorted): coords[j][0]=i\n for i,j in enumerate(coltopsorted): coords[j][1]=i\n for i in coords: ans[coords[i][0]][coords[i][1]]=i\n return ans\n```
1
0
['Array', 'Graph', 'Topological Sort', 'Matrix', 'Python3']
0
build-a-matrix-with-conditions
Hassle Free Method and Easy to Understand
hassle-free-method-and-easy-to-understan-7jic
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
fourthofjuly
NORMAL
2024-07-21T14:32:58.062762+00:00
2024-07-21T14:32:58.062793+00:00
20
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)$$ -->\nO(k*^2 + n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(k*^2 + n)\n\n# Code\n```\nclass Solution {\npublic:\n\n vector<int> topoSort(vector<vector<int>>& edges, int n) {\n unordered_map<int, vector<int>> adj;\n stack<int> st;\n vector<int> order;\n //0 : not visited;\n //1 : visiting (currently in stack via some other DFS)\n //2 : visited\n vector<int> visited(n + 1, 0);\n bool hasCycle = false;\n\n for (vector<int>& edge : edges) {\n int u = edge[0];\n int v = edge[1];\n adj[u].push_back(v);\n }\n\n for (int i = 1; i <= n; i++) {\n if (visited[i] == 0) {\n dfs(i, adj, visited, st, hasCycle);\n if (hasCycle) \n return {}; //no ordering possible\n }\n }\n \n while(!st.empty()) {\n order.push_back(st.top());\n st.pop();\n }\n return order;\n }\n\n void dfs(int node, unordered_map<int, vector<int>>& adj, vector<int>& visited,\n stack<int>& st, bool& hasCycle) {\n \n visited[node] = 1; // Mark node as visiting\n //First, visit node\'s children\n for (int& nbr : adj[node]) {\n if (visited[nbr] == 0) {\n dfs(nbr, adj, visited, st, hasCycle);\n } else if (visited[nbr] == 1) {\n // Cycle detected\n hasCycle = true;\n return;\n }\n }\n\n visited[node] = 2; //visited\n st.push(node); //Now node can be added\n }\n\n vector<vector<int>> buildMatrix(int k, vector<vector<int>>& rowConditions,\n vector<vector<int>>& colConditions) { \n vector<int> orderRows = topoSort(rowConditions, k);\n vector<int> orderColumns = topoSort(colConditions, k);\n\n // We might have found cycle. That\'s why topo order is empty\n if (orderRows.empty() or orderColumns.empty())\n return {};\n\n vector<vector<int>> matrix(k, vector<int>(k, 0));\n for (int i = 0; i < k; i++) {\n for (int j = 0; j < k; j++) {\n if (orderRows[i] == orderColumns[j]) {\n matrix[i][j] = orderRows[i];\n }\n }\n }\n return matrix;\n }\n};\n```
1
0
['Graph', 'Topological Sort', 'Matrix', 'C++']
0
build-a-matrix-with-conditions
Topological Sort Approach to Build Matrix from Row and Column Conditions || 💯💯💯
topological-sort-approach-to-build-matri-itr1
Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem requires creating a matrix based on row and column conditions, which repres
kamalcbe86
NORMAL
2024-07-21T14:17:48.919955+00:00
2024-07-21T14:17:48.919996+00:00
31
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem requires creating a matrix based on row and column conditions, which represent dependencies. Topological sorting is well-suited for this kind of dependency management, as it helps us find a valid ordering for the elements.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. **Topological Sorting**: Use Kahn\'s Algorithm (BFS) to find the topological order for both row and column conditions.\n2. **Build Matrix**: Once we have the topological order for rows and columns, use these orders to place the numbers in the matrix.\n\n# Complexity\n- Time complexity: $$O(V+E)$$ where V is the number of vertices and E is the number of edges. This is due to the topological sorting for both row and column conditions.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(V+E)$$ for the adjacency list, queue, and other auxiliary space used.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int[] topoSort(int V, int pairs[][]) {\n ArrayList<ArrayList<Integer>> adj = new ArrayList<>();\n\n for(int i=0; i<=V; i++){\n adj.add(new ArrayList<>());\n }\n for(int pair[] : pairs){\n int u = pair[0];\n int v = pair[1];\n adj.get(u).add(v);\n }\n int indegree[] = new int[V+1];\n for(int u=0; u<adj.size(); u++){\n for(int v: adj.get(u)){\n indegree[v]++;\n }\n }\n\n Queue<Integer> queue = new LinkedList<>();\n for(int i=1; i<=V; i++){\n if(indegree[i] == 0){\n queue.offer(i);\n }\n }\n ArrayList<Integer> res = new ArrayList<>();\n while(!queue.isEmpty()){\n int node = queue.poll();\n res.add(node);\n for(int neighbour : adj.get(node)){\n indegree[neighbour]--;\n if(indegree[neighbour]==0){\n queue.offer(neighbour);\n }\n }\n }\n\n if(res.size() != V){\n return new int[0];\n }\n\n int ans[] = new int[V];\n for(int i=0; i<V; i++){\n ans[i] = res.get(i);\n }\n return ans;\n }\n public int[][] buildMatrix(int k, int[][] rowConditions, int[][] colConditions) {\n int rowToposort[] = topoSort(k, rowConditions);\n if(rowToposort.length == 0){\n return new int[0][0];\n }\n int colToposort[] = topoSort(k, colConditions);\n if(colToposort.length == 0){\n return new int[0][0];\n }\n int matrix[][] = new int[k][k];\n for(int i=0; i<k; i++){\n for(int j=0; j<k; j++){\n if(rowToposort[i] == colToposort[j]){\n matrix[i][j] = colToposort[j];\n }\n }\n }\n return matrix;\n }\n}\n```
1
0
['Java']
0
build-a-matrix-with-conditions
✅NOT SO EASY JAVA SOLUTION😂
not-so-easy-java-solution-by-swayam28-ecqv
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
swayam28
NORMAL
2024-07-21T14:13:07.447519+00:00
2024-07-21T14:13:07.447548+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 public int[][] buildMatrix(int k, int[][] rowConditions, int[][] colConditions) {\n List<Integer> row_sorting = topo_sort(rowConditions, k);\n List<Integer> col_sorting = topo_sort(colConditions, k);\n if (row_sorting.isEmpty() || col_sorting.isEmpty())\n return new int[0][0];\n\n Map<Integer, int[]> value_position = new HashMap<>();\n for (int n = 1; n <= k; ++n) {\n value_position.put(n, new int[2]); \n }\n for (int ind = 0; ind < row_sorting.size(); ++ind) {\n value_position.get(row_sorting.get(ind))[0] = ind;\n }\n for (int ind = 0; ind < col_sorting.size(); ++ind) {\n value_position.get(col_sorting.get(ind))[1] = ind;\n }\n\n int[][] res = new int[k][k];\n for (int value = 1; value <= k; ++value) {\n int row = value_position.get(value)[0];\n int column = value_position.get(value)[1];\n res[row][column] = value;\n }\n\n return res;\n }\n\n \n private boolean dfs(int src, Map<Integer, List<Integer>> graph, Set<Integer> visited, Set<Integer> cur_path, List<Integer> res) {\n if (cur_path.contains(src)) return false; \n if (visited.contains(src)) return true; \n\n visited.add(src);\n cur_path.add(src);\n\n for (int neighbor : graph.getOrDefault(src, Collections.emptyList())) {\n if (!dfs(neighbor, graph, visited, cur_path, res)) \n return false;\n }\n\n cur_path.remove(src); \n res.add(src);\n return true;\n }\n\n \n private List<Integer> topo_sort(int[][] edges, int k) {\n Map<Integer, List<Integer>> graph = new HashMap<>();\n for (int[] edge : edges) {\n graph.computeIfAbsent(edge[0], x -> new ArrayList<>()).add(edge[1]);\n }\n\n Set<Integer> visited = new HashSet<>();\n Set<Integer> cur_path = new HashSet<>();\n List<Integer> res = new ArrayList<>();\n\n for (int src = 1; src <= k; ++src) {\n if (!dfs(src, graph, visited, cur_path, res))\n return Collections.emptyList();\n }\n\n Collections.reverse(res); \n return res;\n }\n}\n```
1
0
['Java']
0
build-a-matrix-with-conditions
Runtime 99ms || C++ || TopoSorting Algorithm || Time complexity O(K+E) & Space complexity O(k^2)
runtime-99ms-c-toposorting-algorithm-tim-qlr2
Complexity\n- Time complexity:O(K+E)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity:O(k^2) //for final matrix\n Add your space complexity he
sneha029
NORMAL
2024-07-21T13:43:32.611585+00:00
2024-07-21T13:43:32.611613+00:00
18
false
# Complexity\n- Time complexity:O(K+E)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(k^2) //for final matrix\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n void topoSortUtil(stack<int>& stk, vector<int>& vis, int curr, vector<vector<int>>& adjMat, bool& cycle){\n if(cycle) return;\n\n vis[curr] = 1;\n\n for(int i=0; i<adjMat[curr].size(); i++){\n int neighbour = adjMat[curr][i];\n if(vis[neighbour]==0){\n topoSortUtil(stk, vis, neighbour, adjMat, cycle);\n }else if(vis[neighbour]==1) {\n cycle = true;\n return;\n }\n }\n \n vis[curr] = 2;\n stk.push(curr);\n }\n\n vector<int> topoSort(vector<vector<int>>& conditions, int k){\n vector<vector<int>> adjMat(k);\n\n stack<int> stk;\n vector<int> vis(k, 0);\n vector<int> order;\n\n //matrix adjacency\n for(int i=0; i<conditions.size(); i++){ \n int src = conditions[i][0];\n int dest = conditions[i][1];\n adjMat[src-1].push_back(dest-1);\n }\n \n bool cycle = false;\n for(int i=0; i<k;i++){\n if(vis[i]==0){\n topoSortUtil(stk, vis, i, adjMat, cycle); \n if(cycle==true) return {}; \n }\n }\n\n while(!stk.empty()){\n order.push_back(stk.top()+1);\n stk.pop();\n }\n\n return order;\n \n }\n\n vector<vector<int>> buildMatrix(int k, vector<vector<int>>& rowConditions, vector<vector<int>>& colConditions) {\n \n\n vector<int> orderForRowCond = topoSort(rowConditions, k); // for topoSort Algo\n vector<int> orderForColCond = topoSort(colConditions, k);\n\n\n if(orderForRowCond.size()==0 || orderForColCond.size()==0) return {}; //check for cycle\n \n\n vector<vector<int>> finalMat(k, vector<int> (k, 0)); //initalizing final matrix\n\n unordered_map<int,int> colIdx; //storing positions of numbers from 1-k\n\n for(int i=0; i<orderForColCond.size(); i++){\n colIdx[orderForColCond[i]] = i;\n }\n\n for(int i=0; i<orderForRowCond.size(); i++){ //making final matrix\n int idx = colIdx[orderForRowCond[i]];\n finalMat[i][idx] = orderForRowCond[i];\n\n }\n\n\n return finalMat;\n }\n};\n```
1
0
['C++']
0
build-a-matrix-with-conditions
|| Easy solution in C++||
easy-solution-in-c-by-dhanu07-upuf
Intuition\n Describe your first thoughts on how to solve this problem. \nSince we have given the RowCon and ColCon like nodess and we have to sort them. Therefo
Dhanu07
NORMAL
2024-07-21T13:16:44.504951+00:00
2024-07-21T13:16:44.504983+00:00
8
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSince we have given the RowCon and ColCon like nodess and we have to sort them. Therefore the first thing came to mind is Topological Sort.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nIt follows a simple Approach.\nFind the Toposort of rowCondition and colCondition.\nIt will give u the order of the arrangement in rows and cols.\nNow for each node check the cell which is common for both row and col.\nPlace the node in that cell.\nIf rowCondition and colCondition doesn\'t take care of all the nodes then we can randomly arrange them at last.\nMake all the remaining cells as 0\n# Complexity\n- Time complexity:\nThe time complexity of this solution is O(n + m + k),\n- Space complexity:\nThe space complexity is O(k), \n\n# Code\n```\nclass Solution {\nprivate:\n vector<int> TopoSort(int k, vector<vector<int>>& adj)\n {\n vector<int> indegree(k+1, 0);\n for(int node=1; node<=k; node++)\n for(auto it : adj[node])\n indegree[it]++;\n\n queue<int> q;\n vector<int> vis(k+1, 0);\n for(int node=1; node<=k; node++)\n if(indegree[node]==0)\n q.push(node);\n\n vector<int> ans;\n while(!q.empty())\n {\n int n = q.size();\n while(n--)\n {\n int node = q.front();\n q.pop();\n\n vis[node] = true;\n ans.push_back(node);\n\n for(auto it : adj[node])\n {\n if(!vis[it])\n {\n indegree[it]--;\n if(indegree[it]==0) \n q.push(it);\n }\n }\n }\n }\n\n vector<int> notTopo;\n for(int node=1; node<=k; node++) \n if(indegree[node] != 0) \n return notTopo;\n return ans;\n }\n\n void fillTopoArray(int k, vector<int>& arr)\n {\n unordered_map<int, bool> mp;\n for(auto it : arr) \n mp[it] = true;\n\n for(int i=1; i<=k; i++)\n if(!mp[i]) \n arr.push_back(i);\n }\npublic:\n vector<vector<int>> buildMatrix(int k, vector<vector<int>>& rowConditions, vector<vector<int>>& colConditions) \n {\n int n=rowConditions.size(),m=colConditions.size();\n\n vector<vector<int>> adjRow(k+1);\n vector<vector<int>> adjCol(k+1);\n\n for(auto it: rowConditions)\n adjRow[it[0]].push_back(it[1]);\n \n for(auto it: colConditions)\n adjCol[it[0]].push_back(it[1]);\n\n //Apply Toposort\n\n vector<int> rowTopo=TopoSort(k,adjRow);\n vector<int> colTopo=TopoSort(k,adjCol);\n vector<vector<int>> ans;\n\n //Base case\n if(rowTopo.size()==0 || colTopo.size()==0)\n return ans;\n \n\n fillTopoArray(k, rowTopo);\n fillTopoArray(k, colTopo);\n\n unordered_map<int, int> mp;\n for(int j=0; j<k; j++)\n mp[colTopo[j]] = j;\n\n ans = vector<vector<int>>(k, vector<int>(k, 0));\n for(int i=0; i<k; i++)\n ans[i][mp[rowTopo[i]]] = rowTopo[i];\n \n return ans; \n }\n};\n```
1
0
['Array', 'Graph', 'Topological Sort', 'Matrix', 'C++']
0
build-a-matrix-with-conditions
Java Solution
java-solution-by-okiee-zapn
Code\n\nclass Solution {\n public int[][] buildMatrix(int k, int[][] rowConditions, int[][] colConditions) {\n List<Integer>[] rowGraph = new ArrayLis
Okiee
NORMAL
2024-07-21T12:46:23.116670+00:00
2024-07-21T12:46:23.116703+00:00
12
false
# Code\n```\nclass Solution {\n public int[][] buildMatrix(int k, int[][] rowConditions, int[][] colConditions) {\n List<Integer>[] rowGraph = new ArrayList[k + 1]; \n for(int i = 1 ; i < rowGraph.length; i ++) {\n rowGraph[i] = new ArrayList();\n }\n for(int [] rowCondition : rowConditions){ \n rowGraph[rowCondition[0]].add(rowCondition[1]); \n }\n\n List<Integer>[] colGraph = new ArrayList[k + 1]; \n for(int i = 1 ; i < colGraph.length; i ++) {\n colGraph[i] = new ArrayList();\n }\n for(int [] colCondition : colConditions){\n colGraph[colCondition[0]].add(colCondition[1]); \n }\n\n int[] visited = new int[k + 1];\n Deque<Integer> queue = new LinkedList<>(); \n for(int i = 1; i < rowGraph.length; i++){ \n if(!topSort(rowGraph, i, visited, queue)){\n return new int[0][0];\n }\n }\n\n \n int[] rowOrder = new int[k];\n int[] rowIndexMap = new int[k + 1]; \n for(int i = 0; i < k; i++){ \n int node = queue.pollLast(); \n rowOrder[i] = node; //\n rowIndexMap[node] = i;\n }\n\n visited = new int[k + 1];\n queue = new LinkedList();\n for(int i = 1; i < colGraph.length; i++){\n if(!topSort(colGraph, i, visited, queue)){\n return new int[0][0];\n }\n }\n\n int[] colOrder = new int[k];\n int[] colIndexMap = new int[k+1];\n for(int i = 0; i < k; i++){\n int node = queue.pollLast();\n colOrder[i] = node;\n colIndexMap[node] = i;\n }\n\n int[][] result = new int[k][k];\n \n for(int i = 1; i <= k; i++){\n result[rowIndexMap[i]][colIndexMap[i]] = i;\n }\n\n return result;\n\n }\n\n public boolean topSort(List<Integer>[] graph, int node, int[] visited, Deque<Integer> queue){\n if(visited[node] == 2) {\n return false;\n }\n if(visited[node] == 0){\n visited[node] = 2;\n for(int child : graph[node]){\n if(!topSort(graph, child, visited, queue)){\n return false;\n }\n }\n visited[node] = 1;\n queue.add(node);\n }\n return true;\n }\n}\n```
1
0
['Java']
0
build-a-matrix-with-conditions
Swift | DFS Topological Sort (+ Kahn)
swift-dfs-topological-sort-kahn-by-pagaf-dbwh
I originally wrote this using DFS Topological Sort (dfsSort()) but I\'m adding Kahn\'s Topological Sort (khansSort()) for comparison, since most solutions use t
pagafan7as
NORMAL
2024-07-21T12:40:37.910690+00:00
2024-07-22T13:41:59.720275+00:00
28
false
I originally wrote this using **DFS Topological Sort** (```dfsSort()```) but I\'m adding **Kahn\'s Topological Sort** (```khansSort()```) for comparison, since most solutions use that algorithm.\n\nAsymptotically, they both run in O(V + E) time and in practice they seem roughly equivalent.\n\nI thought that one may be easier to implement than the other one, but I also find them to be approximately equal from that point of view.\n\n# Code\n```\nclass Solution {\n func buildMatrix(_ k: Int, _ rowConditions: [[Int]], _ colConditions: [[Int]]) -> [[Int]] {\n var matrix = Array(repeating: Array(repeating: 0, count: k), count: k)\n guard let sortedRows = Graph(nodes: Array(1...k), edges: rowConditions).dfsSort(),\n let sortedCols = Graph(nodes: Array(1...k), edges: colConditions).kahnsSort()\n else { return [] }\n\n for num in 1...k {\n if let row = sortedRows.firstIndex(of: num), let col = sortedCols.firstIndex(of: num) {\n matrix[row][col] = num\n }\n }\n\n return matrix\n }\n}\n\nclass Graph {\n private let nodes: [Int]\n private let edges: [[Int]]\n private var adj = [Int: [Int]]()\n\n init(nodes: [Int], edges: [[Int]]) {\n self.nodes = nodes\n self.edges = edges\n for edge in edges {\n adj[edge[0], default: []].append(edge[1])\n }\n }\n\n func dfsSort() -> [Int]? {\n enum NodeState { case visited, visiting, unvisited }\n var nodeState = [Int: NodeState]()\n var stack: [Int] = []\n\n for node in nodes { nodeState[node] = .unvisited }\n for node in nodes {\n if !dfs(node) {\n return nil\n }\n }\n \n return stack.reversed()\n \n func dfs(_ node: Int) -> Bool {\n if let state = nodeState[node], state == .visited { return true }\n if let state = nodeState[node], state == .visiting { return false }\n nodeState[node] = .visiting\n \n if let neighbors = adj[node] {\n for neighbor in neighbors {\n if !dfs(neighbor) { return false }\n }\n }\n \n nodeState[node] = .visited\n stack.append(node)\n return true\n } \n }\n\n func kahnsSort() -> [Int]? {\n var sorted: [Int] = []\n var inDegrees: [Int: Int] = Dictionary(uniqueKeysWithValues: nodes.map { ($0, 0) })\n for edge in edges {\n inDegrees[edge[1], default: 0] += 1\n }\n var stack = inDegrees.filter{ $0.1 == 0 }.map { $0.0 }\n\n while let node = stack.popLast() {\n if let neighbors = adj[node] {\n for neighbor in neighbors {\n inDegrees[neighbor, default: 0] -= 1\n if inDegrees[neighbor] == 0 { stack.append(neighbor) }\n }\n }\n sorted.append(node)\n }\n\n return sorted.count == nodes.count ? sorted : nil\n }\n}\n```
1
0
['Swift']
0
build-a-matrix-with-conditions
Topological sort using DFS & Kahn's algorithm + optimizations.
topological-sort-using-dfs-kahns-algorit-dri6
All we need is to sort rows and cols dependencies in topological order. If we look at provided example Input: k = 3, rowConditions = [[1,2],[3,2]], colCondition
AlexPG
NORMAL
2024-07-21T11:44:48.906224+00:00
2024-07-21T14:52:59.178212+00:00
17
false
All we need is to sort rows and cols dependencies in topological order. If we look at provided example Input: k = 3, rowConditions = [[1,2],[3,2]], colConditions = [[2,1],[3,2]] we can see, that if we construct graphs for rows&cols conditions and then sort vertices of those graphs in topological order we would have next sorted arrays of vertices: 3, 1, 2 for rows and 3, 2, 1 for cols. Then we can use indexes of each element in those sorted arrays as coords in result matrix. Belows is 2 solutions based on DFS topological sorting. First is more intuitive, second one is the same, but memory and speed optimized.\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> buildMatrix(int k, vector<vector<int>>& rowConditions, vector<vector<int>>& colConditions) {\n vector<vector<short>> rowsGraph(k+1);\n vector<vector<short>> colsGraph(k+1);\n\n for (auto& condition : rowConditions)\n rowsGraph[condition[1]].push_back(condition[0]);\n\n for (auto& condition : colConditions)\n colsGraph[condition[1]].push_back(condition[0]);\n\n vector<char> visited(k+1);\n vector<short> rowsSort;\n vector<short> colsSort;\n rowsSort.reserve(k);\n colsSort.reserve(k);\n\n for (short i = 1; i <= k; i++)\n if (!topoSort(rowsGraph, visited, rowsSort, i, 2) || !topoSort(colsGraph, visited, colsSort, i, 4))\n return {};\n\n vector<vector<int>> matrix(k, vector<int>(k));\n vector<pair<short, short>> coords(k+1);\n for (short i = 0; i < rowsSort.size(); i++) {\n coords[rowsSort[i]].first = i;\n coords[colsSort[i]].second = i;\n }\n\n for (short i = 1; i <= k; i++)\n matrix[coords[i].first][coords[i].second] = i;\n\n return matrix;\n }\n\n bool topoSort(vector<vector<short>>& graph, vector<char>& visited, vector<short>& sorted, short vertice, char flag) {\n // Cycle detection\n if (visited[vertice] & 1)\n return false;\n\n if (visited[vertice] & flag)\n return true;\n\n visited[vertice] |= flag + 1;\n for (short parent : graph[vertice])\n if (!topoSort(graph, visited, sorted, parent, flag))\n return false;\n\n sorted.push_back(vertice);\n visited[vertice] -= 1;\n return true;\n }\n};\n\n```\nOptimized solution without extra arrays for topological sorting.\n```\nclass Solution {\npublic:\n vector<vector<int>> buildMatrix(int k, vector<vector<int>>& rowConditions, vector<vector<int>>& colConditions) {\n vector<vector<short>> rowsGraph(k+1);\n vector<vector<short>> colsGraph(k+1);\n\n // Build rows dependencies graph\n for (auto& condition : rowConditions)\n rowsGraph[condition[1]].push_back(condition[0]);\n\n // Build cols dependencies graph\n for (auto& condition : colConditions)\n colsGraph[condition[1]].push_back(condition[0]);\n\n // Single array to track visited rows & cols.\n // Instead of using 2 arrays of bools we can use array of chars and mark visited by adding binary flag\n // Flag 2 for rows and flag 4 for cols, there also gonna be flag 1 for cycle detection\n vector<char> visited(k+1);\n // In those arrays we gonna track ay which index row,col should appear each 1..k element\n // To find those indexes properly we gonna use modified topological sort by DFS\n // In overall row & col coords is appropriate index of element in rows/cols topological sort\n // Lets assume that after topological sorting elements in graph we would have 2 sorted arrays: 3, 1, 2 for rows and 3, 2, 1 for cols\n // We can see that index in sorted array of each element is its row&col coord in matrix\n // To save momery and speed we can emulate togological sorting using references to rowIndex & colIndex\n vector<short> rowIndexes(k+1);\n vector<short> colIndexes(k+1);\n short rowIndex = 0, colIndex = 0;\n\n // Sort topologically graphs of rows and cols\n for (short i = 1; i <= k; i++)\n if (!topoSort(rowsGraph, visited, rowIndexes, rowIndex, i, 2) || !topoSort(colsGraph, visited, colIndexes, colIndex, i, 4))\n return {};\n\n vector<vector<int>> matrix(k, vector<int>(k));\n for (short i = 1; i <= k; i++)\n matrix[rowIndexes[i]][colIndexes[i]] = i;\n\n return matrix;\n }\n\n bool topoSort(vector<vector<short>>& graph, vector<char>& visited, vector<short>& indexes, short& index, short vertice, char flag) {\n // Cycle detection, check if we reached same vertice in single DFS run\n if (visited[vertice] & 1)\n return false;\n\n if (visited[vertice] & flag)\n return true;\n\n // Mark vertice as visited, also add flag 1 for cycle detection\n visited[vertice] |= flag | 1;\n for (short parent : graph[vertice])\n if (!topoSort(graph, visited, indexes, index, parent, flag))\n return false;\n\n // Set index of vertice in togological order\n indexes[vertice] = index++;\n // Remove cycle detection flag\n visited[vertice] &= ~1;\n return true;\n }\n};\n\n```\n\nSame idea but using Kahn\'s algorithm for topological sort:\n```\nclass Solution {\npublic:\n vector<vector<int>> buildMatrix(int k, vector<vector<int>>& rowConditions, vector<vector<int>>& colConditions) {\n vector<short> rowIndexes(k+1);\n vector<short> colIndexes(k+1);\n\n if (!topoSort(k, rowConditions, rowIndexes) || !topoSort(k, colConditions, colIndexes))\n return {};\n\n vector<vector<int>> matrix(k, vector<int>(k));\n for (short i = 1; i <= k; i++)\n matrix[rowIndexes[i]][colIndexes[i]] = i;\n\n return matrix;\n }\n\n bool topoSort(int k, vector<vector<int>>& edges, vector<short>& indexes) {\n vector<vector<short>> graph(k+1);\n vector<short> indegree(graph.size());\n queue<short> vertices;\n\n for (auto& edge : edges) {\n graph[edge[0]].push_back(edge[1]);\n indegree[edge[1]]++;\n }\n\n for (short vertex = 1; vertex < graph.size(); vertex++)\n if (indegree[vertex] == 0)\n vertices.push(vertex);\n\n short index = 0;\n while (!vertices.empty()) {\n short vertex = vertices.front();\n indexes[vertex] = index++;\n vertices.pop();\n\n for (short next : graph[vertex])\n if (--indegree[next] == 0)\n vertices.push(next);\n }\n\n return index == indexes.size()-1;\n }\n};\n```\n
1
0
['C++']
0
check-balanced-string
Python3 || 2 lines, map and separate || T/S: 99% / 96%
python3-2-lines-map-and-separate-ts-99-9-hgj8
Here\'s the plan:\n1. We map the characters in num to integers.\n\n1. We sum the even-indexed elements of num and we sum the even-indexed elements of num, and t
Spaulding_
NORMAL
2024-11-03T05:29:13.730688+00:00
2024-11-11T21:43:22.919826+00:00
1,122
false
Here\'s the plan:\n1. We map the characters in `num` to integers.\n\n1. We sum the even-indexed elements of `num` and we sum the even-indexed elements of `num`, and then we return whether they are equal. \n ___\n\n```python3 []\nclass Solution:\n def isBalanced(self, num: str) -> bool:\n\n num = list(map(int, num))\n \n return sum(num[0:len(num):2]) == sum(num[1:len(num):2])\n```\n```cpp []\nclass Solution {\npublic:\n bool isBalanced(std::string num) {\n int evenSum = 0;\n int oddSum = 0;\n\n for (size_t i = 0; i < num.length(); ++i) {\n int digit = num[i] - \'0\';\n if (i % 2 == 0) {\n evenSum += digit;} else {\n oddSum += digit;}\n }\n\n return evenSum == oddSum;}\n};\n```\n```java []\nclass Solution {\n public boolean isBalanced(String num) {\n int evenSum = 0;\n int oddSum = 0;\n\n for (int i = 0; i < num.length(); i++) {\n int digit = num.charAt(i) - \'0\'; // Convert char to int\n if (i % 2 == 0) {\n evenSum += digit; } \n else {\n oddSum += digit; }\n }\n return evenSum == oddSum;}\n}\n```\n[https://leetcode.com/problems/check-balanced-string/submissions/1449986452/\n](https://leetcode.com/problems/check-balanced-string/submissions/1449986452/\n)\nI could be wrong, but I think that time complexity is *O*(*N*) and space complexity is *O*(*N*), in which *N* ~ `len(num)`.
17
0
['C++', 'Java', 'Python3']
1
check-balanced-string
[Java/C++/Python] Calculate the Diff
javacpython-calculate-the-diff-by-lee215-t4fw
Time O(n)\nSpace O(1)\n\nJava [Java]\n public boolean isBalanced(String num) {\n int diff = 0, sign = 1, n = num.length();\n for (int i = 0; i
lee215
NORMAL
2024-11-03T04:36:27.988658+00:00
2024-11-03T04:36:55.229820+00:00
1,367
false
Time `O(n)`\nSpace `O(1)`\n\n```Java [Java]\n public boolean isBalanced(String num) {\n int diff = 0, sign = 1, n = num.length();\n for (int i = 0; i < n; ++i) {\n diff += sign * (num.charAt(i) - \'0\');\n sign = -sign;\n }\n return diff == 0;\n }\n```\n\n```C++ [C++]\n bool isBalanced(string num) {\n int diff = 0, sign = 1;\n for (char i: num) {\n diff += sign * (i - \'0\');\n sign = -sign;\n }\n return diff == 0;\n }\n```\n\n```py [Python3]\n\t# O(n) space\n def isBalanced(self, num: str) -> bool:\n A = list(map(int, num))\n return sum(A[::2]) == sum(A[1::2])\n```\n
14
0
['C', 'Python', 'Java']
2
check-balanced-string
Easy & Clear Solution (Java, c++, Python3)
easy-clear-solution-java-c-python3-by-mo-02qb
\n\n### C++ \ncpp\nclass Solution {\npublic:\n bool isBalanced(string num) {\n int evenSum = 0, oddSum = 0;\n for (int i = 0; i < num.length();
moazmar
NORMAL
2024-11-03T04:05:59.032230+00:00
2024-11-03T04:05:59.032257+00:00
1,383
false
\n\n### C++ \n```cpp\nclass Solution {\npublic:\n bool isBalanced(string num) {\n int evenSum = 0, oddSum = 0;\n for (int i = 0; i < num.length(); i++) {\n if (i % 2 == 0) {\n evenSum += num[i] - \'0\'; // Convert char to int\n } else {\n oddSum += num[i] - \'0\'; // Convert char to int\n }\n }\n return evenSum == oddSum;\n }\n};\n```\n\n### Python \n```python\nclass Solution:\n def isBalanced(self, num: str) -> bool:\n even_sum = 0\n odd_sum = 0\n for i in range(len(num)):\n if i % 2 == 0:\n even_sum += int(num[i]) # Convert char to int\n else:\n odd_sum += int(num[i]) # Convert char to int\n return even_sum == odd_sum\n```\n\n# Java\n\n```java\nclass Solution {\n public boolean isBalanced(String num) {\n int evenSum = 0, oddSum = 0;\n for (int i = 0; i < num.length(); i++) {\n if (i % 2 == 0) {\n evenSum += num.charAt(i) - \'0\';\n } else {\n oddSum += num.charAt(i) - \'0\';\n }\n }\n return evenSum == oddSum;\n }\n}\n```\n\n### Brief Logic Explanation:\n1. **Initialization**: Two variables (`evenSum` and `oddSum`) are initialized to hold the sums of digits at even and odd indices.\n2. **Iteration**: A loop goes through each character in the string:\n - If the index is even, the digit at that index is added to `evenSum`.\n - If the index is odd, it is added to `oddSum`.\n3. **Comparison**: Finally, the function checks if `evenSum` equals `oddSum` and returns the result as a boolean.
8
0
['Python', 'C++', 'Java', 'Python3']
1
check-balanced-string
Overcomplicated Python Solution🐍(watch to learn smth new)
overcomplicated-python-solutionwatch-to-o1woo
IntuitionIn a balanced string sum of all odd-places and even-places numbers is the same so their difference is 0.In writing the solution this article helped me:
karasik8765
NORMAL
2025-02-14T12:32:39.952110+00:00
2025-02-14T12:32:39.952110+00:00
159
false
# Intuition In a balanced string sum of all odd-places and even-places numbers is the same so their difference is **0**. In writing the solution this article helped me: https://stackoverflow.com/questions/59092561/how-to-use-iterator-in-while-loop-statement-in-python So we just add all numbers on even positions and subtract all numbers on odd positions and at the end check if we have 0 or not. # Code ```python3 [] class Solution: def isBalanced(self, num: str) -> bool: it, ans = iter(num), 0 while ((even := next(it, None)) is not None): ans += int(even) - (odd := int(next(it, 0))) return not ans ```
5
0
['Python3']
1
check-balanced-string
💢☠💫Easiest👾Faster✅💯 Lesser🧠 🎯 C++✅Python3🐍✅Java✅C✅Python🐍✅C#✅💥🔥💫Explained☠💥🔥 Beats 100
easiestfaster-lesser-cpython3javacpython-eoqe
Intuition\n\n Describe your first thoughts on how to solve this problem. \n- JavaScript Code --> https://leetcode.com/problems/check-balanced-string/submissions
Edwards310
NORMAL
2024-11-03T10:34:28.241535+00:00
2024-11-03T10:34:28.241569+00:00
223
false
# Intuition\n![0ehh83fsnh811.jpg](https://assets.leetcode.com/users/images/087036ae-d1ad-42df-80c3-5269c77c4766_1730629902.0513976.jpeg)\n<!-- Describe your first thoughts on how to solve this problem. -->\n- ***JavaScript Code -->*** https://leetcode.com/problems/check-balanced-string/submissions/1441645507\n- ***C++ Code -->*** https://leetcode.com/problems/check-balanced-string/submissions/1441635776\n- ***Python3 Code -->*** https://leetcode.com/problems/check-balanced-string/submissions/1441644046\n- ***Java Code -->*** https://leetcode.com/problems/check-balanced-string/submissions/1441638641\n- ***C Code -->*** https://leetcode.com/problems/check-balanced-string/submissions/1441648912\n- ***Python Code -->*** https://leetcode.com/problems/check-balanced-string/submissions/1441643239\n- ***C# Code -->*** https://leetcode.com/problems/check-balanced-string/submissions/1441647630\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(N)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(1)\n# Code\n![th.jpeg](https://assets.leetcode.com/users/images/8c51de6a-a173-4cdb-9795-4ab7d66846c0_1730630058.0593195.jpeg)\n\n
5
1
['Math', 'String', 'C', 'String Matching', 'Python', 'C++', 'Java', 'Python3', 'JavaScript', 'C#']
0
check-balanced-string
Easy and simple solution || Beats 100% || String || c++ || Python
easy-and-simple-solution-beats-100-strin-p3eh
C++\ncpp\nclass Solution {\npublic:\n bool isBalanced(string num) {\n int odd = 0;\n int even = 0;\n for (int i = 0; i < num.size(); i++
BijoySingh7
NORMAL
2024-11-03T04:28:39.454838+00:00
2024-11-03T04:28:39.454863+00:00
292
false
### C++\n```cpp\nclass Solution {\npublic:\n bool isBalanced(string num) {\n int odd = 0;\n int even = 0;\n for (int i = 0; i < num.size(); i++) {\n int digit = num[i] - \'0\';\n if (i % 2)\n odd += digit;\n else\n even += digit;\n }\n return even == odd;\n }\n};\n```\n### Python\n\n```python\nclass Solution:\n def isBalanced(self, num: str) -> bool:\n odd = 0\n even = 0\n for i in range(len(num)):\n digit = int(num[i])\n if i % 2 == 0:\n even += digit\n else:\n odd += digit\n return even == odd\n```\n# Beats 100%\n\n![image.png](https://assets.leetcode.com/users/images/e6a87c25-adb6-40d9-b2db-d69b9c0a0f5e_1730607990.9420562.png)\n\n\n### Explanation\n\n- **Intuition**: To check if the sum of digits at even positions equals the sum of digits at odd positions.\n\n- **Approach**:\n 1. Initialize `odd` and `even` as 0 to store sums of digits at odd and even indices, respectively.\n 2. Loop through each digit in the string:\n - Add the digit to `even` if its index is even, otherwise to `odd`.\n 3. Return `True` if `even` and `odd` sums are equal; otherwise, `False`.\n\n### Complexity\n\n- **Time Complexity**: \\(O(n)\\) since we traverse each digit in `num` once.\n- **Space Complexity**: \\(O(1)\\), as we use only two variables to hold the sums.
5
0
['String', 'Python', 'C++', 'Python3']
2
check-balanced-string
C++ 1-liner||0ms beats 100%
c-1-liner0ms-beats-100-by-anwendeng-1mot
Intuition\n Describe your first thoughts on how to solve this problem. \nUse alternating sum; if sum=0 return 1 otherwise 0\n# Approach\n Describe your approach
anwendeng
NORMAL
2024-11-03T04:19:12.244182+00:00
2024-11-03T04:31:02.773902+00:00
283
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUse alternating sum; if sum=0 return 1 otherwise 0\n# Approach\n<!-- Describe your approach to solving the problem. -->\nUse accumulate with lambda function\n```\n[&, i=1](int sum, char x) mutable{\n return sum+=(i*=(-1))*(x-\'0\');\n});\n```\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n# Code||C++ 1-line using accumulate\n```cpp []\nclass Solution {\npublic:\n static bool isBalanced(string& num) {\n return accumulate(num.begin(), num.end(), 0, [&, i=1](int sum, char x) mutable{\n return sum+=(i*=(-1))*(x-\'0\');\n })==0;\n }\n};\n```
5
0
['C++']
1
check-balanced-string
For beginners , Beats 100 % of other submissions' runtime.
for-beginners-beats-100-of-other-submiss-5vvd
Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem requires determining if the sum of digits at even indices in a string match
deep94725kumar
NORMAL
2024-11-03T04:05:33.100015+00:00
2024-11-03T04:05:33.100042+00:00
771
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem requires determining if the sum of digits at even indices in a string matches the sum of digits at odd indices. The first idea is to iterate through the string, keep track of the sum for both even and odd index positions, and compare them at the end.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n1) Initialization: You initialize two variables odd and even to 0, which will store the sum of digits at odd and even indices, respectively.\n\n2) Iteration: Loop through the string using an index i. For each character:\nIf i % 2 == 0, it\'s an even index, so you add the digit at that index to even.Otherwise, add the digit at that index to odd.\n\n3)Result: After the loop, return true if even == odd, meaning the sum of digits at even indices equals the sum of digits at odd indices. Otherwise, return false.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity is O(n), where n is the length of the string.\n\nThis is because we need to iterate through each character in the string once.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is O(1), as we are only using a few extra variables (odd, even, n) and not any additional data structures that grow with input size.\n\n# Code\n```cpp []\nclass Solution {\npublic:\n bool isBalanced(string num) {\n int n =num.length() ;\n int odd=0,even=0;\n for(int i=0;i<n;i++){\n if(i%2==0)\n even+=num[i]-\'0\';\n else\n odd+=num[i]-\'0\';\n }\n return even==odd;\n \n }\n};\n```
5
0
['C++']
1
check-balanced-string
Python solution
python-solution-by-divyap09-v6cm
Intuition\n Describe your first thoughts on how to solve this problem. \nWe need to calculate the sum of elements at even and odd indices separately and check w
divyap09
NORMAL
2024-11-27T09:01:48.637444+00:00
2024-11-27T09:01:48.637498+00:00
98
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe need to calculate the sum of elements at even and odd indices separately and check whether both sums are equal or not.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSince we have to traverse through each position, I used a single variable to store the result. At each odd index, I have added the element to the currSum and at each even index, I have subtracted the element from the currSum. At the end, if the currSum is 0, then we can say the sum of elements at even and odd indices are equal, else they are different.\n\nNote: We can use two separate variables to store the sum of even indices and odd indices separately, but using one variable makes our life simple when comparing it with zero.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n\n# Code\n```python3 []\nclass Solution:\n def isBalanced(self, num: str) -> bool:\n currSum = 0\n for i in range(len(num)):\n if i%2:\n currSum += int(num[i])\n else:\n currSum -= int(num[i])\n\n return currSum == 0\n```
4
0
['Python3']
1
check-balanced-string
Easy beats 100%
easy-beats-100-by-mainframekuznetsov-intc
Intuition\n Describe your first thoughts on how to solve this problem. \nBasic Implementation based problem\n# Approach\n Describe your approach to solving the
MainFrameKuznetSov
NORMAL
2024-11-03T04:36:14.114514+00:00
2024-11-03T08:00:46.119521+00:00
99
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBasic Implementation based problem\n# Approach\n<!-- Describe your approach to solving the problem. -->\nJust compute the sums in even and odd positions and check if they are equal or not\n# Complexity\n- Time complexity:- $O(n)$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:- $O(1)$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n bool isBalanced(string num) {\n int n=num.size(),e=0,o=0;\n for(int i=0;i<n;++i)\n {\n if(i&1)\n o+=(num[i]-\'0\');\n else\n e+=(num[i]-\'0\');\n }\n //cout<<o<<" "<<e<<"\\n";\n return o==e;\n }\n};\n```\n```java []\nclass Solution {\n public boolean isBalanced(String num) {\n int n=num.length();\n int e=0,o=0;\n for (int i=0;i<n;++i) \n {\n if((i&1)!=0)\n o+=num.charAt(i)-\'0\';\n else\n e+=num.charAt(i)-\'0\';\n }\n\n return o==e;\n }\n}\n```\n```python3 []\nclass Solution:\n def isBalanced(self, num: str) -> bool:\n e=0\n o=0 \n for i in range(len(num)):\n if (i&1)!=0:\n o+=int(num[i])\n else:\n e+=int(num[i])\n\n return o==e\n```
3
0
['String', 'C++', 'Java', 'Python3']
0
check-balanced-string
🌹 EASY SOLUTION [SINGLE VARIABLE]
easy-solution-single-variable-by-ramitga-w8ur
\n\n# \uD83D\uDC93**_PLEASE CONSIDER UPVOTING_**\uD83D\uDC93\n\n \n\n\n\n# \u2B50 Intuition\nThe task is to determine if the string of digits is balanced. A bal
ramitgangwar
NORMAL
2024-11-03T04:02:19.888587+00:00
2024-11-03T04:02:19.888633+00:00
55
false
<div align="center">\n\n# \uD83D\uDC93**_PLEASE CONSIDER UPVOTING_**\uD83D\uDC93\n\n</div>\n\n***\n\n# \u2B50 Intuition\nThe task is to determine if the string of digits is balanced. A balanced string is defined by the condition that the sum of the digits at even indices equals the sum of the digits at odd indices. The solution requires iterating through the string and using a single cumulative sum to track the balance.\n\n# \u2B50 Approach\n1. **Initialize a Cumulative Sum**:\n - Start with a variable that tracks the difference between the sums of digits at even and odd indices.\n2. **Iterate Through the String**:\n - For each character in the string, convert it to its integer value.\n - Depending on the index (even or odd), add the digit value to the cumulative sum for even indices and subtract it for odd indices.\n3. **Check Balance**:\n - After processing all characters, check if the cumulative sum is zero. If it is, the string is balanced; otherwise, it is not.\n\n# \u2B50 Complexity\n- **Time Complexity**: O(n), where n is the length of the string, as we iterate through the string once.\n- **Space Complexity**: O(1), as we use a fixed amount of space regardless of input size.\n\n# \u2B50 Code\n```java\nclass Solution {\n public boolean isBalanced(String num) {\n int sum = 0;\n\n for (int i = 0; i < num.length(); i++) {\n int sum1 = num.charAt(i) - \'0\';\n\n if (i % 2 == 0) {\n sum += sum1; // Add for even indices\n } else {\n sum -= sum1; // Subtract for odd indices\n }\n }\n\n return sum == 0; // Check if sums are balanced\n }\n}\n```
3
1
['String', 'Java']
0
check-balanced-string
Check if a Number is Balanced Based on Digit Sums
check-if-a-number-is-balanced-based-on-d-qss0
IntuitionThe problem requires checking whether the sum of digits at even indices is equal to the sum of digits at odd indices in a given string representation o
pramv
NORMAL
2025-02-15T14:10:52.949952+00:00
2025-02-15T14:10:52.949952+00:00
131
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> The problem requires checking whether the sum of digits at even indices is equal to the sum of digits at odd indices in a given string representation of a number. My first thought is to iterate through the string and maintain two separate sums—one for even indices and one for odd indices. If these sums are equal at the end, the number is balanced. # Approach <!-- Describe your approach to solving the problem. --> 1. Initialize two variables, `evenSum` and `oddSum`, to store the sums of digits at even and odd indices, respectively. 2. Iterate through the string representation of the number: - If the index is even, add the corresponding digit (converted from char to int) to evenSum. - If the index is odd, add it to oddSum. 3. After the loop, compare the two sums. If they are equal, return true; otherwise, return false. # Complexity - **Time complexity:** - The solution iterates through the string once, processing each digit in $$O(1)$$ time. - Hence, the overall complexity is $$O(n)$$, where n is the length of the string. - **Space complexity:** - The algorithm only uses a few integer variables (`evenSum`, `oddSum`, and loop iterators), which take $$O(1)$$ extra space. - Thus, the space complexity is $$O(1)$$. # Code ```cpp [] class Solution { public: bool isBalanced(string num) { // stoi(str) int len = num.size(); int oddSum = 0; int evenSum = 0; for (int i = 0; i < len; i++) { if (i % 2 == 0) { evenSum += stoi(string(1, num[i])); } else { oddSum += stoi(string(1, num[i])); } } if (evenSum == oddSum) { return true; } else { return false; } } }; ``` # Improvment 1. **Efficient Digit Conversion:** * Instead of `stoi(string(1, num[i]))`, which is inefficient, we use `num[i] - '0'` to convert a character to an integer in constant time.
2
0
['String', 'C++']
1
check-balanced-string
easy spicy ans
easy-spicy-ans-by-djett0nars-huy7
IntuitionApproachComplexity Time complexity: Space complexity: Code
djeTt0NarS
NORMAL
2025-02-01T09:08:11.978254+00:00
2025-02-01T09:08:11.978254+00:00
90
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] class Solution: def isBalanced(self, num: str) -> bool: n=(len(num)) s=0 s1=0 for i in range(0,n): if i % 2==0: s+=int(num[i]) elif i %2!=0: s1+=int(num[i]) return s==s1 ```
2
0
['Python3']
0
check-balanced-string
Beats 100% users in Time Complexity | Understandable python approach
beats-100-users-in-time-complexity-under-2icj
IntuitionApproachComplexity Time complexity:O(N) Space complexity:O(N) Code
atharvmittal9876
NORMAL
2024-12-28T13:42:38.521960+00:00
2024-12-28T13:42:38.521960+00:00
50
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity:O(N) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity:O(N) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] class Solution: def isBalanced(self, num: str) -> bool: l=[int(i) for i in num] sume=0 sumo=0 for i in range(len(num)): if i%2==0: sume+=l[i] else: sumo+=l[i] return sume==sumo ```
2
0
['String', 'Python', 'Python3']
0
check-balanced-string
simple and easy C++ solution
simple-and-easy-c-solution-by-shishirrsi-l3pq
if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n###### Let\'s Connect on Linkedin: www.linkedin.com/in/shishirrsiam\n\n\n\n# Code\ncpp []\nclass Solution {\
shishirRsiam
NORMAL
2024-11-07T07:32:55.824888+00:00
2024-11-07T07:32:55.824931+00:00
112
false
# if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n###### Let\'s Connect on Linkedin: www.linkedin.com/in/shishirrsiam\n\n\n\n# Code\n```cpp []\nclass Solution {\npublic:\n bool isBalanced(string num) \n {\n map<int, int>mp;\n bool flag = true;\n for(auto ch:num)\n {\n mp[flag] += ch - \'0\';\n flag = !flag;\n }\n return mp[0] == mp[1];\n }\n};\n```
2
0
['String', 'C++']
3
check-balanced-string
Golang simple solution
golang-simple-solution-by-evanfang-x84r
\n\n# Code\ngolang []\nfunc isBalanced(num string) bool {\n var sum rune\n for i, n := range(num) {\n if i % 2 == 0 {\n sum += (n - \'0\
evanfang
NORMAL
2024-11-06T11:38:52.929449+00:00
2024-11-06T11:38:52.929492+00:00
32
false
\n\n# Code\n```golang []\nfunc isBalanced(num string) bool {\n var sum rune\n for i, n := range(num) {\n if i % 2 == 0 {\n sum += (n - \'0\')\n } else {\n sum -= (n - \'0\')\n }\n }\n return sum == 0\n}\n```
2
0
['Go']
0
check-balanced-string
Python3
python3-by-dereksd2019-0ujp
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nCalculated the length o
dereksd2019
NORMAL
2024-11-04T11:10:34.893061+00:00
2024-11-04T11:10:34.893097+00:00
98
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nCalculated the length of a string. For example, 1234 has length of 4. Got the string of even indices and odd indices. Calculated the digit sum of the string of even indices and odd indices. Compared them.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nclass Solution:\n def isBalanced(self, num: str) -> bool:\n digitsum = lambda n: sum(int(digit) for digit in str(n))\n numstrlength = len(num)\n even = num[0:numstrlength:2]\n odd = num[1:numstrlength:2]\n return digitsum(even) == digitsum(odd)\n \n```
2
0
['Python3']
1
check-balanced-string
Linear solution with constant space
linear-solution-with-constant-space-by-g-x259
Approach\nThe solution is very straightforward, we calculate the sum of digits in even indices and the sum of digits in odd indices. We can optimize things a li
gomezdavid89
NORMAL
2024-11-03T17:01:38.536446+00:00
2024-11-22T22:36:06.034039+00:00
14
false
# Approach\nThe solution is very straightforward, we calculate the sum of digits in even indices and the sum of digits in odd indices. We can optimize things a little bit by computing a single sum like: $$num[0] - num[1] + num[2] - num[3] + ...$$, where the final sum should be equal to $$0$$.\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```rust []\nimpl Solution {\n pub fn is_balanced(num: String) -> bool {\n num.as_bytes().iter().fold((0, 1), |(sum, b), &e| (sum + (e - b\'0\') as i32 * b, b * -1)).0 == 0\n }\n}\n```\n\n```c++ []\nclass Solution {\npublic:\n bool isBalanced(string_view num) {\n int sum = 0;\n for (int i = 0; i < num.size(); i++) {\n sum += (i % 2 == 0) ? num[i] - \'0\' : -num[i] + \'0\';\n }\n return sum == 0;\n }\n};\n```
2
0
['Rust']
1
check-balanced-string
💯Very Easy Detailed Solution || 🎯Beats 100% of the users || 🎯 Brute Force
very-easy-detailed-solution-beats-100-of-xrqn
Intuition\n Describe your first thoughts on how to solve this problem. \nWe will take two variable to maitain the count of digits at even and odd indices, and t
chaturvedialok44
NORMAL
2024-11-03T08:39:51.331707+00:00
2024-11-03T08:39:51.331728+00:00
254
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe will take two variable to maitain the count of digits at even and odd indices, and then will check if both equals or not.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Initialize two variables \'evenSum\' and \'oddSum\' to \'zero\'. These will store the sums of digits at even and odd indices, respectively.\n2. Loop through each character in the string \'num\':\n - Convert each character to its integer value using \'Character.getNumericValue(num.charAt(i))\'.\n - If the index \'i is even\', add the digit to \'evenSum\'; if \'i is odd\', add it to \'oddSum\'.\n3. After the loop, compare \'evenSum\' and \'oddSum\'.\n - If they are equal, return \'true\', indicating that the string is balanced.\n - Otherwise, return \'false\'.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n# Code\n```java []\nclass Solution {\n public boolean isBalanced(String num) {\n int evenSum = 0, oddSum = 0;\n for(int i=0; i<num.length(); i++){\n int ch = Character.getNumericValue(num.charAt(i));\n if(i%2 == 0){\n evenSum += ch;\n }\n else{\n oddSum += ch;\n }\n }\n if(evenSum == oddSum){\n return true;\n }\n else{\n return false;\n }\n }\n}\n```
2
0
['Math', 'Two Pointers', 'String', 'String Matching', 'Java']
2
check-balanced-string
Java Clean Solution
java-clean-solution-by-shree_govind_jee-21eb
Code\njava []\nclass Solution {\n public boolean isBalanced(String num) {\n long odd = 0, even = 0;\n for (int i = 0; i < num.length(); i++) {\
Shree_Govind_Jee
NORMAL
2024-11-03T04:05:07.712833+00:00
2024-11-03T04:05:07.712875+00:00
104
false
# Code\n```java []\nclass Solution {\n public boolean isBalanced(String num) {\n long odd = 0, even = 0;\n for (int i = 0; i < num.length(); i++) {\n if (i % 2 == 0) {\n even += num.charAt(i) - \'0\';\n } else {\n odd += num.charAt(i) - \'0\';\n }\n }\n return odd == even;\n }\n}\n```
2
0
['Math', 'String', 'String Matching', 'Java']
0
check-balanced-string
✅ Simple Java Solution
simple-java-solution-by-harsh__005-z5f9
CODE\nJava []\npublic boolean isBalanced(String num) {\n int s1=0, s2 = 0, n = num.length();\n for(int i=0; i<n; i++) {\n char ch = num.charAt(i);\
Harsh__005
NORMAL
2024-11-03T04:04:12.648160+00:00
2024-11-03T04:04:12.648186+00:00
199
false
## **CODE**\n```Java []\npublic boolean isBalanced(String num) {\n int s1=0, s2 = 0, n = num.length();\n for(int i=0; i<n; i++) {\n char ch = num.charAt(i);\n if(i%2 == 0) {\n s2 += (ch-\'0\');\n } else {\n s1 += (ch-\'0\');\n }\n }\n return s1==s2;\n}\n```
2
0
['Java']
1
check-balanced-string
Stop checking solution for wayyyyy to easy problem kid
stop-checking-solution-for-wayyyyy-to-ea-gljj
IntuitionYes i know what you thinking cmon dude just implement it already stop checking solutions for wayyyy to easy problem you ain't gonna learn anythingBoldA
_Aryan_Gupta
NORMAL
2025-04-09T07:11:39.107689+00:00
2025-04-09T07:11:39.107689+00:00
10
false
# Intuition # Yes i know what you thinking cmon dude just implement it already stop checking solutions for wayyyy to easy problem you ain't gonna learn anything**Bold** # Approach Just do what question says you got it # Complexity - Time complexity: O(N) - Space complexity: O(1) # Code ```cpp [] class Solution { public: bool isBalanced(string num) { int counteven=0; int countodd=0; for(int i=0;i<num.length();i++) { if(i%2==0) { counteven=counteven + (num[i] - '0'); } else { countodd=countodd + (num[i] - '0'); } } return counteven==countodd; } }; ```
1
0
['C++']
0
check-balanced-string
Easy Solution Python3
easy-solution-python3-by-adhi_m_s-ytk6
IntuitionApproachComplexity Time complexity: Space complexity: Code
Adhi_M_S
NORMAL
2025-03-20T10:22:00.622506+00:00
2025-03-20T10:22:00.622506+00:00
51
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] class Solution: def isBalanced(self, num: str) -> bool: return sum([int(num[i]) for i in range(len(num)) if i%2!=0])==sum([int(num[i]) for i in range(len(num)) if i%2==0]) ```
1
0
['Python3']
0
check-balanced-string
getNumericValue way
getnumericvalue-way-by-sairangineeni-jiyq
IntuitionConvert string to int by using Character.getNumericValue(num.charAt(i));after that if index is even then add to even or otherwise to oddcheck if they m
Sairangineeni
NORMAL
2025-03-10T06:55:39.834026+00:00
2025-03-10T06:55:39.834026+00:00
46
false
# Intuition Convert string to int by using Character.getNumericValue(num.charAt(i)); after that if index is even then add to even or otherwise to odd check if they match, if not return false. # Code ```java [] class Solution { public static boolean isBalanced(String num) { int even = 0; int odd = 0; for (int i = 0; i < num.length(); i++) { int c = Character.getNumericValue(num.charAt(i)); if(i % 2 == 0) { even += c; }else { odd += c; } } return even == odd; } } ```
1
0
['Java']
0
check-balanced-string
best solution
best-solution-by-haneen_ep-te3m
IntuitionThis solution determines if a number represented as a string is "balanced" by comparing the sum of digits at even positions with the sum of digits at o
haneen_ep
NORMAL
2025-03-06T17:38:18.703642+00:00
2025-03-06T17:38:18.703642+00:00
68
false
# Intuition This solution determines if a number represented as a string is "balanced" by comparing the sum of digits at even positions with the sum of digits at odd positions. A number is considered balanced if both sums are equal. # Approach - Initialize two counters: even for the sum of digits at even positions and odd for the sum of digits at odd positions - Iterate through each digit in the string representation of the number - Add the current digit to either the even or odd sum based on its position - If the position is even (0, 2, 4, ...), add to the even sum - If the position is odd (1, 3, 5, ...), add to the odd sum - After processing all digits, compare the two sums - Return true if the sums are equal, false otherwise # Complexity - Time complexity: O(n) - We iterate once through the string of length n - Each operation inside the loop (conversion, addition) is O(1) - Space complexity: O(1) - We only use two variables (even and odd) regardless of input size - No additional data structures are used that scale with input size # Code ```javascript [] /** * @param {string} num * @return {boolean} */ var isBalanced = function (num) { let even = 0; let odd = 0; for (let i = 0; i < num.length; i++) { i % 2 === 0 ? even += Number(num[i]) : odd += Number(num[i]) } return even === odd; }; ```
1
0
['JavaScript']
0
check-balanced-string
Simple Python Solution --- UNDERSTANDABLE --- BEGINNER FRIENDLY
simple-python-solution-understandable-be-fqpe
IntuitionApproachComplexity Time complexity: Space complexity: Code
22A31A05A9
NORMAL
2025-02-16T19:49:51.686756+00:00
2025-02-16T19:49:51.686756+00:00
21
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python [] class Solution(object): def isBalanced(self, num): """ :type num: str :rtype: bool """ even=odd=0 for i in range(len(num)): if i%2==0: even=even+int(num[i]) else: odd=odd+int(num[i]) return even==odd ```
1
0
['Python']
0
check-balanced-string
Easiest Solution in Java
easiest-solution-in-java-by-sathurnithy-1lpu
Code
Sathurnithy
NORMAL
2025-02-04T13:32:04.318650+00:00
2025-02-04T13:32:04.318650+00:00
100
false
# Code ```java [] class Solution { public boolean isBalanced(String num) { int oddSum = 0, evenSum = 0, len = num.length(); for (int i = 0; i < len; i++) { if (i % 2 == 0) evenSum += (num.charAt(i) - '0'); else oddSum += (num.charAt(i) - '0'); } return oddSum == evenSum; } } ```
1
0
['String', 'Java']
0
check-balanced-string
Easiest Solution in C
easiest-solution-in-c-by-sathurnithy-5zx4
Code
Sathurnithy
NORMAL
2025-02-04T13:29:51.587698+00:00
2025-02-04T13:29:51.587698+00:00
40
false
# Code ```c [] bool isBalanced(char* num) { int oddSum = 0, evenSum = 0, len = strlen(num); for (int i = 0; i < len; i++) { if (i % 2 == 0) evenSum += (num[i] - '0'); else oddSum += (num[i] - '0'); } return oddSum == evenSum; } ```
1
0
['String', 'C']
0
check-balanced-string
Solution in Java and C
solution-in-java-and-c-by-vickyy234-d4ur
Code
vickyy234
NORMAL
2025-02-03T17:45:18.068481+00:00
2025-02-03T17:45:18.068481+00:00
47
false
# Code ```c [] bool isBalanced(char* num) { int odd = 0, even = 0, len = strlen(num); int i = 0; while (i < len) { odd += (num[i] - 48); i += 2; } i = 1; while (i < len) { even += (num[i] - 48); i += 2; } return odd == even; } ``` ```Java [] class Solution { public boolean isBalanced(String num) { int odd = 0, even = 0, len = num.length(); int i = 0; while (i < len) { odd += (num.charAt(i) - 48); i += 2; } i = 1; while (i < len) { even += (num.charAt(i) - 48); i += 2; } return odd == even; } } ```
1
0
['String', 'C', 'Java']
0
check-balanced-string
Easy answer in 1 loop
easy-answer-in-1-loop-by-saksham_gupta-tbsx
Complexity Time complexity: O(n) Space complexity: O(1) Code
Saksham_Gupta_
NORMAL
2025-01-14T18:36:13.342326+00:00
2025-01-14T18:36:13.342326+00:00
106
false
<!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: ***O(n)*** <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: ***O(1)*** <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public boolean isBalanced(String num) { int leftSum = 0; int rightSum = 0; for(int i=0; i<num.length(); i++){ if(i%2 == 0){ leftSum += num.charAt(i) - '0'; } else{ rightSum += num.charAt(i) - '0'; } } return leftSum == rightSum; } } ```
1
0
['Java']
0
check-balanced-string
Easy solution: Using one variable for sum instead of two.
easy-solution-using-one-variable-for-sum-hv95
IntuitionMy initial thought was to create two variables, even_sum and odd_sum, and then loop through the digits to calculate their respective sums.However, I re
ekbullock
NORMAL
2025-01-13T00:40:58.409314+00:00
2025-01-13T00:40:58.409314+00:00
20
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> My initial thought was to create two variables, even_sum and odd_sum, and then loop through the digits to calculate their respective sums. However, I realized there is a simpler way to solve this. Instead of maintaining two separate variables, I could use a single variable, curr_sum. For even indices, I would add the digit to curr_sum, and for odd indices, I would subtract the digit. If the final result of curr_sum is 0, the number is balanced; otherwise, it is not. # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: O(N) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(1) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] class Solution: def isBalanced(self, num: str) -> bool: curr_sum = 0 for val in range(len(num)): if val % 2 == 0: curr_sum += int(num[val]) else: curr_sum -= int(num[val]) return curr_sum == 0 ```
1
0
['Python3']
0
check-balanced-string
BEATING 99% IN 1ms EASY JAVA CODE
beating-99-in-1ms-easy-java-code-by-arsh-epqc
ApproachTo solve this problem efficiently, we can break it down into the following steps: Initialization: We need to keep track of the sums of digits at even an
arshi_bansal
NORMAL
2025-01-11T12:37:25.638738+00:00
2025-01-11T12:37:25.638738+00:00
61
false
# Approach <!-- Describe your approach to solving the problem. --> To solve this problem efficiently, we can break it down into the following steps: 1. Initialization: We need to keep track of the sums of digits at even and odd indices. We can initialize two variables: s1 (for odd indices) and s2 (for even indices). We also need to know the length of the string num in order to loop over its characters. 2. Iterate Over the String: For each character in the string, we need to check its index: If the index is even (i.e., i % 2 == 0), add the value of the character (converted to an integer) to s2. If the index is odd (i.e., i % 2 == 1), add the value of the character (converted to an integer) to s1. 3. Final Comparison: After the loop, compare the sums: If the sum of digits at even indices (s2) is equal to the sum of digits at odd indices (s1), return true (indicating that the string is balanced). Otherwise, return false. # Complexity - Time complexity: O(n) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(1) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public boolean isBalanced(String num) { int s1=0,s2=0,n=num.length(); for(int i=0;i<n;i++){ if(i%2==0){ s2+=num.charAt(i) - '0'; }else{ s1+=num.charAt(i) - '0'; } } if(s1==s2){ return true; } return false; } } ```
1
0
['Java']
0
check-balanced-string
☑️ Checking if given string is Balanced. ☑️
checking-if-given-string-is-balanced-by-85sxr
Code
Abdusalom_16
NORMAL
2024-12-17T17:06:49.016123+00:00
2024-12-17T17:06:49.016123+00:00
45
false
# Code\n```dart []\nclass Solution {\n bool isBalanced(String num) {\n int even = 0;\n int odd = 0;\n for(int i = 0;i < num.length; i++){\n if(i.isEven){\n even+= int.parse(num[i]);\n }else{\n odd+= int.parse(num[i]);\n }\n }\n\n return even == odd;\n }\n}\n```
1
0
['String', 'Dart']
0
check-balanced-string
easy C solution | Runtime Beats 100.00%
easy-c-solution-runtime-beats-10000-by-j-p6x6
IntuitionConsider the even digits as positive numbers and the odd digits and negative numbers. After adding all the digits this way, the result should be zero i
JoshDave
NORMAL
2024-12-16T04:24:04.858122+00:00
2024-12-16T04:24:04.858122+00:00
58
false
# Intuition\nConsider the even digits as positive numbers and the odd digits and negative numbers. After adding all the digits this way, the result should be zero if the string is balanced. So add all the numbers from the string and rather than deciding whether to add or subtract, simply take the opposite of the number at each step.\n\nCase "1234":\n1 - 2 + 3 - 4 = -2\nnot equal to zero so not balanced\nequivalent to:\n(((((((1 * -1) + 2) * -1) + 3) * -1) + 4) * -1) = -2\n\n# Complexity\n- Time complexity: O(n)\n- Space complexity: O(1)\n\n# Code\n```c []\nbool isBalanced(char* num) {\n int total = 0;\n while (*num) {\n total += \'0\' - *num;\n total = -total;\n ++num;\n }\n return total == 0;\n}\n```
1
0
['Math', 'String', 'C']
0
check-balanced-string
1 ms, Beats 99%
1-ms-beats-99-by-sorokus-dev-45d1
Intuition\nCount the sums of even and odd digints in the string.\n\n# Approach\nIterate over the string.\nExtract a character and convert it into integer value
sorokus-dev
NORMAL
2024-11-28T07:01:57.724936+00:00
2024-11-28T07:01:57.724959+00:00
18
false
# Intuition\nCount the sums of even and odd digints in the string.\n\n# Approach\nIterate over the string.\nExtract a character and convert it into integer value simply subtracting \'0\' character from it. Increment odd/even counter respectively.\nDon\'t forget to check if an iteration variable \'i\' is in scope.\n\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(1)\n\n# Code\n```java []\nclass Solution {\n public boolean isBalanced(String num) {\n int odd = 0, even = 0;\n for (int i = 0; i < num.length(); i++) {\n odd += (num.charAt(i++) - \'0\');\n if (i < num.length()) {\n even += (num.charAt(i) - \'0\');\n }\n }\n return odd == even;\n }\n}\n```
1
0
['Java']
0
check-balanced-string
Easy js solution
easy-js-solution-by-joelll-nuuu
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
Joelll
NORMAL
2024-11-27T09:40:40.415183+00:00
2024-11-27T09:40:40.415223+00:00
58
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```javascript []\n/**\n * @param {string} num\n * @return {boolean}\n */\nvar isBalanced = function (num) {\n let even = 0\n let odd = 0\n for (let i = 0; i < num.length; i++) {\n if (i % 2 == 0) {\n even += parseInt(num[i])\n }\n }\n for (let i = 0; i < num.length; i++) {\n if (i % 2 !== 0) {\n odd += parseInt(num[i])\n }\n }\n\n return odd === even\n};\n```
1
0
['JavaScript']
0
check-balanced-string
Easy 📶 solution with each step by step procedure with 🗿 O(n)
easy-solution-with-each-step-by-step-pro-zlom
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
shamnad_skr
NORMAL
2024-11-26T04:20:32.235948+00:00
2024-11-26T04:21:03.496449+00:00
44
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```typescript []\nfunction isBalanced(num: string): boolean {\n\n //converting string to Array\n const numArray : number[] = num.split("").map( no => Number(no) )\n const size : number = numArray.length;\n let evenSum : number = 0;\n let oddSum : number = 0;\n \n for(let i=0; i<size; i++){\n \n if( i%2 === 1 ){\n oddSum += numArray[i];\n }else{\n evenSum += numArray[i];\n }\n }\n\n return oddSum === evenSum;\n \n};\n```
1
0
['TypeScript', 'JavaScript']
0
check-balanced-string
C++ sum
c-sum-by-michelusa-q99p
Sum should be zero\n\ncpp []\nclass Solution {\npublic:\n bool isBalanced(string_view num) {\n int sum = 0;\n int sign = 1;\n for (size_
michelusa
NORMAL
2024-11-25T13:37:57.115785+00:00
2024-11-25T13:37:57.115823+00:00
5
false
Sum should be zero\n\n```cpp []\nclass Solution {\npublic:\n bool isBalanced(string_view num) {\n int sum = 0;\n int sign = 1;\n for (size_t idx = 0; idx != num.size(); ++idx, sign *= -1) {\n sum += sign * (num[idx] - \'0\');\n }\n\n return !sum;\n }\n};\n```
1
0
['C++']
0
check-balanced-string
O(N) easy solution in python
on-easy-solution-in-python-by-nikasvante-ckd0
Time complexity: O(N)\n\n- Space complexity: O(N)\n\n# Code\npython3 []\nclass Solution:\n def isBalanced(self, num: str) -> bool:\n odd,even = 0,0\n
nikasvantes
NORMAL
2024-11-21T16:23:59.950533+00:00
2024-11-21T16:23:59.950560+00:00
30
false
- Time complexity: O(N)\n\n- Space complexity: O(N)\n\n# Code\n```python3 []\nclass Solution:\n def isBalanced(self, num: str) -> bool:\n odd,even = 0,0\n for odd_num in range(1,len(num),2):\n odd += int(num[odd_num])\n for even_num in range(0,len(num),2):\n even += int(num[even_num])\n return even==odd\n```
1
0
['Python3']
0
check-balanced-string
Easy solution
easy-solution-by-chandranshu31-rkjj
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
Chandranshu31
NORMAL
2024-11-18T14:51:44.755299+00:00
2024-11-18T14:51:44.755370+00:00
17
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public boolean isBalanced(String num) {\n \n int n=num.length();\n\n int even=0;\n int evenSum=0;\n int odd=1;\n int oddSum=0;\n\n while(even<n){\n evenSum+=num.charAt(even)-\'0\'; // charAt will return digit as char so to convert it to integer. ASCII of 0 is 48\n // so, supoose we got 9 then char9 then char9-char0= 57-48 by ASCII. =9 int\n even+=2;\n }\n\n while(odd<n){\n oddSum+=num.charAt(odd)-\'0\';\n odd+=2;\n }\n\n return evenSum==oddSum;\n\n\n }\n}\n```
1
0
['Java']
0
check-balanced-string
BEATS 99.5% || MOST OPTIMIZED SOLUTION IN JAVA
beats-995-most-optimized-solution-in-jav-i9bq
\n# Code\njava []\nclass Solution \n{\n public boolean isBalanced(String num) \n {\n int n = num.length();\n int even = 0;\n int odd
dawncindrela
NORMAL
2024-11-13T15:07:38.763548+00:00
2024-11-13T15:07:38.763586+00:00
40
false
\n# Code\n```java []\nclass Solution \n{\n public boolean isBalanced(String num) \n {\n int n = num.length();\n int even = 0;\n int odd = 0;\n for(int i=0;i<n;i++)\n {\n if(i % 2 == 0)\n {\n even += (num.charAt(i)-\'0\');\n }\n else\n {\n odd += (num.charAt(i)-\'0\');\n }\n }\n return (odd==even);\n }\n}\n```
1
0
['String', 'Java']
0
check-balanced-string
For beginners C++, Beats 100 %
for-beginners-c-beats-100-by-shashankkk1-xfxp
Intuition\n Describe your first thoughts on how to solve this problem. \nThe goal is to determine if a string of digits is "balanced" based on the sums of its d
shashankkk1212
NORMAL
2024-11-10T10:58:03.821492+00:00
2024-11-10T10:58:03.821522+00:00
9
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe goal is to determine if a string of digits is "balanced" based on the sums of its digits at even and odd indices. To solve this, we can:\n\n- Separate the digits based on whether they\u2019re located at even or odd - indices.\n- Sum up the digits at these even and odd positions.\n- Check if the sums are equal. If they are, the number is balanced; otherwise, it\u2019s not.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Initialize Sums for Even and Odd Positions: Create two integer variables, even and odd, initialized to zero. These will hold the sum of digits at even and odd indices, respectively.\nTraverse the String:\n- Use a loop to iterate over each character in the string:\n- For characters at even indices (0, 2, 4,...), convert the character to an integer and add it to the even sum.\n- For characters at odd indices (1, 3, 5,...), convert the character to an integer and add it to the odd sum.\n- Compare Sums: After completing the loop, compare the even and odd sums.\n- If they are equal, return true (indicating the number is balanced).\nOtherwise, return false.\n\n# Complexity\n- The time complexity is O(n), where n is the length of the string.\n\n This is because we need to iterate through each character in the string once.\n\n# Code\n```cpp []\nclass Solution {\npublic:\n bool isBalanced(string num) {\n\n int even=0;\n int odd=0;\n for(int i=0;i<num.length();i+=2){\n int a = num[i] - \'0\';\n even = even+a;\n }\n\n for(int i=1;i<num.size();i+=2){\n int a=num[i]-\'0\';\n odd +=a;\n }\n if(odd==even){\n return 1;\n }\n return 0;\n \n }\n};\n```
1
0
['C++']
0
check-balanced-string
After a long gap of 17 days posting a soln bahut lamba break hua resume krna hope so ho jay :D
after-a-long-gap-of-17-days-posting-a-so-siu4
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
yesyesem
NORMAL
2024-11-08T18:43:52.178887+00:00
2024-11-08T18:43:52.178928+00:00
17
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n bool isBalanced(string num) {\n \n int eSum=0;\n int oSum=0;\n\n int n=num.length();\n\n vector<int>arr(n,0);\n\n for(int i=0;i<n;i++)\n {\n arr[i]=num[i]-\'0\';\n }\n\n for(int i=0;i<n;i++)\n {\n if(i%2==0)\n {\n oSum+=arr[i];\n }\n else\n {\n eSum+=arr[i];\n }\n }\n\n return eSum==oSum;\n\n }\n};\n```
1
0
['C++']
0
check-balanced-string
[C++] Short and clean solution
c-short-and-clean-solution-by-bora_maria-tp5k
Use a vector/array of size 2. v[0] will be sum of even position digits, v[1] will be sum of odd position digits.The result will be v[0] == v[1]\n# Code\ncpp []\
bora_marian
NORMAL
2024-11-08T07:45:51.100384+00:00
2024-11-08T07:45:51.100417+00:00
19
false
Use a vector/array of size 2. ```v[0]``` will be sum of even position digits, ```v[1]``` will be sum of odd position digits.The result will be ```v[0] == v[1]```\n# Code\n```cpp []\nclass Solution {\npublic:\n bool isBalanced(string num) {\n vector<int>v(2, 0);\n for (int i = 0; i < num.size(); i++) {\n v[i % 2] += (num[i] - \'0\');\n }\n return v[0] == v[1];\n }\n};\n```
1
0
['C++']
0
check-balanced-string
Assembly with explanation and comparison with C
assembly-with-explanation-and-comparison-4734
\n# Rationale\n\nI\'ve solved this LeetCode problem using inline assembly in C. My goal isn\'t to showcase complexity, but rather to challenge myself and deepen
pcardenasb
NORMAL
2024-11-07T09:22:58.492427+00:00
2024-11-07T09:40:00.960250+00:00
33
false
\n# Rationale\n\nI\'ve solved this LeetCode problem using inline assembly in C. My goal isn\'t to showcase complexity, but rather to challenge myself and deepen my understanding of assembly language. \n\nAs a beginner in assembly, I welcome any improvements or comments on my code.\n\nAdditionally, I aim to share insights on practicing assembly on LeetCode.\n\n# Intuition\n\nAdd the even numbers and substract the odd\n\n# Approach\n\nLoop through all digits of `num` incrementing the `RDI` register. Initialize AX to zero. In the loop, update the value of `AX` adding the even numbers and substracting the odds. Then return. View [code](#assembly-code) comments for explanation.\n\n# Complexity\n- Time complexity: $$O(\\text{num.length})$$, because It will execute the code in `loop` as many times as number of digits in `num`. Moreover, $$\\text{num.length} \\le 100$$.\n- Space complexity: $$O(1)$$, No memory variable is needed, only registers.\n\n# Assembly Code\nThis mixed block shows the C code with inline assembly and the assembly code. View [Notes about assembly](#notes-about-assembly) for notes about the syntax used. Moreover, It shows the assembly code without comment for [comparison with C](#comparison-with-c). If you want to test this code you can [run locally](#run-locally).\n\n```c [C (inline asm)]\nbool isBalanced(char* num) {\n\tbool ret;\n\t__asm__(\n".intel_syntax noprefix\\n"\n"\t## dl: will be the digit as character\\n"\n"\t## ax: the sum of digits\\n"\n"\t## rdi: pointer to current digit\\n"\n"\txor\tdx, dx\\n"\n"\txor\trax, rax\\n"\n"loop:\\n"\n"\t## get the current digit as character in dl\\n"\n"\tmov\tdl, BYTE PTR [rdi]\\n"\n"\t\\n"\n"\t## end loop if character is null\\n"\n"\ttest\tdl, dl\\n"\n"\tje\tendloop\\n"\n"\\n"\n"\t## get the number rather than character\\n"\n"\tsub\tdl, \'0\'\\n"\n"\t\\n"\n"\t## check if even or odd\\n"\n"\ttest\tdil, 1\\n"\n"\tjne\todd\\n"\n"\t\\n"\n"\t## add character to ax\\n"\n"\tadd\tax, dx\\n"\n"\tjmp\tupdate\\n"\n"odd:\\n"\n"\t## substract character from ax\\n"\n"\tsub\tax, dx\\n"\n"\\n"\n"update:\\n"\n"\tinc\trdi\\n"\n"\tjmp\tloop\\n"\n"endloop:\\n"\n"\t## logical not of ax\\n"\n"\ttest\tax, ax\\n"\n"\tsetz\tal\\n"\n"\tjmp\tepilog\\n"\n"epilog:\\n"\n".att_syntax\\n"\n\t\t: "=a"(ret)\n\t);\n\treturn ret;\n}\n```\n```assembly [ASM (with comments)]\n .intel_syntax noprefix\n .globl isBalanced\nisBalanced:\n\t## dl: will be the digit as character\n\t## ax: the sum of digits\n\t## rdi: pointer to current digit\n\txor\tdx, dx\n\txor\trax, rax\nloop:\n\t## get the current digit as character in dl\n\tmov\tdl, BYTE PTR [rdi]\n\t\n\t## end loop if character is null\n\ttest\tdl, dl\n\tje\tendloop\n\n\t## get the number rather than character\n\tsub\tdl, \'0\'\n\t\n\t## check if even or odd\n\ttest\tdil, 1\n\tjne\todd\n\t\n\t## add character to ax\n\tadd\tax, dx\n\tjmp\tupdate\nodd:\n\t## substract character from ax\n\tsub\tax, dx\n\nupdate:\n\tinc\trdi\n\tjmp\tloop\nendloop:\n\t## logical not of ax\n\ttest\tax, ax\n\tsetz\tal\n\tjmp\tepilog\nepilog:\n\tret\n```\n```assembly [ASM (without comments)]\n .intel_syntax noprefix\n .globl isBalanced\nisBalanced:\n\n\n\n\txor\tdx, dx\n\txor\trax, rax\nloop:\n\n\tmov\tdl, BYTE PTR [rdi]\n\t\n\n\ttest\tdl, dl\n\tje\tendloop\n\n\n\tsub\tdl, \'0\'\n\t\n\n\ttest\tdil, 1\n\tjne\todd\n\t\n\n\tadd\tax, dx\n\tjmp\tupdate\nodd:\n\n\tsub\tax, dx\n\nupdate:\n\tinc\trdi\n\tjmp\tloop\nendloop:\n\n\ttest\tax, ax\n\tsetz\tal\n\tjmp\tepilog\nepilog:\n\tret\n```\n```assembly [ASM (without comments)]\n .intel_syntax noprefix\n .globl isBalanced\nisBalanced:\n\txor\tdx, dx\n\txor\trax, rax\nloop:\n\tmov\tdl, BYTE PTR [rdi]\n\ttest\tdl, dl\n\tje\tendloop\n\tsub\tdl, \'0\'\n\ttest\tdil, 1\n\tjne\todd\n\tadd\tax, dx\n\tjmp\tupdate\nodd:\n\tsub\tax, dx\nupdate:\n\tinc\trdi\n\tjmp\tloop\nendloop:\n\ttest\tax, ax\n\tsetz\tal\n\tjmp\tepilog\nepilog:\n\tret\n```\n\n# Notes about assembly\n\n- This code is written Intel syntax using the `.intel_syntax noprefix` directive.\n- This code uses `#` for comments because GAS (GNU Assembler) uses this syntax and Leetcode uses GCC for compiling.\n- The reason I return from the "function" by jumping to the `.epilog` is that it\'s easier to remove everything after the `.epilog` to obtain the C code with inline assembly. I am aware that in assembly I can have multiple ret instructions in my "function", but in inline assembly I need to replace those `ret` instructions with a jump to the end of the inline assembly block.\n\n# Comparison with C\n\nThis my solution using C and the assembly code generated by `gcc -S`. I removed unnecesary lines with the following shell command. I also generated the code with optimization level `-O0`, `-O1`, `-O2`, `-Os`, `-Oz` and remove stack protector for comparison. \n\n```bash\n$ gcc -O2 -fno-stack-protector -fno-asynchronous-unwind-tables -masm=intel -S code.c -o- | \n sed \'/^\\(.LCOLD\\|.LHOT\\|\\s*\\(\\.file\\|\\.type\\|\\.text\\|\\.p2align\\|\\.size\\|\\.ident\\|\\.section\\)\\)/d\'\n```\n\nNote that the C code may use these techniques in order to get optimized code.\n\n- Use `restrict`s, `const`s.\n- Type castings to smaller types.\n- Use do-while instead of while or for.\n\nMoreover, after the generated assembly code, I have also included my solution using assembly without comments for comparison.\n\n```C [-C code]\n#include <stdbool.h>\n\nbool isBalanced(char* num) {\n\tshort sum = 0;\n\twhile (*num) {\n\t\tif ((long) num % 2 == 0) {\n\t\t\tsum += *num - \'0\';\n\t\t} else {\n\t\t\tsum -= *num - \'0\';\n\t\t}\n\t\tnum++;\n\t}\n\t\n\treturn !sum;\n}\n```\n```assembly [-gcc -O0]\n\t.intel_syntax noprefix\n\t.globl\tisBalanced\nisBalanced:\n\tpush\trbp\n\tmov\trbp, rsp\n\tmov\tQWORD PTR -24[rbp], rdi\n\tmov\tWORD PTR -2[rbp], 0\n\tjmp\t.L2\n.L5:\n\tmov\trax, QWORD PTR -24[rbp]\n\tand\teax, 1\n\ttest\trax, rax\n\tjne\t.L3\n\tmov\trax, QWORD PTR -24[rbp]\n\tmovzx\teax, BYTE PTR [rax]\n\tmovsx\tdx, al\n\tmovzx\teax, WORD PTR -2[rbp]\n\tadd\teax, edx\n\tsub\teax, 48\n\tmov\tWORD PTR -2[rbp], ax\n\tjmp\t.L4\n.L3:\n\tmovzx\tedx, WORD PTR -2[rbp]\n\tmov\trax, QWORD PTR -24[rbp]\n\tmovzx\teax, BYTE PTR [rax]\n\tmovsx\tcx, al\n\tmov\teax, edx\n\tsub\teax, ecx\n\tadd\teax, 48\n\tmov\tWORD PTR -2[rbp], ax\n.L4:\n\tadd\tQWORD PTR -24[rbp], 1\n.L2:\n\tmov\trax, QWORD PTR -24[rbp]\n\tmovzx\teax, BYTE PTR [rax]\n\ttest\tal, al\n\tjne\t.L5\n\tcmp\tWORD PTR -2[rbp], 0\n\tsete\tal\n\tpop\trbp\n\tret\n```\n```assembly [-gcc -O1]\n\t.intel_syntax noprefix\n\t.globl\tisBalanced\nisBalanced:\n\tmovzx\teax, BYTE PTR [rdi]\n\ttest\tal, al\n\tje\t.L6\n\tmov\tedx, 0\n\tjmp\t.L5\n.L3:\n\tadd\tedx, 48\n\tcbw\n\tsub\tedx, eax\n.L4:\n\tadd\trdi, 1\n\tmovzx\teax, BYTE PTR [rdi]\n\ttest\tal, al\n\tje\t.L2\n.L5:\n\ttest\tdil, 1\n\tjne\t.L3\n\tcbw\n\tlea\tedx, -48[rdx+rax]\n\tjmp\t.L4\n.L6:\n\tmov\tedx, 0\n.L2:\n\ttest\tdx, dx\n\tsete\tal\n\tret\n```\n```assembly [-gcc -O2]\n\t.intel_syntax noprefix\n\t.globl\tisBalanced\nisBalanced:\n\tmovsx\tax, BYTE PTR [rdi]\n\ttest\tal, al\n\tje\t.L6\n\txor\tecx, ecx\n.L5:\n\tlea\tedx, -48[rcx+rax]\n\ttest\tdil, 1\n\tje\t.L4\n\tlea\tedx, 48[rcx]\n\tsub\tedx, eax\n.L4:\n\tmovsx\tax, BYTE PTR 1[rdi]\n\tadd\trdi, 1\n\tmov\tecx, edx\n\ttest\tal, al\n\tjne\t.L5\n\ttest\tdx, dx\n\tsete\tal\n\tret\n.L6:\n\tmov\teax, 1\n\tret\n```\n```assembly [-gcc -Os]\n\t.intel_syntax noprefix\n\t.globl\tisBalanced\nisBalanced:\n\txor\teax, eax\n.L2:\n\tmovsx\tdx, BYTE PTR [rdi]\n\ttest\tdl, dl\n\tje\t.L7\n\ttest\tedi, 1\n\tjne\t.L3\n\tlea\teax, -48[rax+rdx]\n\tjmp\t.L4\n.L3:\n\tadd\teax, 48\n\tsub\teax, edx\n.L4:\n\tinc\trdi\n\tjmp\t.L2\n.L7:\n\ttest\tax, ax\n\tsete\tal\n\tret\n```\n```assembly [-gcc -Oz]\n\t.intel_syntax noprefix\n\t.globl\tisBalanced\nisBalanced:\n\txor\teax, eax\n.L2:\n\tmovsx\tdx, BYTE PTR [rdi]\n\ttest\tdl, dl\n\tje\t.L7\n\ttest\tedi, 1\n\tjne\t.L3\n\tlea\teax, -48[rax+rdx]\n\tjmp\t.L4\n.L3:\n\tadd\teax, 48\n\tsub\teax, edx\n.L4:\n\tinc\trdi\n\tjmp\t.L2\n.L7:\n\ttest\tax, ax\n\tsete\tal\n\tret\n```\n```assembly [-my ASM]\n .intel_syntax noprefix\n .globl isBalanced\nisBalanced:\n\txor\tdx, dx\n\txor\trax, rax\nloop:\n\tmov\tdl, BYTE PTR [rdi]\n\ttest\tdl, dl\n\tje\tendloop\n\tsub\tdl, \'0\'\n\ttest\tdil, 1\n\tjne\todd\n\tadd\tax, dx\n\tjmp\tupdate\nodd:\n\tsub\tax, dx\nupdate:\n\tinc\trdi\n\tjmp\tloop\nendloop:\n\ttest\tax, ax\n\tsetz\tal\n\tjmp\tepilog\nepilog:\n\tret\n```\n\n\n# Run locally\n\nCompile locally the assembly code with GAS or the inline assembly with GCC.\n\n```bash\n$ as -o code.o assembly_code.s\n$ # or\n$ gcc -c -o code.o c_with_inline_assembly_code.c \n```\n\nThen, create a `main.c` file with the function prototype. Here you can include your tests.\n\n```c\n/* main.c */\n\nbool isBalanced(char* num);\n\nint main(int argc, const char *argv[]) {\n // Use isBalanced function\n return 0;\n}\n```\n\nThen, compile `main.c` and link to create the executable\n\n```bash\n$ gcc main.c code.o -o main\n```\n\nFinally, execute\n\n```bash\n$ ./main\n```\n\n
1
0
['C']
1
check-balanced-string
✅ Easy Rust Solution
easy-rust-solution-by-erikrios-frbb
\nimpl Solution {\n pub fn is_balanced(num: String) -> bool {\n let mut even = 0;\n let mut odd = 0;\n\n for (i, ch) in num.into_bytes()
erikrios
NORMAL
2024-11-06T06:45:38.843558+00:00
2024-11-06T06:45:38.843605+00:00
6
false
```\nimpl Solution {\n pub fn is_balanced(num: String) -> bool {\n let mut even = 0;\n let mut odd = 0;\n\n for (i, ch) in num.into_bytes().into_iter().enumerate() {\n let ch = ch - b\'0\';\n if i & 1 == 0 {\n even += ch as usize;\n } else {\n odd += ch as usize;\n }\n }\n\n even == odd\n }\n}\n```
1
0
['Rust']
1
check-balanced-string
maracode
maracode-by-pugazhmara-0xk2
\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n# Code\njava []\nclass Solution {\n public boolean isBalanced(String num) {\n
pugazhmara
NORMAL
2024-11-05T03:43:08.297895+00:00
2024-11-05T03:43:08.297916+00:00
6
false
\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n# Code\n```java []\nclass Solution {\n public boolean isBalanced(String num) {\n int sum1=0,sum2=0,len=num.length();\n for(int i=0,j=1;i<len;i=i+2,j=j+2){\n sum1+=num.charAt(i)-48;\n if(j<len)\n sum2+=num.charAt(j)-48;\n }\n\n return sum1==sum2;\n }\n}\n```
1
0
['Java']
0
check-balanced-string
Best Soln 👌👇
best-soln-by-ram_saketh-wid9
Approach:\n Describe your approach to solving the problem. \n\n# Complexity\n- Time complexity:O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space compl
Ram_Saketh
NORMAL
2024-11-04T18:28:45.996077+00:00
2024-11-04T18:28:45.996117+00:00
6
false
# Approach:\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public boolean isBalanced(String num) {\n StringBuilder sb = new StringBuilder(num);\n int EvenSum = 0;\n int OddSum = 0;\n for(int i=0; i<sb.length();i+=2){\n EvenSum += Integer.valueOf(sb.charAt(i)) - \'0\';\n }\n for(int i=1; i<sb.length();i+=2){\n OddSum += Integer.valueOf(sb.charAt(i)) - \'0\';\n }\n return (EvenSum==OddSum);\n }\n}\n```
1
0
['Java']
0
check-balanced-string
Easy 2 Ways | Sum | Difference | C++
easy-2-ways-sum-difference-c-by-anubhvsh-dzjn
1. Sum Approach \n\nTime Complexity - O(N)\nSpace Complexity - O(1)\n\n\nclass Solution {\npublic:\n bool isBalanced(string num) {\n int odd = 0, even
anubhvshrma18
NORMAL
2024-11-04T17:20:12.125310+00:00
2024-11-04T17:20:12.125340+00:00
28
false
### 1. Sum Approach \n\n*Time Complexity - O(N)*\n*Space Complexity - O(1)*\n\n```\nclass Solution {\npublic:\n bool isBalanced(string num) {\n int odd = 0, even = 0;\n for(int i=0;i<num.length();i++) {\n if(i%2 == 0) {\n even += (num[i]-\'0\');\n } else {\n odd += (num[i]-\'0\');\n }\n }\n return odd==even;\n }\n};\n```\n\n### 2. Difference Approach\n\n*Time Complexity - O(N)*\n*Space Complexity - O(1)*\n\n```\nclass Solution {\npublic:\n bool isBalanced(string num) {\n int diff = 0;\n for(int i=0;i<num.length();i++) {\n if(i%2 == 0) {\n diff += (num[i]-\'0\');\n } else {\n diff -= (num[i]-\'0\');\n }\n }\n return diff==0;\n }\n};\n```
1
0
['Math', 'String', 'C', 'Iterator']
0
check-balanced-string
Adding to two variables on index
adding-to-two-variables-on-index-by-hari-0z95
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
hari04204
NORMAL
2024-11-04T16:44:26.316928+00:00
2024-11-04T16:44:26.316975+00:00
27
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)$$ -->\nO(n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n# Code\n```java []\nclass Solution {\n public boolean isBalanced(String num) {\n int odd = 0;\n int even = 0;\n for(int i = 0; i<num.length(); i++){\n if(i%2==0){\n even += Integer.parseInt(num.charAt(i)+"");\n }\n else{\n odd += Integer.parseInt(num.charAt(i)+"");\n }\n }\n return odd == even;\n }\n}\n```
1
0
['Java']
1
check-balanced-string
Easy C++ Solution || 100% beat || O(n) complexity
easy-c-solution-100-beat-on-complexity-b-42wl
Intuition\nTo determine if a string of digits is "balanced," we can separate the string into digits at even and odd indices. Summing the digits in these two gro
Sanskruti-Dhal
NORMAL
2024-11-04T15:26:44.462033+00:00
2024-11-04T15:26:44.462066+00:00
11
false
# Intuition\nTo determine if a string of digits is "balanced," we can separate the string into digits at even and odd indices. Summing the digits in these two groups lets us compare the sums to see if they are equal.\n\n# Approach\n1. Initialize two variables, evesum and oddsum, to store the sum of digits at even and odd indices, respectively.\n1. Loop through each character in the string num.\n1. Convert each character to an integer.\n1. If the index is even, add the digit to evesum; if the index is odd, add it to oddsum.\n1. After the loop, check if evesum is equal to oddsum. If they are, return true; otherwise, return false.\n\n# Complexity\n- Time complexity: O(n), where \uD835\uDC5B is the length of num, since we loop through each digit once.\n\n- Space complexity: O(1), as we only use a constant amount of additional space.\n\n# Code\n```cpp []\n#include <string>\nusing namespace std;\n\nclass Solution {\npublic:\n bool isBalanced(string num) {\n int evesum = 0, oddsum = 0;\n \n for (int i = 0; i < num.size(); i++) {\n int x = num[i] - \'0\'; \n \n if (i % 2 == 0) { \n evesum += x;\n } else { \n oddsum += x;\n }\n }\n \n return evesum == oddsum;\n }\n};\n\n```
1
0
['C++']
1
check-balanced-string
fold
fold-by-user5285zn-j6dc
We compute the sum of the digits where the odd positions are weighted with $-1$.\n\nrust []\nimpl Solution {\n pub fn is_balanced(num: String) -> bool {\n
user5285Zn
NORMAL
2024-11-04T08:58:21.105338+00:00
2024-11-04T08:58:21.105393+00:00
2
false
We compute the sum of the digits where the odd positions are weighted with $-1$.\n\n```rust []\nimpl Solution {\n pub fn is_balanced(num: String) -> bool {\n num.chars().fold((0, 1), |(s, f),d|\n (s+f*(d as i32 - \'0\' as i32), -f)\n ).0 == 0\n }\n}\n```
1
0
['Rust']
0
check-balanced-string
Java simple solution
java-simple-solution-by-bijoysingh7-okuu
If you found this helpful, an upvote would be appreciated! \uD83D\uDE0A\n# Java Code\njava\nclass Solution {\n public boolean isBalanced(String num) {\n
BijoySingh7
NORMAL
2024-11-04T03:45:48.987830+00:00
2024-11-04T03:45:48.987873+00:00
29
false
If you found this helpful, an upvote would be appreciated! \uD83D\uDE0A\n# Java Code\n```java\nclass Solution {\n public boolean isBalanced(String num) {\n int oddSum = 0;\n int evenSum = 0;\n\n for (int i = 0; i < num.length(); i++) {\n int digit = num.charAt(i) - \'0\';\n if (i % 2 == 0) {\n evenSum += digit;\n } else {\n oddSum += digit;\n }\n }\n\n return evenSum == oddSum;\n }\n}\n```\n\n---\n\n### Explanation\n\n1. **Initialize Sums**: `oddSum` and `evenSum` are used to store the sums of digits at odd and even positions.\n2. **Loop Through String**:\n - For each character in `num`, convert it to a digit.\n - If the index `i` is even, add the digit to `evenSum`; otherwise, add it to `oddSum`.\n3. **Compare Sums**: Return `true` if `evenSum` and `oddSum` are equal, meaning the string is balanced.
1
0
['String', 'Java']
0
check-balanced-string
➡️ One line solution. TC: O(n)
one-line-solution-tc-on-by-m3f-vpyz
# Intuition \n\n\n\n\n\n# Complexity\n- Time complexity: O(n)\n\n\n- Space complexity: O(n)\n\n\n# Code\njavascript []\n/**\n * @param {string} num\n * @retur
M3f
NORMAL
2024-11-03T13:38:38.849629+00:00
2024-11-04T13:59:27.510463+00:00
106
false
<!-- # Intuition -->\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n<!-- # Approach -->\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n)$$\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```javascript []\n/**\n * @param {string} num\n * @return {boolean}\n */\nvar isBalanced = num => !num.split(\'\').reduce((sum, n, i) => i % 2 ? sum + +n : sum - +n, 0);\n```
1
0
['JavaScript']
1
check-balanced-string
easy solution | beats 100%
easy-solution-beats-100-by-leet1101-8ofg
Intuition\nTo determine if the string num is balanced, we need to separate the digits at even and odd indices, calculate the sum of each group, and check if the
leet1101
NORMAL
2024-11-03T07:53:56.217393+00:00
2024-11-03T07:53:56.217419+00:00
28
false
# Intuition\nTo determine if the string `num` is balanced, we need to separate the digits at even and odd indices, calculate the sum of each group, and check if they are equal.\n\n# Approach\n1. Initialize `even` and `odd` sums to zero.\n2. Traverse each character in the string:\n - If the index is even, add the integer value of the digit to `even`.\n - If the index is odd, add the integer value of the digit to `odd`.\n3. Finally, compare the sums of `even` and `odd` indices. If they are equal, return `true`; otherwise, return `false`.\n\n# Complexity\n- **Time complexity**: $$O(n)$$, where $$n$$ is the length of the string, as we iterate through the string once.\n- **Space complexity**: $$O(1)$$, as only a few variables are used.\n\n# Code\n```cpp []\nclass Solution {\npublic:\n bool isBalanced(string num) {\n int even = 0, odd = 0 ;\n for (int i=0; i<num.size(); i++){\n if (i & 1) odd += (num[i] - \'0\') ;\n else even += (num[i] - \'0\') ;\n }\n return even == odd ;\n }\n};\n```
1
0
['C++']
0
check-balanced-string
Python 1 liner
python-1-liner-by-worker-bee-twxs
Intuition\n\neasy one liner\n\n# Code\npython3 []\nclass Solution:\n def isBalanced(self, num: str) -> bool:\n\n return sum([int(x) for i,x in enumera
worker-bee
NORMAL
2024-11-03T04:07:08.612414+00:00
2024-11-03T04:07:08.612441+00:00
107
false
# Intuition\n\neasy one liner\n\n# Code\n```python3 []\nclass Solution:\n def isBalanced(self, num: str) -> bool:\n\n return sum([int(x) for i,x in enumerate(num) if i%2 == 1 ]) == sum([int(x) for i,x in enumerate(num) if i%2 == 0 ])\n \n```
1
0
['Python3']
2
check-balanced-string
c++ solution
c-solution-by-dilipsuthar60-vyxg
\nclass Solution {\npublic:\n bool isBalanced(string num) {\n int n=num.size();\n int sum=0;\n for(int i=0;i<n;i++){\n if(i&1
dilipsuthar17
NORMAL
2024-11-03T04:02:10.396075+00:00
2024-11-03T04:02:10.396103+00:00
40
false
```\nclass Solution {\npublic:\n bool isBalanced(string num) {\n int n=num.size();\n int sum=0;\n for(int i=0;i<n;i++){\n if(i&1){\n sum-=(num[i]-\'0\');\n }\n else{\n sum+=(num[i]-\'0\');\n }\n }\n return sum==0;\n }\n};\n```
1
0
['C', 'C++']
0
check-balanced-string
Easy to Understand || Beats 100% in C++ & Python || C++, Java, Python
easy-to-understand-beats-100-in-c-python-0fgx
null
anubhav_py
NORMAL
2024-12-11T12:06:14.149838+00:00
2024-12-11T12:06:14.149838+00:00
62
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Screenshot\n![image.png](https://assets.leetcode.com/users/images/5699cde6-609f-469d-a6d1-c8f0cc564205_1733918640.1441736.png)\n\n![image.png](https://assets.leetcode.com/users/images/e0147701-f614-492c-8ba7-a7d3c5f8ed42_1733918745.9299948.png)\n\n\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n bool isBalanced(string num) {\n int even = 0;\n int odd = 0;\n\n for (int i = 0; i < num.length(); i++) {\n int s = num[i] - \'0\';\n if (i % 2 == 0) {\n odd += s;\n } else {\n even += s;\n }\n }\n\n return (even == odd);\n }\n};\n\n\n```\n```java []\nclass Solution {\n public boolean isBalanced(String num) {\n int even = 0;\n int odd = 0;\n\n for (int i = 0; i < num.length(); i++) {\n int s = Integer.parseInt(String.valueOf(num.charAt(i)));\n if (i % 2 == 0) {\n odd = odd + s;\n } else {\n even = even + s;\n }\n }\n return (even == odd);\n }\n}\n\n\n```\n```python3 []\nclass Solution:\n def isBalanced(self, num: str) -> bool:\n even = 0\n odd = 0\n\n for i in range(len(num)):\n if i%2 == 0:\n odd += int(num[i])\n else:\n even += int(num[i])\n \n return odd == even\n\n\n```
1
0
['String', 'Python', 'C++', 'Java', 'Python3']
0
check-balanced-string
Fast solution
fast-solution-by-edgharibyan1-sgtz
IntuitionApproachComplexity Time complexity: Space complexity: Code
edgharibyan1
NORMAL
2025-04-10T13:44:04.604761+00:00
2025-04-10T13:44:04.604761+00:00
2
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```javascript [] /** * @param {string} num * @return {boolean} */ var isBalanced = function(num) { let obj = {'odd': 0, 'even': 0}; for(let i = 0; i < num.length; i++) { if(i % 2 === 0) { obj['even'] += +num[i] }else { obj['odd'] += +num[i] } } return obj['odd'] == obj['even'] }; ```
0
0
['JavaScript']
0
check-balanced-string
Simple C++ solution by traversing the string.
simple-c-solution-by-traversing-the-stri-ht83
Complexity Time complexity:O(N) Space complexity:O(1) Code
vansh16
NORMAL
2025-04-10T10:47:14.968972+00:00
2025-04-10T10:47:14.968972+00:00
1
false
# Complexity - Time complexity:O(N) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity:O(1) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: bool isBalanced(string num) { int sumo=0,sume=0; for(int i=0;i<num.size();i++) { if(i%2==0) sume+=num[i]-'0'; else sumo+=num[i]-'0'; } return sume==sumo; } }; ```
0
0
['String', 'C++']
0
check-balanced-string
java
java-by-xyza41004-6dqo
IntuitionApproachComplexity Time complexity: Space complexity: Code
xyza41004
NORMAL
2025-04-10T09:06:54.672656+00:00
2025-04-10T09:06:54.672656+00:00
1
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public boolean isBalanced(String num) { int even=0,odd=0; for(int i=0;i<num.length();i++) { if(i%2==0) { even+=num.charAt(i)-'0'; } else { odd+=num.charAt(i)-'0'; } } if(odd==even) { return true; } return false; } } ```
0
0
['Java']
0
check-balanced-string
time complexity O(n), and no extra memory
time-complexity-on-and-no-extra-memory-b-gybs
IntuitionWe do need to use extra space because all digits has to sum up and the result should be zero, as long as even digits is positive and odd digits are neg
bear-with-me
NORMAL
2025-04-10T06:27:02.358018+00:00
2025-04-10T06:27:02.358018+00:00
1
false
# Intuition We do need to use extra space because all digits has to sum up and the result should be zero, as long as even digits is positive and odd digits are negative # Approach Recursivily return the next digit with the correct signal (positive or negative) to sum up all digits at the and # Complexity - Time complexity: O(n) - Space complexity: we do not need extra space, O(1) # Code ```python3 [] class Solution: def isBalanced(self, num: str) -> bool: def helper(i): if i >= len(num): return 0 if i % 2 == 0: return (+1 * int(num[i])) + helper(i + 1) else: return (-1 * int(num[i])) + helper(i + 1) return helper(0) == 0 ```
0
0
['Python3']
0
check-balanced-string
isBalanced with a conversion solution from rune to int
isbalanced-with-a-conversion-solution-fr-rcpf
Complexity Time complexity: O(n) Space complexity: O(1) Code
44437
NORMAL
2025-04-07T16:56:29.527342+00:00
2025-04-07T16:56:29.527342+00:00
1
false
# Complexity - Time complexity: $$O(n)$$ <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: $$O(1)$$ <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```golang [] func isBalanced(num string) bool { var even int var odd int for i, v := range num { value := int(v - '0') if i % 2 == 0 { even += value continue } odd += value } return even == odd } ```
0
0
['Go']
0
check-balanced-string
Sum the odd and even in two variables, and just compare it
sum-the-odd-and-even-in-two-variables-an-377n
IntuitionApproachComplexity Time complexity: Space complexity: Code
vikas26061995
NORMAL
2025-04-06T12:52:52.730491+00:00
2025-04-06T12:52:52.730491+00:00
2
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```javascript [] /** * @param {string} num * @return {boolean} */ var isBalanced = function(num) { let sumEvenIndex = 0; let sumOddIndex = 0; for(let i =0; i < num.length; i++){ if(i % 2 == 0){ sumEvenIndex += parseInt(num[i]); } else{ sumOddIndex += parseInt(num[i]); } } if(sumEvenIndex == sumOddIndex) return true; return false; // console.log("sum",sumEvenIndex,sumOddIndex) }; ```
0
0
['JavaScript']
0
check-balanced-string
Beats 100% - Simple Method
beats-100-simple-method-by-siva12443-n6wt
Code
Siva12443
NORMAL
2025-04-03T07:17:53.795295+00:00
2025-04-03T07:17:53.795295+00:00
1
false
# Code ```javascript [] /** * @param {string} num * @return {boolean} */ var isBalanced = function(num) { let even = 0; let odd = 0; for(let i = 0; i < num.length; i+=2){ even += parseInt(num[i]) } for(let j = 1; j < num.length; j+=2 ){ odd += parseInt(num[j]) } if(even === odd){ return true; } return false; }; ```
0
0
['JavaScript']
0
check-balanced-string
C#
c-by-m093020099-x3lo
IntuitionApproachComplexity Time complexity:O(n) Space complexity:O(1) Code
m093020099
NORMAL
2025-04-02T16:55:17.938984+00:00
2025-04-02T16:55:17.938984+00:00
2
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity:O(n) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity:O(1) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```csharp [] public class Solution { public bool IsBalanced(string num) { var evenPointer = 0; var oddPointer = 1; var even = 0L; var odd = 0L; while (evenPointer < num.Length || oddPointer < num.Length) { if (evenPointer < num.Length) { even += num[evenPointer] - '0'; } if (oddPointer < num.Length) { odd += num[oddPointer] - '0'; } evenPointer += 2; oddPointer += 2; } return even == odd; } } ```
0
0
['C#']
0
check-balanced-string
python solved code
python-solved-code-by-archananagaraj-vmy5
IntuitionApproachComplexity Time complexity: Space complexity: Code
archananagaraj
NORMAL
2025-04-02T06:12:45.177623+00:00
2025-04-02T06:12:45.177623+00:00
1
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python [] class Solution(object): def isBalanced(self, num): even=0 odd=0 for i in range(len(num)): digit=int(num[i]) if i%2==0: even=even+digit else: odd=odd+digit return even==odd ```
0
0
['Python']
0
check-balanced-string
Ruby Solution
ruby-solution-by-kishorecheruku-rfe7
IntuitionApproachComplexity Time complexity: Space complexity: Code
kishorecheruku
NORMAL
2025-04-01T02:03:49.880002+00:00
2025-04-01T02:03:49.880002+00:00
1
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```ruby [] # @param {String} num # @return {Boolean} def is_balanced(num) even = 0 odd = 0 num.chars.each_with_index do |v, i| i.even? ? even += v.to_i : odd += v.to_i end even == odd end ```
0
0
['Ruby']
0