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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
minimize-malware-spread-ii
|
Tarjan’s Algorithm - java
|
tarjans-algorithm-java-by-hassam_472-m66l
|
\n# Code\njava []\nclass Solution {\n private int dfs(int[][] graph, int u, int parent, int time, int[] depth, int[] low, boolean[] infected, int[] count) {\
|
hassam_472
|
NORMAL
|
2024-10-19T12:42:24.952511+00:00
|
2024-10-19T12:42:24.952545+00:00
| 12 | false |
\n# Code\n```java []\nclass Solution {\n private int dfs(int[][] graph, int u, int parent, int time, int[] depth, int[] low, boolean[] infected, int[] count) {\n low[u] = depth[u] = time; // Set depth and low values\n boolean isInfected = infected[u];\n int size = 1; // Size of the component rooted at u\n\n for (int v = 0; v < graph[u].length; v++) {\n if (graph[u][v] == 1) { // If u is connected to v\n if (depth[v] == 0) { // v is not visited\n int subtreeSize = dfs(graph, v, u, time + 1, depth, low, infected, count);\n if (subtreeSize == 0) { // If v is infected\n isInfected = true;\n } else {\n size += subtreeSize; // Increase size of the component\n }\n if (low[v] >= depth[u]) { // If v can\'t reach back to u or its ancestors\n count[u] += subtreeSize; // Count size for u\n }\n low[u] = Math.min(low[u], low[v]); // Update low value\n } else if (v != parent) { // Update low value for back edge\n low[u] = Math.min(low[u], depth[v]);\n }\n }\n }\n return isInfected ? 0 : size; // Return size if not infected, otherwise 0\n }\n\n public int minMalwareSpread(int[][] graph, int[] initial) {\n int n = graph.length;\n int ans = initial[0], maxCount = 0;\n boolean[] infected = new boolean[n];\n\n // Mark all initially infected nodes\n for (int u : initial) infected[u] = true;\n\n int[] depth = new int[n], low = new int[n], count = new int[n];\n\n // Perform DFS for each initially infected node\n for (int u : initial) {\n if (depth[u] == 0) { // If u is not visited\n dfs(graph, u, -1, 1, depth, low, infected, count);\n }\n // Check for the optimal node to remove\n if (count[u] > maxCount || (count[u] == maxCount && u < ans)) {\n maxCount = count[u]; // Update maximum count\n ans = u; // Update answer node\n }\n }\n return ans; // Return the best node to remove\n }\n}\n\n```
| 0 | 0 |
['Java']
| 0 |
minimize-malware-spread-ii
|
DFS O(n^2) Time complexity
|
dfs-on2-time-complexity-by-yash559-fcy4
|
Intuition\n- just like this question\'s previous cousin, we have to remove malicious nodes, but here we also have option of remove it completely from graph.\n-
|
yash559
|
NORMAL
|
2024-10-14T01:21:01.528580+00:00
|
2024-10-14T01:21:01.528597+00:00
| 5 | false |
# Intuition\n- just like this question\'s previous cousin, we have to remove malicious nodes, but here we also have option of remove it completely from graph.\n- We can\'t traverse through this node, this is like a dead person in this question, so it can\'t be infected anyway.\n- In it\'s cousin question it is the healthy person you can say that, once any node is infected this guy get\'s infected if he is connected to any infected node.\n\n# Complexity\n- Time complexity: $$O(n^2)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n^2)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n unordered_map<int,vector<int>> adj;\n int dfs(int node, vector<bool> &visited, int remove_node) {\n visited[node] = true;\n int size = 1;\n for(auto &child : adj[node]) {\n if(child != remove_node && !visited[child]) {\n size += dfs(child, visited, remove_node);\n }\n }\n return size;\n }\n int minMalwareSpread(vector<vector<int>>& graph, vector<int>& initial) {\n int n = graph.size();\n for(int i = 0;i < n;i++) {\n for(int j = 0;j < n;j++) {\n if(graph[i][j] == 1) {\n adj[i].push_back(j);\n }\n }\n }\n int sz = initial.size();\n int mi = INT_MAX;\n int ind = -1;\n sort(initial.begin(),initial.end());\n for(int i = 0; i < sz;i++) {\n int remove_node = initial[i];\n vector<bool> visited(n,false);\n int total_nodes = 0;\n for(int j = 0;j < sz;j++) {\n if(initial[j] != remove_node && !visited[initial[j]]) {\n total_nodes += dfs(initial[j], visited, remove_node);\n }\n }\n // cout << total_nodes << \' \' << remove_node << endl;\n if(mi > total_nodes) {\n mi = total_nodes;\n ind = remove_node;\n }\n // if(mi == total_nodes) {\n // mi = min(mi, remove_node);\n // }\n }\n return ind;\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
minimize-malware-spread-ii
|
Brute Force | Beginner's Solution
|
brute-force-beginners-solution-by-kndudh-b0xj
|
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
|
kndudhushyanthan
|
NORMAL
|
2024-10-08T14:37:34.102057+00:00
|
2024-10-08T14:37:34.102088+00:00
| 7 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int n;\n void dfs(int node, vector<vector<int>>&adj, vector<int>&curr,vector<int>&vis){\n vis[node]=1;\n curr.push_back(node);\n for(auto x:adj[node]){\n if(vis[x]==1) continue;\n dfs(x,adj,curr,vis);\n }\n }\n int valid(vector<vector<int>>&adj, vector<int>&ini){\n set<int>st(ini.begin(),ini.end());\n set<int>answer;\n for(int i=0;i<ini.size();i++){\n vector<int>curr,vis(n,0);\n dfs(ini[i],adj,curr,vis);\n for(int i=0;i<curr.size();i++){\n if(st.find(curr[i])==st.end()){\n answer.insert(curr[i]);\n }\n }\n }\n return answer.size();\n }\n int minMalwareSpread(vector<vector<int>>& graph, vector<int>& ini) {\n n = graph.size();\n int ans = INT_MAX;\n int curr=INT_MAX;\n sort(ini.begin(),ini.end());\n for (int k = 0; k < ini.size(); k++) {\n vector<vector<int>> adj(n);\n for (int i = 0; i < n; i++) {\n if (i == ini[k])\n continue;\n for (int j = 0; j < i; j++) {\n if (j == ini[k])\n continue;\n if (graph[i][j] == 1) {\n adj[i].push_back(j);\n adj[j].push_back(i);\n }\n }\n }\n for(int i=0;i<n;i++){\n for(auto x:adj[i]){\n cout<<i<<" "<<x<<endl;\n }\n } \n if(valid(adj,ini)<curr){\n curr=valid(adj,ini);\n ans=ini[k];\n }\n }\n return ans;\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
minimize-malware-spread-ii
|
Simple Java Solution
|
simple-java-solution-by-sakshikishore-fyzr
|
Code\njava []\nclass Solution {\n public int minMalwareSpread(int[][] graph, int[] initial) {\n int result=graph.length;\n int min=graph.length
|
sakshikishore
|
NORMAL
|
2024-10-02T04:12:18.981808+00:00
|
2024-10-02T04:12:18.981838+00:00
| 14 | false |
# Code\n```java []\nclass Solution {\n public int minMalwareSpread(int[][] graph, int[] initial) {\n int result=graph.length;\n int min=graph.length;\n for(int i=0;i<initial.length;i++)\n {\n Queue<Integer> q=new LinkedList<Integer>();\n HashSet<Integer> hset=new HashSet<Integer>();\n hset.add(initial[i]);\n for(int j=0;j<initial.length;j++)\n {\n if(j==i)\n {\n continue;\n }\n q.add(initial[j]);\n hset.add(initial[j]);\n }\n int count=0;\n while(q.size()>0)\n {\n int x=q.poll();\n count++;\n for(int k=0;k<graph[0].length;k++)\n {\n if(graph[x][k]==1 && !hset.contains(k))\n {\n q.add(k);\n hset.add(k);\n }\n }\n\n }\n if(count==min)\n {\n result=Math.min(result,initial[i]);\n min=count;\n }\n else if(count<min)\n {\n result=initial[i];\n min=count;\n }\n }\n return result;\n}\n}\n```
| 0 | 0 |
['Java']
| 0 |
minimize-malware-spread-ii
|
Interview Prepartion
|
interview-prepartion-by-najnifatima01-yn6r
|
Let me clarify the question once ...\ntestcase\nconstraints :\nn == graph.length\nn == graph[i].length\n2 <= n <= 300\ngraph[i][j] is 0 or 1.\ngraph[i][j] == gr
|
najnifatima01
|
NORMAL
|
2024-09-26T05:18:05.797248+00:00
|
2024-09-26T05:18:05.797269+00:00
| 3 | false |
Let me clarify the question once ...\ntestcase\nconstraints :\nn == graph.length\nn == graph[i].length\n2 <= n <= 300\ngraph[i][j] is 0 or 1.\ngraph[i][j] == graph[j][i]\ngraph[i][i] == 1\n1 <= initial.length < n\n0 <= initial[i] <= n - 1\nAll the integers in initial are unique.\nGive me a few minutes to think it through\ncomment - BF, optimal\ncode\n\n# Intuition\ngraph - Union find\n\n# Approach\n\n# Complexity\n- Time complexity:\n$$O(n^2)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<int> parent;\n int find(int node) {\n if(parent[node] != node) {\n return parent[node] = find(parent[node]);\n }\n return parent[node];\n }\n void Union(int u, int v) {\n int rootu = find(u);\n int rootv = find(v);\n if(rootu != rootv) {\n parent[rootu] = rootv;\n }\n }\n int minMalwareSpread(vector<vector<int>>& graph, vector<int>& initial) {\n int n = graph.size();\n parent.resize(n);\n for(int i=0; i<n; i++) {\n parent[i] = i;\n }\n vector<int> clean;\n set<int> initialSet(initial.begin(), initial.end());\n for(int i=0; i<n; i++) {\n if(!initialSet.count(i)) {\n clean.push_back(i);\n }\n }\n for(auto i: clean) {\n for(auto j: clean) {\n if(i != j && graph[i][j]) {\n Union(i, j);\n }\n }\n }\n vector<int> area(n, 0);\n for (auto i : clean) {\n area[find(i)]++;\n }\n \n map<int, set<int>> infect_node;\n map<int, int> infect_count;\n for (auto i : initial) {\n for (auto j : clean) {\n if (graph[i][j]) {\n infect_node[i].insert(find(j));\n }\n }\n for (auto j : infect_node[i]) {\n infect_count[j] += 1;\n }\n }\n int res = initial[0], max_cnt = -1;\n for (auto& [malware, nodes] : infect_node) {\n int count = 0;\n for (auto& node : nodes) {\n if (infect_count[node] == 1) {\n count += area[node];\n }\n }\n if (count > max_cnt || (count >= max_cnt && malware < res)) {\n max_cnt = count;\n res = malware;\n }\n }\n return res;\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
minimize-malware-spread-ii
|
C++ bfs
|
c-bfs-by-user5976fh-waay
|
cpp []\nclass Solution {\npublic:\n vector<vector<int>> g;\n vector<int> init;\n \n int minMalwareSpread(vector<vector<int>>& graph, vector<int>& in
|
user5976fh
|
NORMAL
|
2024-09-07T02:12:01.127688+00:00
|
2024-09-07T02:12:01.127726+00:00
| 2 | false |
```cpp []\nclass Solution {\npublic:\n vector<vector<int>> g;\n vector<int> init;\n \n int minMalwareSpread(vector<vector<int>>& graph, vector<int>& initial) {\n g = graph;\n int ans = 0, largest = INT_MIN;\n sort(initial.begin(), initial.end());\n init = initial;\n for (int i = 0; i < init.size(); ++i) {\n int prev = init[i];\n init[i] = -1;\n int x = bfs(prev);\n if (x > largest) {\n largest = x;\n ans = prev;\n }\n init[i] = prev;\n }\n return ans; \n }\n \n int bfs(int removed) {\n queue<int> q;\n vector<bool> visited(g.size(), false);\n for (auto& n : init) {\n if (n != -1 && n != removed) {\n visited[n] = true;\n q.push(n);\n }\n }\n while (!q.empty()) {\n int f = q.front();\n q.pop();\n for (int i = 0; i < g[f].size(); ++i) {\n if (g[f][i] && !visited[i] && i != removed) {\n visited[i] = true;\n q.push(i);\n }\n }\n }\n int uninfected = 0;\n for (auto b : visited) uninfected += !b;\n return uninfected;\n }\n};\n\n```
| 0 | 0 |
['C++']
| 0 |
minimize-malware-spread-ii
|
Using Dsu
|
using-dsu-by-venkatarohit_p-44bi
|
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
|
venkatarohit_p
|
NORMAL
|
2024-08-23T17:35:41.898824+00:00
|
2024-08-23T17:35:41.898864+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 static int find(int i,int[] parent){\n if(i==parent[i]){\n return i;\n }\n return parent[i]=find(parent[i],parent);\n }\n public static void Union(int x,int y,int[] parent){\n int i=find(x,parent);\n int j=find(y,parent);\n parent[i]=j;\n return;\n }\n public static int Dsu(int[][] graph,int[] initial,int rem){\n int[] parent=new int[graph.length];\n \n for(int i=0;i<graph.length;i++){\n parent[i]=i;\n }\n\n for(int i=0;i<graph.length;i++){\n for(int j=i+1;j<graph.length;j++){\n if(i==rem || j==rem || graph[i][j]==0){\n continue;\n }\n else{\n Union(i,j,parent);\n }\n }\n }\n HashSet<Integer> infected=new HashSet<>();\n for(int i=0;i<initial.length;i++){\n if(initial[i]==rem) continue;\n else{\n infected.add(find(initial[i],parent));\n }\n }\n int count=0;\n for(int i=0;i<graph.length;i++){\n if(infected.contains(find(i,parent))){\n count++;\n }\n }\n return count;\n }\n public int minMalwareSpread(int[][] graph, int[] initial) {\n int min_val=Integer.MAX_VALUE;\n int min_index=-1;\n Arrays.sort(initial);\n for(int i=0;i<initial.length;i++){\n int val=Dsu(graph,initial,initial[i]);\n if(val<min_val){\n min_val=val;\n min_index=initial[i];\n }\n }\n return min_index;\n }\n}\n```
| 0 | 0 |
['Java']
| 0 |
minimize-malware-spread-ii
|
928. Minimize Malware Spread II.cpp
|
928-minimize-malware-spread-iicpp-by-202-8gyg
|
Code\n\nclass UnionFind {\npublic: \n vector<int> parent, rank; \n UnionFind(int n) {\n parent.resize(n); \n iota(parent.begin(), parent.end
|
202021ganesh
|
NORMAL
|
2024-08-20T11:04:38.046921+00:00
|
2024-08-20T11:04:38.046953+00:00
| 8 | false |
**Code**\n```\nclass UnionFind {\npublic: \n vector<int> parent, rank; \n UnionFind(int n) {\n parent.resize(n); \n iota(parent.begin(), parent.end(), 0); \n rank = vector<int>(n, 1); \n } \n int find(int p) {\n if (p != parent[p]) \n parent[p] = find(parent[p]); \n return parent[p]; \n } \n bool connect(int p, int q) {\n int prt = find(p), qrt = find(q); \n if (prt == qrt) return false; \n if (rank[prt] > rank[qrt]) swap(prt, qrt); \n parent[prt] = qrt; \n rank[qrt] += rank[prt]; \n return true; \n }\n}; \nclass Solution {\npublic:\n int minMalwareSpread(vector<vector<int>>& graph, vector<int>& initial) {\n int n = graph.size(); \n vector<bool> infect(n, false); \n for (auto& x : initial) infect[x] = true; \n UnionFind* uf = new UnionFind(n); \n for (int u = 0; u < n; ++u) \n if (!infect[u]) \n for (int v = 0; v < n; ++v) \n if (!infect[v] && graph[u][v]) \n uf->connect(u, v); \n unordered_map<int, unordered_set<int>> mp; \n for (auto& u : initial) \n for (int v = 0; v < n; ++v) \n if (!infect[v] && graph[u][v]) \n mp[u].insert(uf->find(v)); \n unordered_map<int, int> freq; \n for (auto& [k, v] : mp) \n for (auto& x : v) ++freq[x]; \n int best = -1, ans = -1; \n for (auto& u : initial) {\n int cnt = 0; \n for (auto& v : mp[u]) \n if (freq[v] == 1) cnt += uf->rank[v]; \n if (cnt > best || (cnt == best && u < ans)) \n ans = u, best = cnt; \n }\n return ans; \n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
minimize-malware-spread-ii
|
BFS C++ simple code
|
bfs-c-simple-code-by-adityakumar8068-rzjt
|
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
|
adityakumar8068
|
NORMAL
|
2024-08-19T10:12:58.817072+00:00
|
2024-08-19T10:12:58.817103+00:00
| 14 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int minMalwareSpread(vector<vector<int>>& graph, vector<int>& initial) {\n int m=initial.size();\n int ans=-1;\n int maxi=1e9;\n sort(initial.begin(),initial.end());\n for(int i=0;i<m;i++){\n int count=0;\n queue<int>q;\n vector<bool>vist(graph.size(),false);\n for(int k=0;k<m;k++){\n if(k!=i){\n q.push(initial[k]);\n vist[initial[k]]=true;\n count++;\n }\n }\n while(!q.empty()){\n int node=q.front();\n q.pop();\n for(int j=0;j<graph.size();j++){\n if(graph[node][j]==1&&j!=node&&j!=initial[i]&&!vist[j]){\n vist[j]=true;\n q.push(j);\n count++;\n }\n }\n }\n cout<<count<<\',\';\n if(count<maxi){\n ans=initial[i];\n maxi=count;\n \n }\n }\n return ans;\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
minimize-malware-spread-ii
|
scala DisjointSet/UnionFind
|
scala-disjointsetunionfind-by-vititov-hpq8
|
scala\nobject Solution {\n def minMalwareSpread(graph: Array[Array[Int]], initial: Array[Int]): Int =\n import scala.util.chaining._\n val initialSet = i
|
vititov
|
NORMAL
|
2024-08-10T16:50:43.922332+00:00
|
2024-08-10T16:50:43.922361+00:00
| 2 | false |
```scala\nobject Solution {\n def minMalwareSpread(graph: Array[Array[Int]], initial: Array[Int]): Int =\n import scala.util.chaining._\n val initialSet = initial.to(collection.immutable.BitSet)\n val xMap = graph.zipWithIndex.flatMap{case (a,i) => a.zipWithIndex.collect{\n case (v,j) if i!=j && v!=0 => List((i,j),(j,i))\n }}.flatten.distinct.groupMap(_._1)(_._2)\n initial.iterator.map{ node =>\n val djs = graph.indices.to(Array)\n def root(i: Int): Int = if(i == djs(i)) i else root(djs(i)).tap(djs(i) = _)\n def join(i: Int)(j: Int): Int = \n if(initialSet.contains(root(j))) root(j).tap(djs(root(i)) = _)\n else root(i).tap(djs(root(j)) = _)\n xMap.iterator.filter(_._1 != node).foreach{case (k,v) =>\n v.filter(k2 => k2>k && k2 != node).foreach(k2 => join(k)(k2))\n }\n djs.indices.foreach(root)\n (djs.zipWithIndex.collect{case (k,i) if k!=node && initialSet.contains(k) => i}.length, node)\n }.min._2\n}\n```
| 0 | 0 |
['Hash Table', 'Union Find', 'Graph', 'Scala']
| 0 |
minimize-malware-spread-ii
|
python using bridge concept
|
python-using-bridge-concept-by-rnajafi76-ho6d
|
\nclass Solution:\n def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:\n n=len(graph)\n visited=[-1]*n\n res
|
rnajafi76
|
NORMAL
|
2024-07-12T06:43:10.533794+00:00
|
2024-07-12T06:44:08.586648+00:00
| 3 | false |
```\nclass Solution:\n def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:\n n=len(graph)\n visited=[-1]*n\n res=(-1,-inf)\n infected=set(initial)\n \n def dfs(node,root_index):\n if visited[node]!=-1:\n return (True,0)\n\n if node in infected and node!=initial[root_index]:\n return (True,0)\n visited[node]=root_index\n\n ans=(False,1)\n\n for to in range(n):\n if node==to or graph[node][to]==0:\n continue\n if visited[to] ==root_index:\n continue\n\n \n connected_to_other,m=dfs(to,root_index)\n if connected_to_other and node!=initial[root_index]:\n return (True,0)\n if connected_to_other==False:\n ans=(ans[0],m+ans[1])\n if ans[0]:\n return ans\n return ans\n \n for m in range(len(initial)):\n connected_to_other,cnt=dfs(initial[m],m)\n if connected_to_other:\n continue\n \n if cnt>res[1] or (cnt==res[1] and initial[m]< initial[res[0]]):\n res=(m,cnt)\n if res[0]==-1:\n return initial[0]\n return initial[res[0]]\n \n\n```
| 0 | 0 |
['Depth-First Search', 'Python']
| 0 |
minimize-malware-spread-ii
|
DP on Graphs/Tree with Re-Rooting | C++ | O(n^2) Time
|
dp-on-graphstree-with-re-rooting-c-on2-t-w3r0
|
Idea is based on DP on Trees/Graphs with Re-rooting.\n\nApproach: We view each connected graph component as a tree (using DFS Tree), then we apply the conepts o
|
sarvasva_309
|
NORMAL
|
2024-06-29T11:50:46.624305+00:00
|
2024-06-29T11:50:46.624339+00:00
| 9 | false |
Idea is based on DP on Trees/Graphs with Re-rooting.\n\nApproach: We view each connected graph component as a tree (using DFS Tree), then we apply the conepts of DP on Tree with Re-rooting to solve the problem. \n\nStep1: Find all articulation points in the graph.\n\nStep2: Perform DFS and update the values of number of nodes in subtree of each node and infected nodes in subtree of each node.\n\nStep3: Perform re-rooting using another DFS function (dfs2) and using the results of parent node, update the results for children node.\n\nStep4: Check for removal condition on (1) Infected Node AND (2) If the node is the **ONLY** infected node in this connected component OR the node is an articulation point.\n\n```\nclass Solution {\npublic:\n set<int> articulation;\n vector<bool> vis;\n vector<vector<int>> adj;\n vector<int> tin, low;\n int dfs_timer;\n int n;\n void dfs_articulation(int v, int par = -1) {\n vis[v] = 1;\n tin[v] = low[v] = dfs_timer++;\n int children = 0;\n for (auto& child : adj[v]) {\n if (child == par)\n continue;\n if (!vis[child]) {\n dfs_articulation(child, v);\n low[v] = min(low[v], low[child]);\n if (low[child] >= tin[v] && par != -1)\n articulation.insert(v);\n children++;\n } else\n low[v] = min(low[v], tin[child]);\n }\n if (par == -1 && children >= 2)\n articulation.insert(v);\n }\n\n void find_cutpoints() {\n dfs_timer = 0;\n vis.assign(n, false);\n tin.assign(n, -1);\n low.assign(n, -1);\n for (int i = 0; i < n; ++i)\n if (!vis[i])\n dfs_articulation(i);\n }\n\n vector<int> subRootedNodes, components, infectedNodes;\n vector<bool> isInfectedNode;\n int answer, total, answerNode;\n void dfs1(int node) {\n vis[node] = 1;\n subRootedNodes[node] = 1;\n if (isInfectedNode[node])\n infectedNodes[node] = 1;\n\n for (auto& child : adj[node]) {\n if (!vis[child]) {\n dfs1(child);\n infectedNodes[node] += infectedNodes[child];\n subRootedNodes[node] += subRootedNodes[child];\n }\n }\n }\n\n void dfs2(int node, int x, int topNodes, int topInfectedNodes, bool flag) {\n vis[node] = 1;\n int currentInfected = 0;\n if (topInfectedNodes > 0)\n currentInfected = topNodes;\n\n for (auto& child : adj[node]) {\n if (!vis[child]) {\n dfs2(child, x,\n topNodes + subRootedNodes[node] - subRootedNodes[child],\n topInfectedNodes + infectedNodes[node] -\n infectedNodes[child],\n flag);\n if (infectedNodes[child])\n currentInfected += subRootedNodes[child];\n }\n }\n if (isInfectedNode[node] &&\n (flag || articulation.find(node) != articulation.end())) {\n if (answer > total - x + currentInfected + 1) {\n answer = total - x + currentInfected + 1;\n answerNode = node;\n }\n if (answer == total - x + currentInfected + 1) {\n answerNode = min(answerNode, node);\n }\n }\n }\n int minMalwareSpread(vector<vector<int>>& graph, vector<int>& initial) {\n n = graph.size();\n adj.assign(n, vector<int>(0));\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n if (graph[i][j] && i != j) {\n adj[i].push_back(j);\n adj[j].push_back(i);\n }\n }\n }\n isInfectedNode.assign(n, 0);\n subRootedNodes.assign(n, 0);\n infectedNodes.assign(n, 0);\n components.assign(n, 0);\n\n answerNode = n;\n for (auto inf : initial)\n isInfectedNode[inf] = 1, answerNode = min(answerNode, inf);\n cout << answerNode << endl;\n find_cutpoints();\n\n vis.assign(n, 0);\n total = 0;\n for (int i = 0; i < n; i++) {\n if (!vis[i]) {\n dfs1(i);\n total += (infectedNodes[i] > 0 ? subRootedNodes[i] : 0);\n }\n }\n\n vis.assign(n, 0);\n answer = total;\n bool flag = 0;\n for (int i = 0; i < n; i++) {\n if (!vis[i]) {\n int currentInfectedNodes =\n (infectedNodes[i] > 0 ? subRootedNodes[i] : 0);\n if (infectedNodes[i] == 1)\n flag = 1;\n dfs2(i, currentInfectedNodes, 0, 0, flag);\n }\n }\n return answerNode;\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
minimize-malware-spread-ii
|
Python Depth-first traversal with adjacency list for each initial, O(mn^2) time
|
python-depth-first-traversal-with-adjace-mwdk
|
Intuition\nVariant of depth-first search\n\n# Approach\n1. Create an adjacency list from adjacency matrix.\n2. For each initially infected node:\n 1. Remove
|
fdtfbn
|
NORMAL
|
2024-06-25T15:49:45.306453+00:00
|
2024-06-25T15:49:45.306487+00:00
| 36 | false |
# Intuition\nVariant of depth-first search\n\n# Approach\n1. Create an adjacency list from adjacency matrix.\n2. For each initially infected node:\n 1. Remove it from the graph (virtually).\n 2. Traverse the graph once to infect nodes.\n 3. Count the number of nodes infected.\n 4. Maintain the minimum.\n\n# Complexity\nLet m = len(initial).\n\n- Time complexity: $O(mn^2)$\n\n- Space complexity: $O(n^2)$\n\n# Code\n```\nclass Solution:\n def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:\n n = len(graph)\n adj_list = self.to_adj_list(graph)\n chosen_node = n\n min_infected_count = n + 1\n for remove_node in initial:\n infected = [False for _ in range(n)]\n for init in initial:\n self.infect(init, adj_list, infected, remove_node)\n infected_count = sum(infected)\n if infected_count < min_infected_count or \\\n (infected_count == min_infected_count and remove_node < chosen_node):\n min_infected_count = infected_count\n chosen_node = remove_node\n return chosen_node\n\n \n @staticmethod\n def infect(node: int, adj_list: List[List[int]], infected: List[bool], remove_node: int) -> None:\n if node != remove_node:\n infected[node] = 1\n for neighbor in adj_list[node]:\n if not infected[neighbor]:\n Solution.infect(neighbor, adj_list, infected, remove_node)\n\n\n @staticmethod\n def to_adj_list(adj_mat: List[List[int]]) -> List[List[int]]:\n n = len(adj_mat)\n adj_list = [[] for _ in range(n)]\n for i in range(1, n):\n for j in range(i):\n if adj_mat[i][j]:\n adj_list[i].append(j)\n adj_list[j].append(i)\n return adj_list\n```
| 0 | 0 |
['Depth-First Search', 'Python3']
| 0 |
minimize-malware-spread-ii
|
Union Find Based| C++| Approach
|
union-find-based-c-approach-by-thecoderk-yyl0
|
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
|
TheCoderKrukks
|
NORMAL
|
2024-06-23T04:25:48.836812+00:00
|
2024-06-23T04:25:48.836837+00:00
| 43 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/*\nThe approach utilizes Disjoint Set Union (DSU) to model the connectivity of nodes in the graph, excluding initially infected nodes. It then tracks parent-child relationships between infected nodes and their connected components using freq and freq2 vectors. By calculating the size of DSU components connected to each infected node, it determines which removal minimizes malware spread, considering connections and avoiding redundant infections. Finally, it selects the node with the smallest index among ties to optimize removal and minimize potential malware propagation.\n*/\nclass DSU {\npublic:\n vector<int> parent, rank, size;\n \n DSU(int n) {\n parent.resize(n);\n rank.resize(n, 0);\n size.resize(n, 1);\n for (int i = 0; i < n; i++) {\n parent[i] = i;\n }\n }\n \n int find(int x) {\n if (x == parent[x]) {\n return x;\n }\n return parent[x] = find(parent[x]);\n }\n \n void unionbyrank(int x, int y) {\n int xx = find(x);\n int yy = find(y);\n if (xx == yy) return;\n if (rank[xx] < rank[yy]) {\n parent[xx] = yy;\n } else if (rank[xx] > rank[yy]) {\n parent[yy] = xx;\n } else {\n rank[xx]++;\n parent[yy] = xx;\n }\n return;\n }\n\n void unionbysize(int x, int y) {\n int xx = find(x);\n int yy = find(y);\n if (xx == yy) return;\n if (size[xx] < size[yy]) {\n parent[xx] = yy;\n size[yy] += size[xx];\n } else if (size[xx] > size[yy]) {\n parent[yy] = xx;\n size[xx] += size[yy];\n } else {\n size[xx] += size[yy];\n parent[yy] = xx;\n }\n return;\n }\n};\n\nclass Solution {\npublic:\n int minMalwareSpread(vector<vector<int>>& graph, vector<int>& initial) {\n int n = graph.size();\n DSU ds(n);\n unordered_map<int, int> mp;\n for (auto t : initial) {\n mp[t]++;\n }\n for (int i = 0; i < n; i++) {\n if (mp[i]) continue;\n for (int j = 0; j < n; j++) {\n if (i == j || mp[j]) continue;\n if (graph[i][j] == 1) ds.unionbysize(i, j);\n }\n }\n vector<vector<int>> freq(n); \n vector<vector<int>> freq2(n); \n for (auto t : initial) {\n for (int i = 0; i < n; i++) {\n if (i == t || mp[i]) continue; \n if (graph[t][i] == 1) {\n int par = ds.find(i);\n freq[t].push_back(par); \n freq2[par].push_back(t);\n \n }\n }\n }\n int ans = -1e8, mini = 1e8;\n for (auto t:initial) {\n unordered_set<int>st(freq[t].begin(),freq[t].end()); \n int sz=0; \n for(auto r:st){\n unordered_set<int>st2(freq2[r].begin(),freq2[r].end());\n if(st2.size()>1)continue;\n sz+=ds.size[r];\n }\n if(ans<sz){\n ans=sz;\n mini=t;\n }\n if(ans==sz){\n mini=min(t,mini);\n }\n }\n if (ans == -1e8) return *min_element(initial.begin(), initial.end());\n return mini;\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
minimize-malware-spread-ii
|
no recursion, simple queue solution
|
no-recursion-simple-queue-solution-by-ta-mkj5
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
tanishqj2005
|
NORMAL
|
2024-06-19T19:18:26.335904+00:00
|
2024-06-19T19:18:26.335926+00:00
| 11 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:\n \n n = len(graph)\n\n def dfs(used,l):\n \n ans = 0\n while len(l):\n # print(ans, l, used)\n a = l[0]\n ans += 1\n l.pop(0)\n for i in range(n):\n # print(i,graph[a][i],used[a])\n\n if graph[a][i] == 1 and used[i] == 0:\n used[i] = 1\n l.append(i)\n return ans\n \n ans = 500\n tempmax = 500\n\n for x in initial:\n used = [0 for _ in range(n)]\n used[x] = 1\n temp = 0\n for y in initial:\n if used[y] == 0:\n l = [y]\n used[y] = 1\n temp += dfs(used,l)\n # print(x,tempmax,temp)\n if temp < tempmax:\n tempmax = temp\n ans = x\n elif temp == tempmax:\n ans = min(ans,x)\n \n return ans\n\n```
| 0 | 0 |
['Python3']
| 0 |
minimize-malware-spread-ii
|
ap n^2
|
ap-n2-by-ap5123-c3oa
|
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
|
ap5123
|
NORMAL
|
2024-06-19T16:14:47.256101+00:00
|
2024-06-19T16:14:47.256135+00:00
| 2 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\nint k(int node,vector<int> adj[],vector<int>&ini,int n1)\n{\n vector<int> vis(n1,0);\n queue<int> q;\n for(auto i:ini)\n {\n if(i==node)continue;\n q.push(i);\n vis[i]=1;\n }\n vector<int> ans;\n while(!q.empty())\n {\n int n=q.front();\n q.pop();\n ans.push_back(n);\n for(auto i:adj[n])\n {\n if(i==node)continue;\n if(!vis[i])\n {\n vis[i]=1;\n q.push(i);\n }\n }\n }\n return ans.size();\n}\n int minMalwareSpread(vector<vector<int>>& graph, vector<int>& ini) {\n int n=graph.size();\n vector<int> adj[n];\n for(int i=0;i<n;i++)\n {\n for(int j=0;j<n;j++)\n {\n if(graph[i][j])\n {\n adj[i].push_back(j);\n }\n }\n }\n sort(ini.begin(),ini.end());\n int mini=k(ini[0],adj,ini,n);\n int ans=ini[0];\n for(int i=1;i<ini.size();i++)\n {\n if(k(ini[i],adj,ini,n)<mini)\n {\n mini=k(ini[i],adj,ini,n);\n ans=ini[i];\n }\n }\n return ans;\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
minimize-malware-spread-ii
|
C++ code using BFS
|
c-code-using-bfs-by-sting285-s49v
|
\n# Code\n\nclass Solution {\npublic:\n int getInfected(vector<int>adj[], vector<int>&initial, int ignore, int n){\n vector<int>arr(n, 0);\n qu
|
Sting285
|
NORMAL
|
2024-06-18T16:43:45.243036+00:00
|
2024-06-18T16:43:45.243065+00:00
| 10 | false |
\n# Code\n```\nclass Solution {\npublic:\n int getInfected(vector<int>adj[], vector<int>&initial, int ignore, int n){\n vector<int>arr(n, 0);\n queue<int>q;\n\n for(int i=0;i<initial.size();i++){\n if(initial[i] == ignore)\n continue;\n arr[initial[i]] = 1;\n q.push(initial[i]);\n }\n\n while(!q.empty()){\n int temp = q.front();\n q.pop();\n\n for(auto it: adj[temp]){\n if(it == ignore) continue;\n if(arr[it] == 0){\n arr[it] = 1;\n q.push(it);\n }\n }\n }\n\n int count = 0;\n for(auto it: arr){\n if(it == 1)\n ++count;\n }\n\n return count;\n }\n\n int minMalwareSpread(vector<vector<int>>& graph, vector<int>& initial) {\n int n = graph.size();\n vector<int>adj[n];\n\n sort(initial.begin(), initial.end());\n\n for(int i=0;i<n;i++){\n for(int j=0;j<n;j++){\n if(i == j) continue;\n if(graph[i][j] == 1){\n adj[i].push_back(j);\n adj[j].push_back(i);\n }\n }\n }\n\n int res = -1, resVal = INT_MAX;\n\n for(int i=0;i<initial.size();i++){\n int val = getInfected(adj, initial, initial[i], n);\n if(val < resVal){\n resVal = val;\n res = initial[i];\n }\n }\n\n return res;\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
minimize-malware-spread-ii
|
Java Union Find with Explanation
|
java-union-find-with-explanation-by-r_sl-e5ce
|
Intuition\nLoop through inital array and perform the following where each node in initial is removed one at a time:\n\nUnion find, finds a unique parent of ever
|
R_Slickerzzz
|
NORMAL
|
2024-06-15T08:56:58.624591+00:00
|
2024-06-15T08:56:58.624631+00:00
| 27 | false |
# Intuition\nLoop through inital array and perform the following where each node in initial is removed one at a time:\n\nUnion find, finds a unique parent of every node. If parent of a normal node is a parent of an infected node, it must be in the same disjoint set, hence it is infected. Place parents of infected nodes in a set. Check each node, if its parent is apart of set, it is infected. return index of the node that if removed minimises M.\n\n# Complexity\n- Time complexity:\nloops through initial array -> O(k)\n\nCreate union set, find() is log(n) -> O(E * log(n))\nloop through all nodes find parent (this call of find() is O(1) as the path has already been compressed) -> O(n)\n\ntotal: O(k(E * log(n) + n))\n\n# Code\n```\nclass Solution {\n public int minMalwareSpread(int[][] graph, int[] initial) {\n // storing minimiser and M value at minimiser\n int minimiser = -1;\n int min_val = Integer.MAX_VALUE;\n\n\n for (int i = 0; i < initial.length; i++) {\n\n // for given infected node find M value if it is removed\n int rem_val = singleInitRem(graph, initial, initial[i]);\n\n // second statement for finding lower node index on ties for M value\n if (rem_val < min_val || (rem_val == min_val && minimiser > initial[i])) {\n min_val = rem_val;\n minimiser = initial[i];\n }\n\n }\n return minimiser;\n }\n\n public int singleInitRem(int[][] graph, int[] init, int rem) {\n\n int n = graph.length;\n UF uf = new UF(n);\n\n // creating union find set, skip node (rem) that is removed\n for (int i = 0; i < n; i++) {\n for (int j = i + 1; j < n; j++) {\n if (i == rem || j == rem || graph[i][j] == 0) continue;\n \n uf.union(i, j);\n }\n }\n\n // finding parents of infected nodes, if any other node is connected\n // it is joint to an infected set\n HashSet<Integer> infected_parents = new HashSet<>();\n for (int i = 0; i < init.length; i++) {\n if (init[i] == rem) continue;\n\n infected_parents.add(uf.find(init[i]));\n }\n\n // finding infected nodes, skipping removed node\n int infected = 0;\n for (int i = 0; i < n; i++) {\n if (i == rem) continue;\n\n if (infected_parents.contains(uf.find(i))) infected++;\n }\n return infected;\n }\n\n // classical union find with compression (use rank based for better performance)\n public class UF {\n int n;\n int[] parent;\n\n public UF(int n) {\n parent = new int[n];\n for (int i = 0; i < n; i++) {\n parent[i] = i;\n }\n }\n\n public void union(int i, int j) {\n int par_j = find(j), par_i = find(i);\n parent[par_i] = par_j;\n }\n\n public int find(int i) {\n if (parent[i] == i) { \n return i; \n } \n parent[i] = find(parent[i]); \n return parent[i]; \n \n }\n\n }\n}\n```
| 0 | 0 |
['Java']
| 0 |
minimize-malware-spread-ii
|
Python Union/Find (Easy to Understand)
|
python-unionfind-easy-to-understand-by-a-2bit
|
\n# Approach\n1. Create disjoint set for non-infected nodes\n2. Find the groups where current malware node is infecting.\nTry to find the malware source count i
|
aarav26r
|
NORMAL
|
2024-06-10T11:33:19.247405+00:00
|
2024-06-10T11:33:19.247427+00:00
| 52 | false |
\n# Approach\n1. Create disjoint set for non-infected nodes\n2. Find the groups where current malware node is infecting.\nTry to find the malware source count in each group\n3. Now for each malware node, check if it will infect the connected\ngroup. To check, find whether the group has only one malware source.\nFind the safe nodes count.\n4. Return the one with max safe nodes count.\n\n# Code\n```\nclass DisjointSet:\n def __init__(self, n):\n self.parent = [i for i in range(n)]\n self.rank = [1 for i in range(n)]\n \n def get_parent(self, node):\n if node == self.parent[node]:\n return node\n self.parent[node] = self.get_parent(self.parent[node])\n return self.parent[node]\n\n def union(self, node1, node2):\n parent_1, parent_2 = self.get_parent(node1), self.get_parent(node2)\n if parent_1 == parent_2:\n return\n \n if self.rank[parent_1] >= self.rank[parent_2]:\n self.parent[parent_2] = parent_1\n self.rank[parent_1] += self.rank[parent_2]\n else:\n self.parent[parent_1] = parent_2\n self.rank[parent_2] += self.rank[parent_1]\n \n def get_component_size(self, node):\n return self.rank[self.get_parent(node)]\n\nclass Solution:\n def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:\n n = len(graph)\n infected_nodes = set(initial)\n disjoint_set = DisjointSet(n)\n for i in range(n):\n if i not in infected_nodes:\n for j in range(n):\n if graph[i][j] == 1 and j not in infected_nodes and i != j:\n disjoint_set.union(i, j)\n \n malware_group_infecting_map = defaultdict(set)\n group_malware_source_count = defaultdict(int)\n\n for node in infected_nodes:\n for i in range(n):\n if i != node and graph[node][i] == 1 and i not in infected_nodes:\n parent_node = disjoint_set.get_parent(i)\n if parent_node not in malware_group_infecting_map[node]:\n malware_group_infecting_map[node].add(parent_node)\n group_malware_source_count[parent_node] += 1\n \n max_safe_node_count = -1\n ans = -1\n for node in infected_nodes:\n safe_node_count = 0\n for parent_node in malware_group_infecting_map[node]:\n if group_malware_source_count[parent_node] == 1:\n safe_node_count += disjoint_set.get_component_size(parent_node)\n if safe_node_count > max_safe_node_count:\n max_safe_node_count = safe_node_count\n ans = node\n elif safe_node_count == max_safe_node_count:\n ans = min(ans, node)\n\n return ans\n\n\n \n```
| 0 | 0 |
['Union Find', 'Graph', 'Python3']
| 0 |
minimize-malware-spread-ii
|
bfs
|
bfs-by-johnchen-n26z
|
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
|
johnchen
|
NORMAL
|
2024-04-19T15:12:25.250920+00:00
|
2024-04-19T15:15:16.355153+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 {\npublic:\n int minMalwareSpread(vector<vector<int>>& graph, vector<int>& initial) {\n const int n = graph.size();\n sort(initial.begin(), initial.end());\n int res = 0;\n int cnt = n + 1;\n for (const int m: initial)\n {\n vector<vector<int>> gh(n);\n queue<int> q;\n vector<bool> visited(n);\n for (const int w: initial)\n {\n if (m == w)\n continue;\n q.push(w);\n visited[w] = true;\n }\n for (int i = 0; i < n; ++ i)\n {\n for (int j = 0; j < n; ++ j)\n {\n if (graph[i][j] == 1 && i != m && j != m)\n {\n gh[i].push_back(j);\n }\n }\n }\n const int count = minMalwareSpread(gh, q, visited);\n if (count < cnt)\n {\n res = m;\n cnt = count;\n }\n }\n return res;\n }\n int minMalwareSpread(const vector<vector<int>>& graph, queue<int>& q, vector<bool>& visited)\n { \n while (!q.empty())\n {\n const int n = q.size();\n for (int i = 0; i < n; ++ i)\n {\n const int node = q.front();\n q.pop();\n for (const int next: graph[node])\n {\n if (visited[next])\n continue;\n visited[next] = true;\n q.push(next);\n }\n }\n }\n return count(visited.cbegin(), visited.cend(), true); \n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
minimize-malware-spread-ii
|
Two Approaches one DFS and another Union Find | c++ | EASY to Understand
|
two-approaches-one-dfs-and-another-union-ye2q
|
Intuition\nFor a infected node do dfs traversal to get all infected nodes finally.\n\n# Approach\nFor each node in initial vector don\'t do dfs tarversal and
|
shekhar125
|
NORMAL
|
2024-04-11T18:36:10.293707+00:00
|
2024-04-11T18:36:10.293760+00:00
| 47 | false |
# Intuition\nFor a infected node do dfs traversal to get all infected nodes finally.\n\n# Approach\nFor each node in initial vector don\'t do dfs tarversal and do for other infected initial nodes so all the nodes which are in same component can marked as visited . So it means that all nodes which are marked as visited will get infected if this one infected node is removed.\n\n# Complexity\n- Time complexity:\n$$O(n*m)$$ N is for dfs Traversal and M is for traversing through initial vector and for each node in intial vector dfs function is called. \n\n- Space complexity:\n$$O(n^2)$$ It is for storing graph as adjacency list.\n\n\n# Code\n```\nvoid dfs(int node,vector<int>&vis, vector<vector<int>> &adj,int block)\n{\n vis[node]=1;\n for(auto it:adj[node])\n {\n if(vis[it]==0 && it!=block)\n {\n dfs(it,vis,adj,block);\n }\n }\n}\nclass Solution {\npublic:\n int minMalwareSpread(vector<vector<int>>& g, vector<int>& ini) {\n\n int n=g.size();\n int m=ini.size();\n vector<vector<int>> adj(n);\n for(int i=0;i<n;++i)\n {\n for(int j=0;j<n;++j)\n {\n if(g[i][j]==1)\n {\n adj[i].push_back(j);\n }\n }\n }\n sort(ini.begin(),ini.end());\n int ans;\n int mini=1e9;\n for(int k=0;k<m;++k)\n {\n\n vector<int> vis(n,0);\n for(int j=0;j<m;++j)\n {\n if(j!=k)\n {\n if(vis[ini[j]]==0)\n dfs(ini[j],vis,adj,ini[k]);\n }\n }\n int tot=0;\n for(int i=0;i<n;++i)\n {\n if(vis[i]==1) tot++;\n }\n\n if(mini>tot)\n {\n ans=ini[k];\n mini=tot;\n }\n\n }\n\n return ans;\n \n }\n};\n```\n\n# Intuition\nUnite all nodes which can be infected and then get all nodes which are infected by getting size of that component using union by size.\n\n\n# Complexity\n- Time complexity:\n$$O(n*n*m)$$ \n\n- Space complexity:\n$$O(n)$$ \n\n# Code\n```\nclass DSU{\n\n public:\n vector<int> p,si;\n\n DSU(int n)\n {\n p.resize(n+1);\n for(int i=0;i<=n;++i) p[i]=i;\n si.resize(n+1,1);\n }\n\n int fp(int n)\n {\n if(n==p[n]) return n;;\n\n return p[n]=fp(p[n]);\n }\n\n void union1(int u,int v)\n {\n int pu=fp(u);\n int pv=fp(v);\n\n if(pu==pv) return ;\n\n if(si[pu]>si[pv])\n {\n si[pu]+=si[pv];\n p[pv]=pu;\n }\n else\n {\n si[pv]+=si[pu];\n p[pu]=pv; \n }\n }\n};\n\nclass Solution {\npublic:\n int minMalwareSpread(vector<vector<int>>& g, vector<int>& ini) {\n\n int n=g.size();\n int m=ini.size();\n sort(ini.begin(),ini.end());\n int ans;\n int mini=1e9;\n for(int k=0;k<m;++k)\n {\n DSU ds(n);\n for(int i=0;i<n;++i)\n {\n for(int j=0;j<n;++j)\n {\n if(g[i][j]==1)\n {\n if(!(i==ini[k] || j==ini[k]))\n ds.union1(i,j);\n }\n }\n }\n \n set<int> s;\n for(int j=0;j<m;++j)\n {\n if(k!=j)\n {\n s.insert(ds.fp(ini[j]));\n }\n }\n\n int tot=0;\n for(auto it:s)\n {\n tot+=ds.si[it];\n }\n\n if(mini>tot)\n {\n ans=ini[k];\n mini=tot;\n }\n\n }\n\n return ans;\n \n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
minimize-malware-spread-ii
|
O(n^2) solution | Clean code with comments
|
on2-solution-clean-code-with-comments-by-rvca
|
Complexity\n- Time complexity: O(n^2)\n- Space complexity: O(n)\n\n# Code\n\nclass Solution {\n \n int[][] graph;\n\n \n private static final int ST
|
PawelWar
|
NORMAL
|
2024-03-23T18:07:14.654357+00:00
|
2024-03-23T18:08:01.146705+00:00
| 7 | false |
# Complexity\n- Time complexity: $$O(n^2)$$\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution {\n \n int[][] graph;\n\n \n private static final int STATUS_NOT_VISITED = 0;\n private static final int STATUS_VISITED = 1;\n private static final int STATUS_INITIALLY_INFECTED = 3;\n int[] nodesStatus;\n \n int[] initial;\n\n public int minMalwareSpread(int[][] graph, int[] initial) {\n this.graph = graph;\n this.initial = initial;\n this.nodesStatus = new int[graph.length];\n List<NodesGroup> groups = new ArrayList<>(); \n\n // iterate over initially infected nodes and mark them in "nodesStatus" structure\n // Time complexity: O(n)\n for (int infectedNode : initial) {\n nodesStatus[infectedNode] = STATUS_INITIALLY_INFECTED;\n }\n \n // iterate over graph and create groups\n // Time complexity: O(n^2)\n for (int nodeIndex = 0; nodeIndex < graph.length; nodeIndex++) {\n if (nodesStatus[nodeIndex] != STATUS_NOT_VISITED) {\n continue;\n }\n NodesGroup group = new NodesGroup();\n dfs(group, nodeIndex);\n groups.add(group);\n }\n \n // iterate over groups and check which one:\n // - can be saved by removing one infected node\n // - and remember how many nodes are saved by removing this node\n // Time complexity: O(n)\n int[] savedNodes = new int[graph.length];\n for (NodesGroup group : groups) {\n // important condition: we can save group which is connected with only one infected node\n if (group.infectedNeighbours.size() == 1) { \n savedNodes[group.getFirstInfectedNeighbour()] += group.healthyNodes.size();\n }\n }\n\n // We have structure "savedNodes" which aggregates how many nodes can be saved\n // Time complexity: O(n)\n Integer nodeThatShouldBeRemoved = getLowestInfectedNode(); // <- default value\n Integer numberOfNodesThatWillBeSaved = 0;\n for (int sn = 0; sn < savedNodes.length; sn++) {\n if (savedNodes[sn] > numberOfNodesThatWillBeSaved) {\n nodeThatShouldBeRemoved = sn;\n numberOfNodesThatWillBeSaved = savedNodes[sn];\n }\n }\n\n // You can uncomment this line to see how exactly this structure looks like\n // System.out.println("groups: " + groups);\n return nodeThatShouldBeRemoved;\n }\n\n private int getLowestInfectedNode() {\n int minIndex = initial[0];\n for (int i = 1; i < initial.length; i++) {\n minIndex = Math.min(minIndex, initial[i]);\n }\n return minIndex;\n }\n\n private void dfs(NodesGroup group, int nodeIndex) {\n if (nodesStatus[nodeIndex] == STATUS_NOT_VISITED) {\n group.healthyNodes.add(nodeIndex);\n nodesStatus[nodeIndex] = STATUS_VISITED; \n for (int ni = 0; ni < graph.length; ni++) {\n if (this.graph[nodeIndex][ni] == 1) {\n dfs(group, ni);\n }\n } \n } else if (nodesStatus[nodeIndex] == STATUS_INITIALLY_INFECTED) {\n group.infectedNeighbours.add(nodeIndex);\n } else {\n // the last possible option\n // nodesStatus[nodeIndex] == STATUS_VISITED so... it was already handled\n }\n }\n\n class NodesGroup {\n Set<Integer> healthyNodes = new HashSet<>();\n Set<Integer> infectedNeighbours = new HashSet<>();\n\n public Integer getFirstInfectedNeighbour() {\n return infectedNeighbours.iterator().next();\n }\n\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append("\\n");\n sb.append("hn: " + healthyNodes.toString());\n sb.append(" | ");\n sb.append("in: " + infectedNeighbours.toString());\n return sb.toString();\n } \n }\n}\n```
| 0 | 0 |
['Java']
| 0 |
minimize-malware-spread-ii
|
dfs
|
dfs-by-teddddddy-p8v8
|
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
|
teddddddy
|
NORMAL
|
2024-03-06T16:38:28.023230+00:00
|
2024-03-06T17:52:41.749190+00:00
| 24 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nfrom typing import List\n\nclass Solution:\n def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:\n # Initialize variables to keep track of the best node to remove and the result\n best = -1\n res = min(initial) # Start with the smallest infected node\n infected = set(initial) # Convert the initial list to a set for efficient lookups\n\n # DFS function to explore the graph from a given node\n def dfs(node, visited):\n if node in infected:\n return 0 # Return 0 if the node is infected\n visited.add(node) # Mark the node as visited\n counts = 1 # Start counting from the current node\n for i in range(len(graph[node])):\n if graph[node][i] == 1 and i not in visited: # If there\'s a connection and it\'s not visited\n count = dfs(i, visited) # Recursively explore the connected node\n if count == 0:\n infected.add(node) # If the exploration returns 0, it means a connected node is infected\n return 0\n counts += count\n return counts\n \n # Iterate over each initially infected node to simulate its removal\n for node in initial:\n visited = set([node]) # Initialize the visited set with the current node\n count = 0\n for i in range(len(graph)):\n if graph[node][i] == 1 and i not in visited:\n count += dfs(i, visited) # Explore connected nodes and add up the counts\n \n # If the current node leads to a higher count of non-infected nodes, update the result\n # Or if the count is the same but the node index is smaller, also update the result\n if count > best or (count == best and node < res):\n res = node\n best = count\n \n return res\n\n\n```
| 0 | 0 |
['Python3']
| 0 |
minimize-malware-spread-ii
|
Solution Minimize Malware Spread II
|
solution-minimize-malware-spread-ii-by-s-o2sb
|
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
|
Suyono-Sukorame
|
NORMAL
|
2024-03-05T09:47:10.350432+00:00
|
2024-03-05T09:47:10.350465+00:00
| 3 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public $vis = array();\n\n function dfs($v, $node, $nhi_dekhna, &$ans) {\n $this->vis[$node] = true;\n $ans++;\n foreach ($v[$node] as $x) {\n if (!$this->vis[$x] && $x != $nhi_dekhna) {\n $this->dfs($v, $x, $nhi_dekhna, $ans);\n }\n }\n }\n\n function minMalwareSpread($graph, $initial) {\n $n = count($graph);\n $v = array_fill(0, $n, array());\n \n for ($i = 0; $i < $n; $i++) {\n for ($j = 0; $j < $n; $j++) {\n if ($graph[$i][$j] == 1 && $i != $j) {\n $v[$i][] = $j;\n }\n }\n }\n \n sort($initial);\n $res = PHP_INT_MAX;\n $res1 = $initial[0];\n \n foreach ($initial as $x) {\n $ans = 0;\n $this->vis = array_fill(0, $n, false);\n foreach ($initial as $y) {\n if ($x != $y && !$this->vis[$y]) {\n $this->dfs($v, $y, $x, $ans);\n }\n }\n if ($ans < $res) {\n $res1 = $x;\n $res = $ans;\n }\n }\n \n return $res1;\n }\n}\n\n```
| 0 | 0 |
['PHP']
| 0 |
minimize-malware-spread-ii
|
BFS
|
bfs-by-ammar-amjad-m2mo
|
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
|
Ammar-Amjad
|
NORMAL
|
2024-02-25T21:07:34.655112+00:00
|
2024-02-25T21:07:34.655131+00:00
| 16 | 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```\nfrom collections import defaultdict, deque\n\nclass Solution:\n def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:\n initial_set = set(initial)\n initial = sorted(initial)\n\n adj_list = defaultdict(list)\n for i in range(len(graph)):\n for j in range(len(graph[0])):\n if i != j and graph[i][j] == 1:\n adj_list[i].append(j)\n \n \n def BFS(skip):\n queue = deque()\n\n for i in initial:\n if i != skip:\n queue.append(i)\n\n infection_count = 0\n seen = set()\n\n while queue:\n node = queue.popleft()\n\n for nei in adj_list[node]:\n if nei != skip:\n if nei not in seen:\n if nei not in initial_set:\n infection_count += 1\n queue.append(nei)\n seen.add(nei)\n\n return infection_count\n\n prev = float(\'inf\')\n idx = 0\n\n for i in initial:\n Curr_infections = BFS(i)\n \n\n if Curr_infections < prev:\n idx = i\n prev = Curr_infections\n \n return idx\n```
| 0 | 0 |
['Python3']
| 0 |
minimize-malware-spread-ii
|
Simple DFS || C++
|
simple-dfs-c-by-lotus18-jqus
|
Intuition\nRemove one infected node at a time and simulate the spread of malware. The one that gives the minimum M(initial) is the answer.\n# Code\n\nclass Solu
|
lotus18
|
NORMAL
|
2024-02-24T11:43:58.070412+00:00
|
2024-02-24T11:43:58.070431+00:00
| 14 | false |
# Intuition\nRemove one infected node at a time and simulate the spread of malware. The one that gives the minimum M(initial) is the answer.\n# Code\n```\nclass Solution \n{\npublic:\n void dfs(int node, vector<int> adj[], vector<int>& vis)\n {\n if(vis[node]) return;\n vis[node]=1;\n for(auto it: adj[node])\n {\n dfs(it,adj,vis);\n }\n }\n int minMalwareSpread(vector<vector<int>>& graph, vector<int>& initial) \n {\n int n=graph.size();\n int mn=400;\n int ans=-1;\n sort(initial.begin(),initial.end());\n for(auto i: initial)\n {\n vector<vector<int>> temp=graph;\n for(int x=0; x<n; x++) temp[x][i]=0;\n for(int y=0; y<n; y++) temp[i][y]=0;\n vector<int> adj[n];\n for(int x=0; x<n; x++)\n {\n for(int y=0; y<n; y++)\n {\n if(temp[x][y]) \n {\n adj[x].push_back(y);\n adj[y].push_back(x);\n }\n }\n }\n vector<int> vis(n,0);\n for(auto node: initial)\n {\n dfs(node,adj,vis);\n }\n int cnt=0;\n for(int x=0; x<n; x++)\n {\n if(vis[x]) cnt++;\n }\n if(cnt<mn)\n {\n mn=cnt;\n ans=i;\n }\n }\n return ans;\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
minimize-malware-spread-ii
|
BFS solution
|
bfs-solution-by-nuenuehao2-keoq
|
Intuition\n Describe your first thoughts on how to solve this problem. \nCalculate the total number of infected nodes for each node that we want to remove, and
|
nuenuehao2
|
NORMAL
|
2024-02-23T20:22:16.234323+00:00
|
2024-02-23T20:22:16.234346+00:00
| 13 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nCalculate the total number of infected nodes for each node that we want to remove, and get the minimum result.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n^3)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:\n n = len(graph)\n edges = defaultdict(list)\n for i in range(n):\n for j in range(n):\n if i != j and graph[i][j] == 1:\n edges[i].append(j)\n edges[j].append(i)\n initial.sort()\n\n def bfs(nodeToRemove):\n infected = set()\n for node in initial:\n if node != nodeToRemove:\n infected.add(node)\n queue = deque([node])\n while queue:\n curr = queue.popleft()\n for next in edges[curr]:\n if next not in infected and next != nodeToRemove:\n infected.add(next)\n queue.append(next)\n return len(infected)\n\n\n\n\n minInfection = n + 1\n candidate = None\n for node in initial:\n result = bfs(node)\n if result < minInfection:\n minInfection = result\n candidate = node\n return candidate\n\n```
| 0 | 0 |
['Python3']
| 0 |
minimize-malware-spread-ii
|
python dfs solution
|
python-dfs-solution-by-chengchao60827-85d7
|
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
|
chengchao60827
|
NORMAL
|
2024-02-22T01:27:46.194774+00:00
|
2024-02-22T01:27:46.194804+00:00
| 16 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:\n # brute force\n\n def dfs(graph: List[List[int]], initial: Set[int], infected_by: List[List[int]], initial_infected: int, current: int, visited: Set[int]) -> None:\n if current in visited:\n return\n\n if current in initial and current != initial_infected:\n return\n\n visited.add(current)\n if current != initial_infected:\n infected_by[current].append(initial_infected)\n\n for neighbor in range(len(graph[current])):\n if graph[current][neighbor] == 1 and current != neighbor:\n dfs(graph, initial, infected_by, initial_infected, neighbor, visited)\n\n\n initial = sorted(initial)\n initial_set = set(initial)\n n = len(graph)\n infected_by = [[] for _ in range(n)]\n for v in initial:\n visited = set()\n dfs(graph, initial_set, infected_by, v, v, visited)\n\n rst = [0 for _ in range(n)]\n for v in range(len(infected_by)):\n if len(infected_by[v]) == 1:\n rst[infected_by[v][0]] += 1\n\n max_uniquely_infected = 0\n rst_index = initial[0]\n for v in initial:\n if rst[v] > max_uniquely_infected:\n rst_index = v\n max_uniquely_infected = rst[v]\n\n return rst_index\n\n\n\n\n \n```
| 0 | 0 |
['Python3']
| 0 |
minimize-malware-spread-ii
|
Java Solution BFS
|
java-solution-bfs-by-ndsjqwbbb-oyby
|
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
|
ndsjqwbbb
|
NORMAL
|
2024-02-17T23:35:50.924592+00:00
|
2024-02-17T23:35:50.924622+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)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int minMalwareSpread(int[][] graph, int[] initial) {\n Map<Integer, List<Integer>> map = new HashMap<>();\n for(int i = 0; i < graph.length; i++){\n for(int j = i + 1; j < graph[0].length; j++){\n if(graph[i][j] == 1){\n map.putIfAbsent(i, new ArrayList<>());\n map.get(i).add(j);\n map.putIfAbsent(j, new ArrayList<>());\n map.get(j).add(i);\n }\n }\n }\n Map<Integer, List<Integer>> node_to_source = new HashMap<>();\n TreeSet<Integer> initials = new TreeSet<>();\n for(int i : initial){\n initials.add(i);\n }\n for(int start : initial){\n helper(start, node_to_source, map, initials);\n }\n Map<Integer, Integer> source_affect_node = new HashMap<>();\n for(Map.Entry<Integer, List<Integer>> entry : node_to_source.entrySet()){\n int node = entry.getKey();\n List<Integer> sources = entry.getValue();\n if(sources.size() == 1){\n int source = sources.get(0);\n source_affect_node.putIfAbsent(source, 0);\n source_affect_node.put(source, source_affect_node.get(source) + 1);\n }\n }\n int removed_source = -1;\n int count = -1;\n for(Map.Entry<Integer, Integer> entry : source_affect_node.entrySet()){\n int source = entry.getKey();\n int num_node_affected = entry.getValue();\n if(count < num_node_affected){\n removed_source = source;\n count = num_node_affected;\n }\n else if(count == num_node_affected && source < removed_source){\n removed_source = source;\n }\n }\n if(removed_source == -1){\n Arrays.sort(initial);\n return initial[0];\n }\n return removed_source;\n }\n private void helper(int start, Map<Integer, List<Integer>> node_to_source, Map<Integer, List<Integer>> map, TreeSet<Integer> initials){\n Queue<Pair<Integer, Integer>> queue = new ArrayDeque<>();\n Set<Integer> visited = new HashSet<>();\n queue.offer(new Pair<>(start, start));\n while(!queue.isEmpty()){\n Pair<Integer, Integer> current = queue.poll();\n int current_node = current.getKey();\n int source = current.getValue();\n List<Integer> neighbors = map.get(current_node);\n if(neighbors == null){\n continue;\n }\n for(int nei : neighbors){\n if(visited.add(nei) && !initials.contains(nei)){\n queue.offer(new Pair<>(nei, source));\n node_to_source.putIfAbsent(nei, new ArrayList<>());\n node_to_source.get(nei).add(source);\n }\n }\n }\n }\n}\n```
| 0 | 0 |
['Java']
| 0 |
minimize-malware-spread-ii
|
python3 bfs from every initial
|
python3-bfs-from-every-initial-by-0icy-2hqt
|
\n# Code\n\nclass Solution:\n def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:\n edges = defaultdict(list)\n init
|
0icy
|
NORMAL
|
2024-02-07T14:23:45.102980+00:00
|
2024-02-07T14:23:45.103012+00:00
| 17 | false |
\n# Code\n```\nclass Solution:\n def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:\n edges = defaultdict(list)\n initial.sort()\n for r in range(len(graph)):\n for c in range(len(graph)):\n if r == c:\n continue\n if graph[r][c]:\n edges[r].append(c)\n edges[c].append(r)\n\n node = inf\n final = inf\n for i in range(len(initial)):\n i = initial[i]\n visited = set([i])\n dfs = []\n for a in initial:\n if a not in visited:\n dfs.append(a)\n \n while dfs:\n k = dfs.pop()\n visited.add(k)\n for e in edges[k]:\n if e not in visited:\n visited.add(e)\n dfs.append(e)\n \n if len(visited)-1 < final:\n final = len(visited)-1\n node = i\n \n\n return node\n\n\n\n```
| 0 | 0 |
['Python3']
| 0 |
minimize-malware-spread-ii
|
Simple BFS Solution and Pass
|
simple-bfs-solution-and-pass-by-codingma-5kyq
|
Intuition\n Describe your first thoughts on how to solve this problem. \nBFS with each deleted initial values and see how many connected nodes in each connected
|
codingmaster123
|
NORMAL
|
2024-02-07T13:02:09.969366+00:00
|
2024-02-07T13:04:59.862680+00:00
| 9 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBFS with each deleted initial values and see how many connected nodes in each connected component from supposed deleted initial. Get the smallest connected component. If equal, then get the smallest index of deleted initial.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:\n # bfs\n\n def bfs(node): # bfs with each deleted value\n queue = deque(initial)\n visited = set()\n while queue:\n cur = queue.popleft()\n if cur == node or cur in visited: # ignore deleted initial\n continue\n \n visited.add(cur)\n # it will traverse the whole row of cur node\n for idx, value in enumerate(graph[cur]): \n if value == 1:\n queue.append(idx) \n return len(visited) # visited set is malware nodes caused by deleted initial\n\n min_value = float(\'inf\')\n connected_component = {}\n for node in initial:\n connected_component[node] = bfs(node)\n min_value = min(min_value, connected_component[node])\n\n res = []\n for k, v in connected_component.items():\n if v == min_value:\n res.append(k)\n return min(res)\n \n```
| 0 | 0 |
['Python3']
| 0 |
minimize-malware-spread-ii
|
TS Code
|
ts-code-by-gennadysx-lc3t
|
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
|
GennadySX
|
NORMAL
|
2024-01-28T11:43:05.192231+00:00
|
2024-01-28T11:43:05.192258+00:00
| 8 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nfunction minMalwareSpread(graph: number[][], initial: number[]): number {\n const n = graph.length;\n const infected = new Array(n).fill(false);\n function dfs(graph: number[][], u: number, visited: boolean[], infected: boolean[]): number {\n if (infected[u]) return 0;\n visited[u] = true;\n let count = 1;\n for (let v = 0; v < graph[u].length; v++) {\n if (!visited[v] && graph[u][v] === 1) {\n const c = dfs(graph, v, visited, infected);\n if (c === 0) {\n infected[u] = true;\n return 0;\n }\n count += c;\n }\n }\n return count;\n }\n \n for (const u of initial) {\n infected[u] = true;\n }\n let ans = initial[0], max = 0;\n for (const u of initial) {\n const visited = new Array(n).fill(false);\n visited[u] = true;\n let count = 0;\n for (let i = 0; i < n; i++) {\n if (!visited[i] && graph[u][i] === 1) {\n count += dfs(graph, i, visited, infected);\n }\n }\n if (count > max || count === max && u < ans) {\n max = count;\n ans = u;\n }\n }\n return ans;\n}\n```
| 0 | 0 |
['TypeScript', 'JavaScript']
| 0 |
minimize-malware-spread-ii
|
TS Code
|
ts-code-by-gennadysx-yfkd
|
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
|
GennadySX
|
NORMAL
|
2024-01-28T11:43:04.953795+00:00
|
2024-01-28T11:43:04.953820+00:00
| 2 | 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```\nfunction minMalwareSpread(graph: number[][], initial: number[]): number {\n const n = graph.length;\n const infected = new Array(n).fill(false);\n function dfs(graph: number[][], u: number, visited: boolean[], infected: boolean[]): number {\n if (infected[u]) return 0;\n visited[u] = true;\n let count = 1;\n for (let v = 0; v < graph[u].length; v++) {\n if (!visited[v] && graph[u][v] === 1) {\n const c = dfs(graph, v, visited, infected);\n if (c === 0) {\n infected[u] = true;\n return 0;\n }\n count += c;\n }\n }\n return count;\n }\n \n for (const u of initial) {\n infected[u] = true;\n }\n let ans = initial[0], max = 0;\n for (const u of initial) {\n const visited = new Array(n).fill(false);\n visited[u] = true;\n let count = 0;\n for (let i = 0; i < n; i++) {\n if (!visited[i] && graph[u][i] === 1) {\n count += dfs(graph, i, visited, infected);\n }\n }\n if (count > max || count === max && u < ans) {\n max = count;\n ans = u;\n }\n }\n return ans;\n}\n```
| 0 | 0 |
['TypeScript', 'JavaScript']
| 0 |
minimize-malware-spread-ii
|
Simple Iterative BFS Solution: O(k * n^2)
|
simple-iterative-bfs-solution-ok-n2-by-h-z5nr
|
Intuition\nRemoving a node is equivalent to skipping it in graph algorithms.\n\n# Approach\n\n- For each initial node that can be skipped:\n - Skip it and find
|
hthuwal
|
NORMAL
|
2024-01-26T07:28:31.786369+00:00
|
2024-01-26T10:05:22.204602+00:00
| 12 | false |
# Intuition\nRemoving a node is equivalent to skipping it in graph algorithms.\n\n# Approach\n\n- For each initial node that can be skipped:\n - Skip it and find the number of infected nodes:\n - Perform BFS starting from all initially infected nodes except the one to be skipped. \n - Note: BFS algorithm should skip the node as well.\n - Number of Infected nodes = Number of visited nodes \n - If Number of infected noes is minimum, this is the node we should skip.\n\nReturn the node skipping which yielded least number of infected nodes.\n\n\n# Complexity\n\n### Time Complexity\n\nLet k be the number of initially infected nodes, n be the total number of nodes.\n\nFor each initial node we perform BFS. \n\n= O(k) * O(V + E)\n= O(k) * O(n + n^2)\n= **O(k * n^2)**\n\n### Space complexity:\n\n- Create an adjacency list => O(n^2)\n- Visited Vector and queue for bfs => O(n) and O(n)\n\n= **O(n^2)**\n\n\n# Code\n```\nclass Solution {\n public:\n // Perfroms BFS starting from all initially infected nodes except the one to be skipped\n // BFS too skips the node to be skipped\n // Returns the total number of visited (infected) nodes\n // O(v + e) -> O(n^2)\n int totalInfected(vector<vector<int>>& adj_list, vector<int>& initial, int to_skip) {\n int n = adj_list.size();\n\n int num_visited_nodes = 0;\n vector<bool> visited(n, 0);\n\n // Pushes the node into queue, marks it as visited, and increases the number of visited nodes\n auto visit_node = [&](queue<int>& q, int node) {\n q.push(node);\n visited[node] = true;\n num_visited_nodes++;\n };\n\n // DO BFS starting from all initially infected, unvisted and not to be skipped nodes\n for (const int& start : initial) {\n if (start == to_skip || visited[start]) {\n continue;\n }\n\n queue<int> q;\n visit_node(q, start);\n while (!q.empty()) {\n int front = q.front();\n q.pop();\n for (const int& nbr : adj_list[front]) {\n if (nbr == to_skip) {\n continue;\n }\n\n if (!visited[nbr]) {\n visit_node(q, nbr);\n }\n }\n }\n }\n return num_visited_nodes;\n }\n\n int minMalwareSpread(vector<vector<int>>& graph, vector<int>& initial) {\n // Convert the graph from adj matrix to adj list (lower time complexity for sparse graphs)\n vector<vector<int>> adj_list(graph.size(), vector<int>());\n for (int i = 0; i < graph.size(); i++) {\n for (int j = 0; j < graph.size(); j++) {\n if (graph[i][j]) {\n adj_list[i].push_back(j);\n }\n }\n }\n\n // Iteratively skip each starting node and find how many nodes will be infected using bfs\n // Keep track of the minimum number of infected nodes and the node to be removed\n int node_to_be_removed = -1;\n int minimum_infection_so_far = graph.size() + 1;\n for (const int& skip_node : initial) {\n int infected_nodes = totalInfected(adj_list, initial, skip_node);\n\n if (infected_nodes < minimum_infection_so_far) {\n minimum_infection_so_far = infected_nodes;\n node_to_be_removed = skip_node;\n } else if (infected_nodes == minimum_infection_so_far && skip_node < node_to_be_removed) {\n node_to_be_removed = skip_node;\n }\n }\n return node_to_be_removed;\n }\n};\n```
| 0 | 0 |
['Breadth-First Search', 'C++']
| 0 |
minimize-malware-spread-ii
|
Java | Union Find | Explained
|
java-union-find-explained-by-prashant404-29a0
|
Approach Use Disjoint Set Union with Path compression\n\n>T/S: O(n\xB2)/O(n), where n = size(graph)\n\npublic int minMalwareSpread(int[][] graph, int[] initial)
|
prashant404
|
NORMAL
|
2023-11-01T07:14:18.510995+00:00
|
2023-11-01T07:14:18.511058+00:00
| 14 | false |
**Approach** Use Disjoint Set Union with Path compression\n\n>T/S: O(n\xB2)/O(n), where n = size(graph)\n```\npublic int minMalwareSpread(int[][] graph, int[] initial) {\n var maxSize = 0;\n var ans = -1;\n var n = graph.length;\n var parent = new int[n];\n var size = new int[n];\n var infected = new int[n];\n var initialSet = new HashSet<Integer>();\n var infectedToConnectedComponentsParents = new HashMap<Integer, Set<Integer>>();\n\n init(initial, initialSet, infectedToConnectedComponentsParents);\n Arrays.setAll(parent, i -> i);\n Arrays.fill(size, 1);\n\n // Create components without the infected nodes\n for (var i = 0; i < n; i++)\n for (var j = 0; j < n; j++)\n if (i != j && graph[i][j] == 1 && !initialSet.contains(i) && !initialSet.contains(j)) {\n\n var parentI = find(parent, i);\n var parentJ = find(parent, j);\n\n if (parentI != parentJ)\n union(size, parent, parentI, parentJ);\n }\n\n /*\n * Create a map of infected nodes (I) to parents of components which contain neighbors of I.\n * This is done to find out how many nodes we can save from getting infected if we delete I\n * This is also the reason we exclude counting any neighbor of I which itself is infected because deletion of I\n cannot save an originally infected node\n\n * Additionally, we also keep count of how many times a parent appears in different components.\n * If infected[parent = P] = 1, then it means P is part of only 1 component which has only 1 infected node\n * If infected[parent = P] > 1, then removing one infected node will not make any difference because there are\n * other infected nodes which can infect the whole component. Thus skip such components\n */\n for (var i : initial)\n for (var j = 0; j < n; j++)\n if (i != j && graph[i][j] == 1 && !initialSet.contains(j)) {\n var parentJ = find(parent, j);\n\n if (infectedToConnectedComponentsParents.get(i).add(parentJ))\n infected[parentJ]++;\n }\n\n /*\n * Now iterate through all infected nodes I\n * Then iterate through all disinfectable components that node-I effects and sum up their sizes (S). This is done to \n find out how many nodes can get disinfected if we remove I\n * Find max S among all sums and the corresponding I will be the answer\n * In case of a tie, choose min(I)\n * If no result is found, min(initial) is the answer \n */\n for (var i : initial) {\n var componentSize = 0;\n\n for (var head : infectedToConnectedComponentsParents.get(i))\n if (infected[head] == 1)\n componentSize += size[head];\n\n if (maxSize == componentSize) {\n ans = Math.min(ans, i);\n } else if (maxSize < componentSize) {\n ans = i;\n maxSize = componentSize;\n }\n }\n\n return ans == -1\n ? Arrays.stream(initial).min().getAsInt()\n : ans;\n}\n\nprivate void init(int[] initial, Set<Integer> set, Map<Integer, Set<Integer>> map) {\n for (var i : initial) {\n set.add(i);\n map.put(i, new HashSet<>());\n }\n}\n\nprivate int find(int[] parent, int i) {\n if (parent[i] == i)\n return i;\n return parent[i] = find(parent, parent[i]);\n}\n\nprivate void union(int[] size, int[] parent, int i, int j) {\n if (size[j] < size[i]) {\n parent[j] = i;\n size[i] += size[j];\n } else {\n parent[i] = j;\n size[j] += size[i];\n }\n}\n```\n***Please upvote if this helps***
| 0 | 0 |
['Java']
| 0 |
minimize-malware-spread-ii
|
Easy C++ DFS solution
|
easy-c-dfs-solution-by-ayushkumar135-ir8z
|
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
|
ayushkumar135
|
NORMAL
|
2023-10-24T12:09:35.819857+00:00
|
2023-10-24T12:09:35.819887+00:00
| 25 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int minMalwareSpread(vector<vector<int>>& graph, vector<int>& initial) {\n int n=graph.size();\n sort(initial.begin(),initial.end());\n vector<int> adj[n];\n for(int i=0;i<n;i++){\n for(int j=0;j<n;j++){\n if(graph[i][j]==1){\n adj[i].push_back(j);\n }\n }\n }\n int mini=INT_MAX;\n int ans=-1;\n for(int i=0;i<initial.size();i++){\n int cnt=0;\n vector<int> vis(n,0);\n queue<int> q;\n for(int j=0;j<initial.size();j++){\n if(j==i)continue;\n else{\n cnt++;\n vis[initial[j]]=1;\n q.push(initial[j]);\n }\n }\n while(!q.empty()){\n int node=q.front();\n q.pop();\n for(auto nbr:adj[node]){\n if(!vis[nbr] && nbr!=initial[i]){\n q.push(nbr);\n cnt++;\n vis[nbr]=1;\n }\n }\n }\n if(mini>cnt){\n mini=cnt;\n ans=initial[i];\n }\n }\n return ans;\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
minimize-malware-spread-ii
|
Easiest Solution
|
easiest-solution-by-kunal7216-xikq
|
\n\n# Code\njava []\nclass Solution {\n int[][] par;\n \n public int minMalwareSpread(int[][] graph, int[] initial) {\n \tint n = graph.length;\n
|
Kunal7216
|
NORMAL
|
2023-10-14T12:30:13.453815+00:00
|
2023-10-14T12:30:13.453838+00:00
| 17 | false |
\n\n# Code\n```java []\nclass Solution {\n int[][] par;\n \n public int minMalwareSpread(int[][] graph, int[] initial) {\n \tint n = graph.length;\n par = new int[n][2];\n for(int i = 0; i < par.length; i++){\n par[i][0] = i;\n par[i][1] = 1;\n }\n \n HashSet<Integer> set = new HashSet<>();\n for(int p : initial)\n \tset.add(p);\n \n for(int i = 0; i < n; i++) {\n \tfor(int j = i + 1; j < n; j++) {\n \t\tif(graph[i][j] == 1 && !set.contains(i) && !set.contains(j)) {\n \t\t\tint li = find(i);\n \t\t\tint lj = find(j);\n \t\t\tif(li != lj){\n par[li][0] = lj;\n par[lj][1] += par[li][1];\n }\n \t\t}\n \t}\n }\n \n HashMap<Integer, HashSet<Integer>> map = new HashMap<>();\n HashMap<Integer, HashSet<Integer>> conntoinf = new HashMap<>();\n \n for(int i : initial) {\n \tmap.put(i, new HashSet<>());\n \tfor(int j = 0; j < n; j++) {\n \t\tif(graph[i][j] == 1 && i != j && !set.contains(j)) {\n \t\t\tint lj = find(j);\n \t\t\tmap.get(i).add(lj);\n if(conntoinf.containsKey(lj) == false)\n conntoinf.put(lj, new HashSet<>());\n \t\t\tconntoinf.get(lj).add(i);\n \t\t}\n \t}\n }\n int ans = initial[0];\n int max = -1;\n \n for(int p : initial) {\n \tint val = 0;\n \tfor(int l : map.get(p)) {\n \t\tif(conntoinf.get(l).size() == 1)\n \t\t\tval += par[l][1];\n \t}\n if(val >= max) {\n if(val == max)\n ans = Math.min(p, ans);\n else\n ans = p;\n max = val;\n }\n }\n \n return ans;\n }\n \n public int find(int x){\n if(par[x][0] == x)\n return x;\n int temp = find(par[x][0]);\n return par[x][0] = temp;\n }\n}\n```\n```c++ []\nclass Solution {\npublic: \n void prepare(unordered_map<int, set<int>> &adj, vector<vector<int>>& graph)\n {\n int n = graph.size();\n for(int i = 0 ; i < n ; i++)\n {\n for(int j = 0 ; j < n ; j++)\n {\n if(i != j && graph[i][j] == 1)\n {\n adj[i].insert(j);\n adj[j].insert(i);\n }\n }\n }\n }\n void dfs(int node, unordered_map<int, set<int>> &adj, vector<int> &vis, int *cnt)\n {\n vis[node] = 1;\n *cnt = *cnt + 1;\n for(auto it: adj[node])\n {\n if(!vis[it])\n {\n dfs(it, adj, vis, cnt);\n }\n }\n }\n int minMalwareSpread(vector<vector<int>>& graph, vector<int>& initial) {\n int n = graph.size();\n unordered_map<int, set<int>> adj;\n prepare(adj, graph);\n\n// Logic: Try to remove each initial malicious node from graph and then call dfs for each other malicious node and count how many infected.(i,e. given by the total nodes reachable from thode rest initial nodes)\n// The one node on whose removal we have the least number of infected nodes is the answer.\n// To remove a node, just at initialization make its visited 1. So all it will never be called by dfs. (Good Trick)\n int ans = initial[0];\n int infected = INT_MAX;\n for(int i = 0 ; i < initial.size() ; i++)\n {\n vector<int> vis(n, 0);\n vis[initial[i]] = 1;\n int count_infected = 0;\n for(int j = 0 ; j < initial.size() ; j++)\n {\n if(!vis[initial[j]])\n {\n dfs(initial[j], adj, vis, &count_infected);\n }\n }\n if(count_infected < infected)\n {\n infected = count_infected;\n ans = initial[i];\n }\n else if(count_infected == infected)\n {\n ans = min(ans, initial[i]);\n }\n }\n return ans;\n }\n};\n```
| 0 | 0 |
['C++', 'Java']
| 0 |
minimize-malware-spread-ii
|
[Python] DFS Solution- O(n ^ 2) => The cost of adjacency matrix
|
python-dfs-solution-on-2-the-cost-of-adj-g2fq
|
Intuition\n Describe your first thoughts on how to solve this problem. \nWe need to count the nodes which are infected by only one initial node.\nSo traversal f
|
hanbro0112
|
NORMAL
|
2023-10-05T17:52:00.565525+00:00
|
2023-10-05T17:53:05.913619+00:00
| 34 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe need to count the nodes which are infected by **only one** initial node.\nSo traversal from the initial nodes and stop until it encounter another initial nodes or already visited nodes.\n<br>\nDFS would pass each node once, so the complexcity is every node pass its adjacency array from the adjacency matrix = O(n ^ 2).\n# Code\nRuntime 793 ms || 94.87%\nMemory 23.5 MB || 5.13%\n```\nclass Solution:\n def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:\n # O(n ^ 2) => the cost of adjacency matrix\n # Three types of node:\n # -1 -> not visit\n # i -> first pass by node i\n # [0 ~ n-1] -> another infected node\n n = len(graph)\n vis = [-1] * n\n for i in initial:\n vis[i] = i\n \n def dfs(node, cur):\n vis[node] = cur \n cnt = 1\n for i, v in enumerate(graph[node]):\n if not v: continue\n if vis[i] == -1:\n cnt += dfs(i, cur)\n elif vis[i] != cur:\n # The set is infected by another node\n vis[cur] = n\n return cnt\n \n ans = [-1, -1]\n for i in initial:\n count = 0\n for j, v in enumerate(graph[i]):\n if not v or vis[j] != -1: \n continue\n # reset\n vis[i] = i\n k = dfs(j, i)\n if vis[i] == i:\n count += k\n if count > ans[1]:\n ans = [i, count]\n if count == ans[1]:\n ans[0] = min(ans[0], i)\n\n return ans[0]\n```\nMemory optimization:\n\nRuntime: 787 ms || 96.15% \nMemory 18.8 MB || 96.15%\n```\nclass Solution:\n def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:\n # O(n ^ 2) => the cost of adjacency matrix\n # Three types of node:\n # -1 -> not visit\n # i -> first pass by node i\n # [0 ~ n-1] -> another infected node\n n = len(graph)\n vis = [-1] * n\n for i in initial:\n vis[i] = i\n \n ans = [-1, -1]\n for i in initial:\n count = 0\n for j, v in enumerate(graph[i]):\n if not v or vis[j] != -1: \n continue\n q = [j]\n vis[i] = vis[j] = i\n cnt = infected = 0\n while q:\n node = q.pop()\n cnt += 1\n for nxt, v in enumerate(graph[node]):\n if not v: continue\n if vis[nxt] == -1:\n q.append(nxt)\n vis[nxt] = i\n elif vis[nxt] != i:\n # The set is infected by another node\n infected = 1\n if not infected:\n count += cnt\n if count > ans[1]:\n ans = [i, count]\n if count == ans[1]:\n ans[0] = min(ans[0], i)\n\n return ans[0]\n```
| 0 | 0 |
['Depth-First Search', 'Python3']
| 0 |
minimize-malware-spread-ii
|
Python3 FT 90%, O(V+E) time and space: Union-Find and Cut/Articulation Point Detection
|
python3-ft-90-ove-time-and-space-union-f-hqjg
|
The Idea\n\nWe can use union-find to find infected clusters.\n if a cluster has one infected node, deleting it saves the whole cluster. So the reduction is size
|
biggestchungus
|
NORMAL
|
2023-09-23T01:55:20.111938+00:00
|
2023-09-23T01:55:20.111958+00:00
| 19 | false |
# The Idea\n\nWe can use union-find to find infected clusters.\n* if a cluster has one infected node, deleting it saves the whole cluster. So the reduction is size(component)\n* if a cluster has 2+ infected nodes, then we can still save some nodes if some of them are cut points (articulation points), and the new clusters created are full of only uninfected nodes\n\nUnion-find and finding cut/articulation points both run in O(V+E) time.\n\nSee the code for details and more explanation.\n\nIn a way this solution is more complicated than the union-find-merge-clusters solutions because you need to find articulation points. And that\'s a relatively advanced algorithm.\n\nBut on the other hand, that algorithm (`findCuts`) isn\'t too hard to code up once you know it.* And you benefit from a simpler explanation - the code very directly answers the question "if I deleted this infected node, would I create a new cluster(s) of uninfected nodes?"\n\n*be VERY careful of replacing `v` with `p`, etc. though!\n\n# Code\n```\nclass Solution:\n def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:\n debug = False\n\n # if we delete node u:\n # if u is not a cut point: reduction is componentSize if u is the only infected node, else 0\n # if u is a cut point: removing u isolates 1 or more child components from the rest of the graph\n # if the component that would be isolated has zero infected nodes, removing u saves all nodes\n # from infection. So we\'ll add those nodes to a running total for u\n # otherwise there is 1+ infected node, so eventually the whole component will become infected.\n # So no nodes in that component will be saved.\n\n # Finding cut points is a known DFS algo, onto which we can bolt on summing up clean and total node counts easily\n\n # So the steps are\n # 1. identify the connected components with union find\n # 2. for each connected component with an infected vertex: what infected vertices are in there\n # 3. scan over those infected components\n # a. if there\'s only one infected node, deleting it saves the whole cluster\n # b. if there are 2+, find cut points in the component. Then if an infected\n # vertex u is a cut point, then number of nodes saved is\n # i. clean nodes in "sub-components" that become isolated if we delete u\n # ii. plus 1 for the infected vertex we delete\n\n N = len(graph)\n\n ### (1) UNION-FIND\n p = [-1]*N # -size if root, else parent\n\n def getRoot(u: int) -> int:\n if p[u] < 0:\n return u\n\n p[u] = getRoot(p[u])\n return p[u]\n\n def union(u: int, v: int) -> None:\n ru = getRoot(u)\n rv = getRoot(v)\n\n if ru == rv:\n return\n\n # union smaller component into larger component\n if p[rv] < p[ru]:\n ru, rv = rv, ru\n\n p[ru] += p[rv]\n p[rv] = ru\n\n adj = defaultdict(list)\n for u in range(N):\n for v in range(u):\n if graph[u][v]:\n union(u, v)\n adj[u].append(v)\n adj[v].append(u)\n\n if debug: \n for i in range(N): \n js = list(j for j in adj[i])\n print(f"adj {i}: {js}")\n\n ### (2) FIND INFECTED COMPONENTS AND THEIR INFECTED VERTICES\n ccs = defaultdict(list) # infected CC root -> infected vertices\n for u in initial:\n ccs[getRoot(u)].append(u)\n\n ### (3) PROCESS EACH INFECTED COMPONENT\n time = [-1]*N\n lo = [-1]*N\n reductions = defaultdict(int) # infected index => the total reduction we get\n infset = set(initial)\n\n def findCuts(u: int, p: int, t: int, sz: int, ninf: int) -> tuple[int, int]:\n """\n Detects if u is a cut point. If so, and it isolates\n a cluster of all uninfected nodes from a cluster of infected nodes,\n then it increments reductions by that that number.\n\n Returns the number of clean and total nodes reachable from u without visiting p.\n\n Updates time and lo.\n """\n\n # This is a variation on identifying cut points, see https://cp-algorithms.com/graph/cutpoints.html,\n # modified to return node counts; the "plain vanilla" algo just identifies vertices that are\n # cut points.\n\n time[u] = t\n lo[u] = t\n total = 1\n clean = 0 if u in infset else 1\n for v in adj[u]:\n if v == p: continue\n \n if time[v] == -1:\n if debug: print(f" time[{u}] = {time[u]}, visiting {v} with time {t+1}")\n cl, ttl = findCuts(v, u, t+1, sz, ninf)\n if lo[v] >= time[u]:\n # deleting v isolates u and all reachable except via u-v\n if cl == ttl:\n reductions[u] += cl\n \n clean += cl\n total += ttl\n\n # regardless\n if lo[v] < lo[u]:\n if debug: print(f" {u}: non-parent(=={p}) neighbor {v} has lo[{v}] {lo[v]} < lo[{u}] {lo[u]}. Updating lo[{u}]")\n lo[u] = lo[v]\n\n # NOTE: we don\'t need this (and thus sz and numInf as params either) by always picking\n # an infected node as the root. this way the "ancestor cluster" and yet-unvisited\n # nodes will contain at least one infected node so we know that isolating them\n # won\'t reduce the solution (well yet-unvisited nodes might, but they\'ll be picked\n # up when visited later on)\n # (this was a bug I had to fix!!)\n # if lo[u] == time[u]:\n # # DFS from u never touched p and other ancestor nodes,\n # # so we include the "ancestor cluster" will all other nodes\n # cl = (sz - ninf) - clean\n # ttl = sz - total\n # if cl == ttl:\n # reductions[u] += cl\n\n if debug: print(f"node {u}: time[u] = {time[u]}, lo[u] = {lo[u]}, clean={clean}, total={total}, sz={sz}, numInf={numInf}")\n\n return clean, total\n\n bestReduction = 0\n bestVertex = min(initial)\n for r, inf in ccs.items():\n sz = -p[r]\n numInf = len(inf)\n if numInf == 1:\n u = inf[0]\n \n if sz > bestReduction or (sz == bestReduction and u < bestVertex):\n bestReduction = sz\n bestVertex = u\n\n if debug: print(f"iso: deleting {u} would reduce inf by {sz}")\n\n else:\n maxReductionPossible = sz - numInf + 1 # isolate all size(CC)-len(inf), plus 1 for deleting an infected node\n if maxReductionPossible < bestReduction: continue\n if maxReductionPossible == bestReduction and all(u > bestVertex for u in inf): continue # same reduction, but worse index\n\n # BUG FIX: start from an infected node\n # that way we don\'t have to handle the edge case where a cut point isolates all len(inf) infected\n # nodes from the "ancestor cluster" with only clean nodes\n if debug: print(f"finding cut points starting from {inf[0]}")\n findCuts(inf[0], -1, 0, sz, numInf)\n for u in inf:\n if reductions[u] + 1 > bestReduction or (reductions[u] + 1 == bestReduction and u < bestVertex):\n # +1 because we isolate all the clean nodes, and also delete an infected node\n bestReduction = reductions[u] + 1\n bestVertex = u\n\n if debug: print(f"cut: deleting {u} would reduce inf by {reductions[u] + 1}")\n\n return bestVertex\n```
| 0 | 0 |
['Python3']
| 0 |
minimize-malware-spread-ii
|
Easy DFS C++ Solution with explanation :)
|
easy-dfs-c-solution-with-explanation-by-02l8j
|
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
|
vinayag29
|
NORMAL
|
2023-09-16T10:42:51.556458+00:00
|
2023-09-16T10:42:51.556477+00:00
| 11 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic: \n void prepare(unordered_map<int, set<int>> &adj, vector<vector<int>>& graph)\n {\n int n = graph.size();\n for(int i = 0 ; i < n ; i++)\n {\n for(int j = 0 ; j < n ; j++)\n {\n if(i != j && graph[i][j] == 1)\n {\n adj[i].insert(j);\n adj[j].insert(i);\n }\n }\n }\n }\n void dfs(int node, unordered_map<int, set<int>> &adj, vector<int> &vis, int *cnt)\n {\n vis[node] = 1;\n *cnt = *cnt + 1;\n for(auto it: adj[node])\n {\n if(!vis[it])\n {\n dfs(it, adj, vis, cnt);\n }\n }\n }\n int minMalwareSpread(vector<vector<int>>& graph, vector<int>& initial) {\n int n = graph.size();\n unordered_map<int, set<int>> adj;\n prepare(adj, graph);\n\n// Logic: Try to remove each initial malicious node from graph and then call dfs for each other malicious node and count how many infected.(i,e. given by the total nodes reachable from thode rest initial nodes)\n// The one node on whose removal we have the least number of infected nodes is the answer.\n// To remove a node, just at initialization make its visited 1. So all it will never be called by dfs. (Good Trick)\n int ans = initial[0];\n int infected = INT_MAX;\n for(int i = 0 ; i < initial.size() ; i++)\n {\n vector<int> vis(n, 0);\n vis[initial[i]] = 1;\n int count_infected = 0;\n for(int j = 0 ; j < initial.size() ; j++)\n {\n if(!vis[initial[j]])\n {\n dfs(initial[j], adj, vis, &count_infected);\n }\n }\n if(count_infected < infected)\n {\n infected = count_infected;\n ans = initial[i];\n }\n else if(count_infected == infected)\n {\n ans = min(ans, initial[i]);\n }\n }\n return ans;\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
find-the-original-array-of-prefix-xor
|
[Java/C++/Python] Easy and Concise with Explantion
|
javacpython-easy-and-concise-with-explan-6f0g
|
Intuition\nDo this first:\nGiven pref, find arr that\npref[i] = arr[0] + arr[1] + ... + arr[i]\npref is prefix sum of arr\n\nThe solution is simple:\ncpp\nfor(i
|
lee215
|
NORMAL
|
2022-10-09T04:03:45.979653+00:00
|
2022-10-09T04:55:47.507138+00:00
| 10,376 | false |
# **Intuition**\nDo this first:\nGiven `pref`, find `arr` that\n`pref[i] = arr[0] + arr[1] + ... + arr[i]`\n`pref` is prefix sum of `arr`\n\nThe solution is simple:\n```cpp\nfor(int i = A.size() - 1; i > 0; --i)\n A[i] -= A[i - 1];\nreturn A;\n```\n\nNow we are doing something similar for this problem.\n<br>\n\n# **Explanation**\nSince `pref` is the prefix array,\nit\'s calculated from `arr` one by one,\nwe can doing this process reverssely to recover the original array.\n\nSince\n`pref[i] = pref[i-1] ^ A[i]`\nso we have\n`pref[i] ^ pref[i-1] = A[i]`\n\nSo we simply change `-` to `^` in the intuition solution\n\nThe reverse operation of `+` is `-`\nThe reverse operation of `^` is still `^`\nMore general, we can apply this solution to prefix of any operation.\n<br>\n\n# **Complexity**\nTime `O(n)`\nSpace `O(n)`\n<br>\n\n**Java**\n```java\n public int[] findArray(int[] A) {\n for (int i = A.length - 1; i > 0; --i)\n A[i] ^= A[i - 1];\n return A;\n }\n```\n**C++**\n```cpp\n vector<int> findArray(vector<int>& A) {\n for (int i = A.size() - 1; i > 0; --i)\n A[i] ^= A[i - 1];\n return A;\n }\n```\n**Python**\n```py\n def findArray(self, A):\n for i in range(len(A) - 1, 0, -1):\n A[i] ^= A[i - 1]\n return A\n```\n**Pythonic2**\n```py\n def findArray(self, A):\n return map(xor, A, [0] + A[:-1])\n```\n
| 112 | 0 |
['C', 'Python', 'Java']
| 23 |
find-the-original-array-of-prefix-xor
|
【Video】Give me 5 minutes - How we think about a solution - Python, JavaScript, Java, C++
|
video-give-me-5-minutes-how-we-think-abo-7v4m
|
Intuition\nThis is similar to prefix sum\n\n---\n\n# Solution Video\n\nhttps://youtu.be/ck4dJURKAlA\n\n\u25A0 Timeline of the video\n0:05 Solution code with bui
|
niits
|
NORMAL
|
2023-10-31T03:24:52.008378+00:00
|
2023-11-01T08:12:43.060772+00:00
| 3,831 | false |
# Intuition\nThis is similar to prefix sum\n\n---\n\n# Solution Video\n\nhttps://youtu.be/ck4dJURKAlA\n\n\u25A0 Timeline of the video\n`0:05` Solution code with build-in function\n`0:06` quick recap of XOR calculation\n`0:28` Demonstrate how to solve the question\n`1:37` How you keep the original previous number\n`2:29` Continue to demonstrate how to solve the question\n`3:59` Coding\n`4:43` Time Complexity and Space Complexity\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forget to subscribe to my channel! \u2B50\uFE0F\u2B50\uFE0F\n\n**\u25A0 Subscribe URL**\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\nSubscribers: 2,898\nMy initial goal is 10,000\nThank you for your support!\n\n---\n\n# Approach\n\n## How we think about a solution\n\nTo be honest, there is no complicated logic this time. This is similar to prefix sum, so we can calculate `XOR` with the input numbers one by one.\n\n```\nInput: pref = [5,2,0,3,1]\n```\n\n##### Quick recap of XOR caluclation\n---\nIf one of numbers is 1 and the other is 0 \u2192 1\nIf both numbers are 1 \u2192 0\nIf both numbers are 0 \u2192 0\n\n---\n\n\n\nFirst of all, we calculate `5`, but there is no previous number, so it is considered as `0`\n\n```\n101 (= 5)\n000 (= 0)\n---\n101 (= 5)\n\n```\nActually, we can start from `index 1` in real solution code, becuase the number at index 0 never change.\n\nMy solution starts from here. In the solution code, I update input array `pref` itself.\n```\nindex = 1\n\n010 (= 2)\n101 (= 5)\n---\n111 (= 7)\n\npref = [5, 7, 0, 3, 1]\n```\nBut problem is we need `2` for the next calculation, because `2` is the previous original number of intput array. How do you get `2`.\n\nIt\'s simple.\n```\n2 ^ 5 = 7 \n```\nThis is similar to \n```\n80 + 20 = 100\n\u2193\n80 = 100 - 20\n```\n```\n2 ^ 5 = 7 \n\u2193\n2 = 7 ^ 5\n\n111 (= 7)\n101 (= 5)\n---\n010 (= 2)\n\n```\n---\n\n\u2B50\uFE0F Points\n\nCalculate a previous number we need for the next calculation before we move the next iteration.\n```\n(next)prev = pref[i] ^ (current)prev\n\npref[i] is a current result\n```\n---\n\nWe use `prev` for the next calculation.\n```\nprev = 2\npref = [5, 7, 0, 3, 1]\n```\n```\nindex = 2\n\n000 (= 0 from input array)\n010 (= 2 from prev)\n---\n010 (= 2)\n\npref = [5, 7, 2, 3, 1]\nprev = 0 (= 2 ^ 2) \n```\n```\nindex = 3\n\n011 (= 3 from input array)\n000 (= 0 from prev)\n---\n011 (= 3)\n\npref = [5, 7, 2, 3, 1]\nprev = 3 (= 0 ^ 3) \n```\n\n```\nindex = 4\n\n001 (= 1 from input array)\n011 (= 3 from prev)\n---\n010 (= 2)\n\npref = [5, 7, 2, 3, 2]\nprev = 1 (= 3 ^ 2) \n```\n```\npref: [5,7,2,3,2] (Output)\n```\n\n---\n\n\n\n### Algorithm Overview:\nThe algorithm takes an input list `pref` of integers and transforms it in-place.\n\n### Detailed Explanation:\n1. Initialize a variable `prev` with the value of the first element in the `pref` list.\n2. Start a loop from the second element (index 1) to the last element of the `pref` list.\n3. Inside the loop, perform a bitwise XOR operation (`^`) between the current element at index `i` and the `prev` value. This replaces the current element with the XOR result.\n4. Update the `prev` value by performing a bitwise XOR operation between the previous `prev` value and the updated current element.\n5. Repeat steps 3-4 for all elements in the `pref` list.\n6. Return the modified `pref` list. The input list has been transformed in-place, with each element being XORed with the cumulative XOR of all previous elements.\n\n\n---\n\n\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\nIf we can update input array. My solution code updates it directly. But if we can\'t, space complexity should be $$O(n)$$ for result array. You need to ask interviewers about it in real interviews.\n\n\n```python []\nclass Solution:\n def findArray(self, pref: List[int]) -> List[int]:\n \n prev = pref[0]\n\n for i in range(1, len(pref)):\n pref[i] ^= prev\n prev ^= pref[i]\n \n return pref\n```\n```javascript []\n/**\n * @param {number[]} pref\n * @return {number[]}\n */\nvar findArray = function(pref) {\n let prev = pref[0];\n \n for (let i = 1; i < pref.length; i++) {\n pref[i] ^= prev;\n prev ^= pref[i];\n }\n \n return pref; \n};\n```\n```java []\nclass Solution {\n public int[] findArray(int[] pref) {\n int prev = pref[0];\n \n for (int i = 1; i < pref.length; i++) {\n pref[i] ^= prev;\n prev ^= pref[i];\n }\n \n return pref; \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n vector<int> findArray(vector<int>& pref) {\n int prev = pref[0];\n \n for (int i = 1; i < pref.size(); i++) {\n pref[i] ^= prev;\n prev ^= pref[i];\n }\n \n return pref; \n }\n};\n```\n\n---\n\nThank you for reading my post.\n\u2B50\uFE0F Please upvote it and don\'t forget to subscribe to my channel!\n\n\u25A0 Subscribe URL\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\n\u25A0 Twitter\nhttps://twitter.com/CodingNinjaAZ\n\n### My next daily coding challenge post and video.\n\npost\nhttps://leetcode.com/problems/find-mode-in-binary-search-tree/solutions/4233557/video-give-me-5-minutes-how-we-think-about-a-solution-why-do-we-use-inorder-traversal/\n\nvideo\nhttps://youtu.be/0i1Ze62pTuU\n\n\u25A0 Timeline of the video\n`0:04` Which traversal do you use for this question?\n`0:34` Properties of a Binary Search Tree\n`1:31` Key point of my solution code\n`3:09` How to write Inorder, Preorder, Postorder\n`4:08` Coding\n`7:13` Time Complexity and Space Complexity\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forget to subscribe to my channel! \u2B50\uFE0F\u2B50\uFE0F\n\n**\u25A0 Subscribe URL**\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\nSubscribers: 2,908\nMy initial goal is 10,000\nThank you for your support!\n\n\n### My previous daily coding challenge post and video.\n\npost\nhttps://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/solutions/4225041/video-give-me-10-minutes-using-heap-without-build-in-function-such-as-sort-or-bit-count/\n\nvideo\nhttps://youtu.be/oqV8Ai0_UWA\n\n\u25A0 Timeline\n`0:05` Solution code with build-in function\n`0:26` Two difficulties to solve the question\n`0:41` How do you count 1 bits?\n`1:05` Understanding to count 1 bits with an example\n`3:02` How do you keep numbers in ascending order when multiple numbers have the same number of 1 bits?\n`5:29` Coding\n`7:54` Time Complexity and Space Complexity
| 54 | 0 |
['C++', 'Java', 'Python3', 'JavaScript']
| 8 |
find-the-original-array-of-prefix-xor
|
✅ 92.93% One Line XORing
|
9293-one-line-xoring-by-vanamsen-tdtm
|
Intuition\nUpon reading the problem, the first thing that might come to mind is how the XOR operation behaves. Since the prefix XOR array is essentially an accu
|
vanAmsen
|
NORMAL
|
2023-10-31T00:13:10.399209+00:00
|
2023-10-31T02:02:59.219688+00:00
| 13,630 | false |
# Intuition\nUpon reading the problem, the first thing that might come to mind is how the XOR operation behaves. Since the prefix XOR array is essentially an accumulation of XOR operations, the inverse process would involve \'undoing\' the XOR operation. We remember that XOR has the following properties:\n\n1. $ a \\oplus a = 0 $\n2. $ a \\oplus 0 = a $\n3. XOR operation is both associative and commutative.\n\nThese properties hint towards the approach of using previous prefix values to deduce the current value.\n\n## Live Coding in Python & Go?\nhttps://youtu.be/nyRgqGYnAf4?si=8YeN7ukMB6uEdXSi\n\n# Approach\n1. The first observation is that the first element of the original array is equal to the first element of the prefix array. This is because there\'s no prior value to XOR with.\n2. For every subsequent element in the prefix array, we can obtain the corresponding element in the original array by XORing the current prefix value with the previous prefix value. This is derived from the properties of XOR, which allows us to \'cancel out\' values, essentially \'undoing\' the accumulation.\n\nUsing this approach, we iterate through the prefix array and populate our original array.\n\n# Complexity\n- Time complexity: $O(n)$\n - We iterate through the prefix array exactly once, resulting in a linear time complexity.\n\n- Space complexity: $O(n)$\n - We are creating a new list that has the same size as the input prefix array, resulting in a linear space complexity.\n\n# Code\n```python []\nclass Solution:\n def findArray(self, pref: List[int]) -> List[int]:\n return [pref[0]] + [pref[i] ^ pref[i-1] for i in range(1, len(pref))]\n```\n``` Java []\npublic class Solution {\n public int[] findArray(int[] pref) {\n int[] result = new int[pref.length];\n result[0] = pref[0];\n for(int i = 1; i < pref.length; i++) {\n result[i] = pref[i] ^ pref[i-1];\n }\n return result;\n }\n}\n```\n``` Go []\nfunc findArray(pref []int) []int {\n result := make([]int, len(pref))\n result[0] = pref[0]\n for i := 1; i < len(pref); i++ {\n result[i] = pref[i] ^ pref[i-1]\n }\n return result\n}\n```\n``` Rust []\nimpl Solution {\n pub fn find_array(pref: Vec<i32>) -> Vec<i32> {\n let mut result = Vec::with_capacity(pref.len());\n result.push(pref[0]);\n for i in 1..pref.len() {\n result.push(pref[i] ^ pref[i-1]);\n }\n result\n }\n}\n```\n``` C++ []\nclass Solution {\npublic:\n vector<int> findArray(vector<int>& pref) {\n vector<int> result(pref.size());\n result[0] = pref[0];\n for(int i = 1; i < pref.size(); i++) {\n result[i] = pref[i] ^ pref[i-1];\n }\n return result;\n }\n};\n```\n``` C# []\npublic class Solution {\n public int[] FindArray(int[] pref) {\n int[] result = new int[pref.Length];\n result[0] = pref[0];\n for(int i = 1; i < pref.Length; i++) {\n result[i] = pref[i] ^ pref[i-1];\n }\n return result;\n }\n}\n```\n``` JavaScript []\nvar findArray = function(pref) {\n let result = [pref[0]];\n for(let i = 1; i < pref.length; i++) {\n result.push(pref[i] ^ pref[i-1]);\n }\n return result;\n }\n```\n``` PHP []\nclass Solution {\n function findArray($pref) {\n $result = [];\n $result[] = $pref[0];\n for($i = 1; $i < count($pref); $i++) {\n $result[] = $pref[$i] ^ $pref[$i-1];\n }\n return $result;\n }\n}\n```\n\n---\n\n## Performance\n\n| Language | Execution Time (ms) | Memory Usage (MB) |\n|------------|---------------------|-------------------|\n| Java | 1 | 58.4 |\n| Rust | 39 | 3.5 |\n| Go | 85 | 9.6 |\n| C++ | 86 | 76.3 |\n| JavaScript | 184 | 71.2 |\n| C# | 243 | 60.2 |\n| PHP | 253 | 39.4 |\n| Python3 | 655 | 36.5 |\n\n\n\n\n## What We Have Learned?\n\nFrom this problem, we\'ve reinforced our understanding of the XOR operation and its properties, particularly how it can be used to deduce information from accumulated data. The solution is optimal because it utilizes the inherent properties of XOR to deduce the original values in a single pass through the prefix array. The approach is both space and time efficient, and showcases how sometimes, understanding the underlying mathematics or logic (in this case, bitwise operations) can lead to very efficient solutions.
| 45 | 13 |
['Array', 'Bit Manipulation', 'PHP', 'C++', 'Java', 'Go', 'Python3', 'Rust', 'JavaScript', 'C#']
| 9 |
find-the-original-array-of-prefix-xor
|
[Python3] if c=a^b then b=c^a beginner friendly!
|
python3-if-cab-then-bca-beginner-friendl-geti
|
The key to this problem is to know the reverse XOR!\nif c = a^b then a = c^b and b = c^a\nThen we can go through the pref, keep the XOR of all elements in res s
|
MeidaChen
|
NORMAL
|
2022-10-09T05:02:37.221372+00:00
|
2024-01-04T19:22:06.666387+00:00
| 1,739 | false |
The key to this problem is to know the reverse XOR!\nif `c = a^b` then `a = c^b` and `b = c^a`\nThen we can go through the `pref`, keep the XOR of all elements in `res` so far, and compute the next element in `res`, append it to `res`.\n```\nclass Solution:\n def findArray(self, pref: List[int]) -> List[int]:\n last = pref[0]\n res = [last] ### the first element in the result is the same as pref\n for n in pref[1:]:\n cur = n^last ### compute the current element in result\n res.append(cur) \n last ^= cur ### update the XOR of all elements in result so far\n return res\n```\n\n**Upvote** if you like this post.\n\n**Connect with me on [LinkedIn](https://www.linkedin.com/in/meida-chen-938a265b/)** if you\'d like to discuss other related topics\n\n\uD83C\uDF1F If you are interested in **Machine Learning** || **Deep Learning** || **Computer Vision** || **Computer Graphics** related projects and topics, check out my **[YouTube Channel](https://www.youtube.com/@meidachen8489)**! Subscribe for regular updates and be part of our growing community.
| 38 | 0 |
[]
| 4 |
find-the-original-array-of-prefix-xor
|
Reverse XOR
|
reverse-xor-by-votrubac-tgvh
|
\nC++\ncpp\nvector<int> findArray(vector<int>& pref) {\n for (int i = 0, prev = 0; i < pref.size(); ++i) {\n \xA0 \xA0 \xA0 \xA0pref[i] ^= prev;\n \xA0 \xA0
|
votrubac
|
NORMAL
|
2022-10-09T04:02:11.576811+00:00
|
2022-10-09T08:49:45.192418+00:00
| 1,816 | false |
\n**C++**\n```cpp\nvector<int> findArray(vector<int>& pref) {\n for (int i = 0, prev = 0; i < pref.size(); ++i) {\n \xA0 \xA0 \xA0 \xA0pref[i] ^= prev;\n \xA0 \xA0 \xA0 \xA0prev ^= pref[i];\n } \n return pref;\n}\n```
| 19 | 0 |
[]
| 8 |
find-the-original-array-of-prefix-xor
|
XOR is self-inverting & associative & commutative :)
|
xor-is-self-inverting-associative-commut-xnku
|
Java\njava\npublic int[] findArray(int[] pref) {\n int[] result = new int[pref.length];\n result[0] = pref[0];\n for (int i = 1; i < pref.l
|
FLlGHT
|
NORMAL
|
2022-10-09T06:58:14.795299+00:00
|
2022-10-09T07:40:06.102131+00:00
| 1,426 | false |
##### Java\n```java\npublic int[] findArray(int[] pref) {\n int[] result = new int[pref.length];\n result[0] = pref[0];\n for (int i = 1; i < pref.length; ++i) {\n result[i] = pref[i] ^ pref[i - 1];\n }\n \n return result;\n }\n```\n\n##### C++\n```cpp\npublic:\n vector<int> findArray(vector<int>& pref) {\n vector<int> result(pref.size());\n result[0] = pref[0];\n for (int i = 1; i < pref.size(); ++i) {\n result[i] = pref[i] ^ pref[i - 1];\n }\n\n return result;\n }\n```
| 16 | 0 |
['C', 'Java']
| 2 |
find-the-original-array-of-prefix-xor
|
✅C++ | ✅Simple Approach
|
c-simple-approach-by-yash2arma-jkvc
|
Please upvote if it helps :)\n\nLogic:\nif c = a^b then a = b^c\nso, ans[i] = ans[0]^ans[1]^...^ans[i-1]^pref[i]\n\nCode:\n\nclass Solution \n{\npublic:\n ve
|
Yash2arma
|
NORMAL
|
2022-10-09T04:00:39.775858+00:00
|
2022-10-09T04:48:02.233891+00:00
| 2,037 | false |
***Please upvote if it helps :)***\n\n**Logic:**\nif c = a^b then a = b^c\nso, ans[i] = ans[0]^ans[1]^...^ans[i-1]^pref[i]\n\n**Code:**\n```\nclass Solution \n{\npublic:\n vector<int> findArray(vector<int>& pref) \n {\n int n = pref.size();\n int pre_xor=0;\n \n for(int i=1; i<n; i++)\n {\n pre_xor ^= pref[i-1];\n pref[i] = pre_xor^pref[i];\n }\n return pref;\n }\n};\n```
| 16 | 1 |
['C', 'C++']
| 1 |
find-the-original-array-of-prefix-xor
|
🔥Beginner Friendly || Brute Force || Optimization Approach Both (Time And Space)
|
beginner-friendly-brute-force-optimizati-dvp7
|
Method : 1 BruteForce(Time Limit Exceed\n\n# Intuition\nThe code aims to generate a sequence of integers that, when XORed together, produces the given vector pr
|
gautam309
|
NORMAL
|
2023-10-31T07:56:53.442518+00:00
|
2023-10-31T16:48:59.550482+00:00
| 1,254 | false |
# Method : 1 BruteForce(Time Limit Exceed\n\n# Intuition\nThe code aims to generate a sequence of integers that, when XORed together, produces the given vector pref. It does this by iteratively finding the next integer for the sequence, starting with the first element of pref. The code uses a nested loop to incrementally test and identify the missing numbers in the sequence, adding them to the ans vector. While the approach is functional, the nested loop\'s high time complexity may result in inefficiency for larger inputs.\n\n# Complexity\n- Time complexity: O(n * 1000000000), where n is the size of the pref vector\n- Space complexity: The space complexity is O(n) as it stores the ans vector of the same size as pref\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> findArray(vector<int>& pref) \n {\n int n = pref.size() ;\n vector<int> ans ;\n \n ans.push_back(pref[0]) ;\n int temp = pref[0] ;\n\n for(int i = 1 ; i < n ; i++)\n {\n for(int num = 0 ; num <= 1000000000 ; num++)\n {\n if( (temp^num) == pref[i])\n {\n ans.push_back(num) ;\n temp = temp^num ;\n break ;\n } \n }\n }\n return ans ; \n }\n};\n```\n---\n# Method : 2 Time Optimization(accepted) \n\n# Intuition\nThe intuition behind this code is to perform a sequence of XOR operations on the input vector pref to generate the output vector ans. Each element of the output vector is formed by XORing the corresponding element in the input vector with the previous element in the input vector. \n\nThe provided image illustrates a problem-solving approach that is based on visual cues\n\n\n\n\n# Approach\n1. The loop starts from i = 1 and continues until i is less than the size of pref.\n2. In each iteration, it calculates the XOR of the current element pref[i-1] and the previous element pref[i-1], and appends the result to ans.\n3. Finally, it returns the ans vector as the result.\n\n# Complexity\n- Time complexity: O(n), where n is the size of the pref vector,\n- Space complexity: The space complexity is O(n) as well because it creates a new vector ans of the same size as pref\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> findArray(vector<int>& pref) \n {\n int n = pref.size() ;\n vector<int> ans ;\n \n ans.push_back(pref[0]) ;\n\n for(int i = 1 ; i < n ; i++)\n ans.push_back(pref[i-1]^pref[i]) ;\n\n return ans ; \n }\n};\n```\n---\n# Method : 3 Time and Space Optimization(accepted) \n\n# Intuition\n1. It initializes n as the size of the input vector pref.\n2. The code then iterates through the elements of pref in reverse order (from the last element to the second element).\n3. In each iteration, it calculates the XOR of the current element pref[i] with the previous element pref[i-1] and updates \n the current element with the result.\n4. The code returns the modified pref vector after all iterations.\n\n# Complexity\n- Time complexity: O(n)\n- Space complexity: O(1)\n# Code\n```\nclass Solution {\npublic:\n vector<int> findArray(vector<int>& pref) \n {\n int n = pref.size() ;\n \n for(int i = n-1 ; i > 0 ; i--)\n pref[i] = pref[i]^pref[i-1] ;\n\n return pref ; \n }\n};\n```\n\n** If you find it helpful, your upvote would be greatly appreciated. It provides valuable support to me. Thank you**
| 15 | 0 |
['Bit Manipulation', 'C++']
| 0 |
find-the-original-array-of-prefix-xor
|
python3 easy code
|
python3-easy-code-by-hakkiot-2rc0
|
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# Code\n\nclass Solut
|
hakkiot
|
NORMAL
|
2023-06-20T15:16:51.671189+00:00
|
2023-06-20T15:16:51.671206+00:00
| 649 | 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# Code\n```\nclass Solution:\n def findArray(self, pref: List[int]) -> List[int]:\n if len(pref)==1:\n return pref\n ans=[pref[0]]\n for i in range(len(pref)-1):\n ans.append(pref[i]^pref[i+1])\n return ans\n```
| 14 | 0 |
['Python3']
| 3 |
find-the-original-array-of-prefix-xor
|
✅ Easiest Possible Approach ✅ Bit Manipulation ✅ Fastest Too
|
easiest-possible-approach-bit-manipulati-e511
|
\n\n\n# YouTube Video Explanation:\n\nhttps://youtu.be/eNT1d-tB68k\n\n\uD83D\uDD25 Please like, share, and subscribe to support our channel\'s mission of making
|
millenium103
|
NORMAL
|
2023-10-31T02:31:58.293778+00:00
|
2023-10-31T02:31:58.293806+00:00
| 2,050 | false |
\n\n\n# YouTube Video Explanation:\n\n[https://youtu.be/eNT1d-tB68k](https://youtu.be/eNT1d-tB68k)\n\n**\uD83D\uDD25 Please like, share, and subscribe to support our channel\'s mission of making complex concepts easy to understand.**\n\nSubscribe Link: https://www.youtube.com/@leetlogics/?sub_confirmation=1\n\n*Subscribe Goal: 200 Subscribers*\n*Current Subscribers: 165*\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem essentially asks us to find the missing element in the `arr` array given the `pref` array. The `^` operator denotes the bitwise-xor operation. To find the missing element, we can apply the xor operation to the prefix array elements. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Create an integer array `result` of the same size as `pref`.\n2. Initialize the first element of `result` as `pref[0]` because `arr[0] = pref[0]`.\n3. Iterate through the `pref` array from index 1 to the end.\n4. For each element at index `i`, calculate `result[i]` as the xor of `pref[i]` and `result[i-1]` (the previously calculated element in the `result` array).\n5. Return the `result` array, which represents the `arr` array.\n\n# Complexity\n- Time Complexity: `O(n)` - We iterate through the `pref` array once, and each operation is constant time.\n- Space Complexity: `O(n)` - We use additional space to store the `result` array.\n\n# Code\n### Java\n```\nclass Solution {\n public int[] findArray(int[] pref) {\n int[] result = new int[pref.length];\n result[0] = pref[0];\n\n for(int i=1;i<pref.length;i++)\n {\n result[i] = pref[i] ^ pref[i-1];\n }\n\n return result;\n }\n}\n```\n\n### C++\n```\nclass Solution {\npublic:\n vector<int> findArray(vector<int>& pref) {\n int n = pref.size();\n vector<int> result(n);\n result[0] = pref[0];\n\n for (int i = 1; i < n; i++) {\n result[i] = pref[i] ^ pref[i - 1];\n }\n\n return result;\n }\n};\n```\n\n### Python\n```\nclass Solution(object):\n def findArray(self, pref):\n n = len(pref)\n result = [0] * n\n result[0] = pref[0]\n\n for i in range(1, n):\n result[i] = pref[i] ^ pref[i - 1]\n\n return result\n \n```\n\n### Javascript\n```\nvar findArray = function(pref) {\n const n = pref.length;\n const result = new Array(n);\n result[0] = pref[0];\n\n for (let i = 1; i < n; i++) {\n result[i] = pref[i] ^ pref[i - 1];\n }\n\n return result;\n};\n```\n---\n\n\n
| 13 | 2 |
['Array', 'Bit Manipulation', 'Python', 'C++', 'Java', 'JavaScript']
| 4 |
find-the-original-array-of-prefix-xor
|
Original Array profix xor | Explanation
|
original-array-profix-xor-explanation-by-v4t7
|
Hi,\n\nUnderstanding my solution is as follows:\n\npref[i] = pref[i-1] ^ res[i];\n\nso we have to find the value of \'res[i]\', so we move the xor operation to
|
Surendaar
|
NORMAL
|
2022-10-09T04:17:00.410101+00:00
|
2022-10-09T04:18:35.393150+00:00
| 711 | false |
Hi,\n\nUnderstanding my solution is as follows:\n\n**pref[i] = pref[i-1] ^ res[i];**\n\nso we have to find the value of \'res[i]\', so we move the xor operation to the other side:\n\n**res[i] = pref[i] ^ pref[i-1];**\n\nWhen i=0 the xor res value will be same as given array.\n\nHappy learning, kindly upvote if helps:\n\n```\n public int[] findArray(int[] pref) {\n int res[] = new int[pref.length];\n res[0]=pref[0];\n for(int i=1; i<pref.length; i++){\n \tres[i]=pref[i]^pref[i-1];\n }\n return res;\n }
| 11 | 0 |
['Java']
| 2 |
find-the-original-array-of-prefix-xor
|
Easy C++ Solution (Bit manipulation- Easy Method)
|
easy-c-solution-bit-manipulation-easy-me-3geh
|
Intuition\nInitialize an empty vector v to store the elements of the arr.\n\nInitialize first to 0. This variable represents the cumulative XOR of elements in a
|
ganeshdarshan18
|
NORMAL
|
2023-10-31T16:45:50.912351+00:00
|
2023-10-31T16:47:42.187930+00:00
| 66 | false |
# Intuition\nInitialize an empty vector v to store the elements of the arr.\n\nInitialize first to 0. This variable represents the cumulative XOR of elements in arr from index 0 to the current index, and it starts with 0 since there are no elements in arr initially.\n\nIterate through the elements of pref using a loop. For each element x in pref:\n\nCompute temp as the XOR of x and the current value of first. This represents the value of arr[i] at the current index.\nPush temp onto the v vector.\nUpdate the first value by performing an XOR between the current first and temp. This updates the cumulative XOR value.\nAfter the loop, v will contain the elements of arr, and you can return it as the result.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n\n\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n)$$\n The code iterates through each element in the pref array exactly once, performing constant-time operations within the loop (XOR and vector operations). Therefore, the time complexity is $$O(n)$$, where n is the size of the pref array.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: \n The code uses a vector v to store the elements of arr, which has the same size as the pref array. Therefore, the space complexity is $$O(n)$$, where n is the size of the pref array. The additional space complexity is $$O(1)$$ for other variables used in the solution.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Please Upvote if you find useful :)\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> findArray(vector<int>& pref) {\n vector <int> v ;\n int first = 0;\n int temp ;\n for(auto x:pref){\n temp = x ^ first;\n v.push_back(temp);\n first = first^temp ;\n }\n return v ;\n }\n};\n```
| 10 | 0 |
['Math', 'Bit Manipulation', 'C', 'C++']
| 0 |
find-the-original-array-of-prefix-xor
|
JAVA|| 1 LINER CODE || 100 % FASTER || 2 APPROACH EXPLAINED
|
java-1-liner-code-100-faster-2-approach-ca0od
|
PLEASE UPVOTE IF YOU LIKE THIS\n\n# Code\n\nFirst Approach:\n\nTime complexity : O(N);\nSpace complexity: O(N);\n\nclass Solution {\n public int[] findArray(
|
sharforaz_rahman
|
NORMAL
|
2023-03-13T07:29:34.515745+00:00
|
2023-03-14T04:15:12.321810+00:00
| 609 | false |
**PLEASE UPVOTE IF YOU LIKE THIS**\n\n# Code\n```\nFirst Approach:\n\nTime complexity : O(N);\nSpace complexity: O(N);\n\nclass Solution {\n public int[] findArray(int[] pref) {\n int[] res = new int[pref.length];\n for (int i = 0, j = 1; i < pref.length - 1; i++, j++) {\n int storeValue = pref[j];\n res[j] = pref[i] ^ pref[j];\n }\n res[0] = pref[0];\n return res;\n }\n}\n```\n```\nSecond Approach:\n\nTime complexity : O(N);\nSpace complexity: O(1);\n\npublic static int[] findArray(int[] pref) {\n for(int i = pref.length - 1; i > 0; i--) pref[i] = pref[i] ^ pref[i-1];\n return pref;\n }\n```
| 10 | 0 |
['Java']
| 3 |
find-the-original-array-of-prefix-xor
|
C++ xor||59ms Beats 99.71%
|
c-xor59ms-beats-9971-by-anwendeng-29av
|
Intuition\n Describe your first thoughts on how to solve this problem. \nBased on the formula:\n\nx ^y= z\n=> (x^y)^y =z^y \n=> x^(y^y)=z^y (associative)\n=> x^
|
anwendeng
|
NORMAL
|
2023-10-31T04:37:31.131373+00:00
|
2023-10-31T10:11:23.955576+00:00
| 1,169 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBased on the formula:\n```\nx ^y= z\n=> (x^y)^y =z^y \n=> x^(y^y)=z^y (associative)\n=> x^0=z^y\n=> x=z^y\n```\nSame as modulo 2 addition!\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThis for-loop implements the XOR computation.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n# Code\n```\n#pragma GCC optimize("O3")\nclass Solution {\npublic:\n vector<int> findArray(vector<int>& pref) {\n int n=pref.size();\n vector<int> ans(n);\n ans[0]=pref[0];\n for(int i=1; i<n; i++)\n ans[i]=pref[i-1]^pref[i];\n return ans;\n }\n};\nauto init = []()\n{ \n ios::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n return \'c\';\n}();\n```
| 7 | 0 |
['Array', 'Bit Manipulation', 'C++']
| 2 |
find-the-original-array-of-prefix-xor
|
Prefix XOR
|
prefix-xor-by-ayushy_78-f8hb
|
Intuition\nTo compute the current element we need the prefix xor of previous elements.\norig[i] = prefix[i - 1] xor prefix[i]\n Describe your first thoughts on
|
SelfHelp
|
NORMAL
|
2022-10-09T12:05:01.724142+00:00
|
2022-10-09T13:28:06.728761+00:00
| 481 | false |
# Intuition\nTo compute the current element we need the prefix `xor` of previous elements.\n`orig[i] = prefix[i - 1] xor prefix[i]`\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nWe maintian a variable `x` which is the prefix xor of all the elements before it.\n\nAfter the operation the resultant array will be the original array.\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```\nclass Solution {\npublic:\n vector<int> findArray(vector<int>& pref) {\n int x = pref[0], n = pref.size();\n for(int i = 1; i < n; i++) {\n pref[i] = x ^ pref[i];\n x ^= pref[i];\n }\n return pref;\n }\n};\n```
| 7 | 0 |
['Array', 'Prefix Sum', 'C++']
| 2 |
find-the-original-array-of-prefix-xor
|
C++ | Simple Approach | 5 Lines of Code | Explained
|
c-simple-approach-5-lines-of-code-explai-wgp3
|
Idea : If you see test cases resultant array is just xor of pref[i] and pref[i-1] \nAlso remember XOR operator follows associativity \n\npush_back(pref[0]);\nth
|
PModhe_09
|
NORMAL
|
2022-10-09T04:05:38.915620+00:00
|
2022-10-09T04:42:46.887517+00:00
| 658 | false |
Idea : If you see test cases resultant array is just xor of pref[i] and pref[i-1] \nAlso remember XOR operator follows associativity \n\npush_back(pref[0]);\nthen res[i] is xor of all elements upto ith element\n```\nclass Solution {\npublic:\n vector<int> findArray(vector<int>& pref) {\n vector<int> res; // this will be our result array\n res.push_back(pref[0]);\n \n for(int i=1;i<pref.size();i++){\n res.push_back(pref[i] xor pref[i-1]);\n }\n \n return res;\n }\n};\n```
| 7 | 0 |
['C', 'C++']
| 3 |
find-the-original-array-of-prefix-xor
|
Easiest Solution [ Java ] [ 88.64% ] [ 2ms ]
|
easiest-solution-java-8864-2ms-by-rajars-5egx
|
Approach\n1. Initialization:\n - Create a new integer array arr with the same length as the input prefix XOR array pref.\n - Set the first element of arr to
|
RajarshiMitra
|
NORMAL
|
2024-06-02T06:13:07.245209+00:00
|
2024-06-16T06:31:59.055722+00:00
| 29 | false |
# Approach\n1. **Initialization**:\n - Create a new integer array `arr` with the same length as the input prefix XOR array `pref`.\n - Set the first element of `arr` to be the same as the first element of `pref`.\n\n2. **Iterate Through the Prefix XOR Array**:\n - Start a loop from the second element (index 1) to the last element of the `pref` array.\n - For each element at index `i` in `pref`:\n - Calculate the current element of the original array by XORing the current element of `pref` (`pref[i]`) with the previous element of `pref` (`pref[i-1]`).\n - Assign this calculated value to the corresponding index in the `arr` array.\n\n3. **Return the Result**:\n - After the loop completes, return the `arr` array which now contains the original array.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution {\n public int[] findArray(int[] pref) {\n int arr[]=new int[pref.length];\n arr[0]=pref[0];\n for(int i=1; i<pref.length; i++){\n int ele=pref[i]^pref[i-1];\n arr[i]=ele;\n }\n return arr;\n }\n}\n```\n\n\n\n
| 6 | 0 |
['Java']
| 0 |
find-the-original-array-of-prefix-xor
|
Python List Comprehension -- One Line Solution 🔥
|
python-list-comprehension-one-line-solut-obwa
|
Intuition\nThe problem requires us to find an array "arr" such that pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i].\nWe can observe that pref[i] can be calculated as
|
Nitish_kr01
|
NORMAL
|
2023-10-31T05:38:42.250365+00:00
|
2023-10-31T05:38:42.250393+00:00
| 279 | false |
# Intuition\nThe problem requires us to find an array "arr" such that pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i].\nWe can observe that pref[i] can be calculated as follows:\npref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i]\npref[i-1] = arr[0] ^ arr[1] ^ ... ^ arr[i-1]\npref[i] ^ pref[i-1] = (arr[0] ^ arr[1] ^ ... ^ arr[i]) ^ (arr[0] ^ arr[1] ^ ... ^ arr[i-1])\nIf we simplify the XOR operation, we get arr[i] = pref[i] ^ pref [i-1].\n# Approach\nWe can use the above observation to find the elements of the array "arr" by iterating through the "pref" array.\nInitialize an empty list "arr".\nFor the first element of "arr", add pref[0].\nThen, iterate from i = 1 to len(pref) - 1, and for each i, calculate arr[i] as pref[i] ^ pref[i-1] and append it to "arr".\nReturn the "arr" as the result.\n# Complexity\n- Time complexity:\n O(n)\n\n- Space complexity:\n O(n)\n\n# Code\n```\nclass Solution:\n def findArray(self, pref: List[int]) -> List[int]:\n return [pref[0]]+[(pref[i-1]^pref[i]) for i in range(1,len(pref))]\n```
| 6 | 0 |
['Python3']
| 3 |
find-the-original-array-of-prefix-xor
|
Beats 100% | Easy To Understand | 3 Lines of Code 🚀🚀
|
beats-100-easy-to-understand-3-lines-of-yteg0
|
Intuition\n\n\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- T
|
The_Eternal_Soul
|
NORMAL
|
2023-10-31T01:23:54.393652+00:00
|
2023-10-31T01:23:54.393676+00:00
| 1,647 | false |
# Intuition\n\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> findArray(vector<int>& pref) {\n ios_base::sync_with_stdio(false);\n cin.tie(0);\n cout.tie(0);\n\n int n = pref.size();\n for(int i = n - 1; i >= 1; i--)\n {\n pref[i] = (pref[i] ^ pref[i-1]);\n }\n return pref;\n }\n};\n```
| 6 | 1 |
['Array', 'Bit Manipulation', 'C', 'Python', 'C++', 'Java', 'Python3', 'JavaScript']
| 6 |
find-the-original-array-of-prefix-xor
|
C++ || in-place re-write from the back || fast 100% (98ms)
|
c-in-place-re-write-from-the-back-fast-1-gjmt
|
Approach 1: in-place re-write from the back\n\npref[i] = arr[0] \oplus arr[1] \oplus \ldots \oplus arr[i] and if we xor this with pref[i - 1] = arr[0] \oplus a
|
heder
|
NORMAL
|
2022-10-09T16:21:45.382534+00:00
|
2022-10-09T19:49:22.687607+00:00
| 241 | false |
### Approach 1: in-place re-write from the back\n\n$$pref[i] = arr[0] \\oplus arr[1] \\oplus \\ldots \\oplus arr[i]$$ and if we xor this with $$pref[i - 1] = arr[0] \\oplus arr[1] \\oplus \\ldots \\oplus arr[i - 1]$$ we get $$arr[i]$$, and in the end $$arr[0] = pref[0]$$ already.\n\n```cpp\n static vector<int> findArray(vector<int>& pref) {\n for (int i = size(pref) - 1; i > 0; --i) {\n pref[i] ^= pref[i - 1];\n }\n return pref;\n }\n```\n\n**Complexity Analysis**\n * Time complexity: $$O(n)$$, where $$n$$ is ```size(pref)```.\n * Space complexity: $$O(1)$$ as we are not generating a new output vector.\n\n### Approach 2: std::adjacent_difference\n\nThis is based on a [post](https://leetcode.com/problems/find-the-original-array-of-prefix-xor/discuss/2682613/1-liner) by @andrii_khlevniuk, which is a great use of ```std::adjacent_difference```.\n\n```cpp\n static vector<int> findArray(vector<int>& pref) {\n adjacent_difference(begin(pref), end(pref), begin(pref), bit_xor());\n return pref;\n }\n```\n\nThe complexity is the same as above.\n\n_As always: Feedback, questions, and comments are welcome. Leaving an upvote sparks joy! :)_\n\n**p.s. Join us on the [LeetCode The Hard Way Discord Server](https://discord.gg/Nqm4jJcyBf)!**\n
| 6 | 0 |
['C']
| 1 |
find-the-original-array-of-prefix-xor
|
4 Line Code ✅| Beats 100%🔥| Easiest Solution
|
4-line-code-beats-100-easiest-solution-b-k75j
|
Intuition\n Describe your first thoughts on how to solve this problem. \nUpon reading the problem, the first thing that comes to our mind is how the XOR operati
|
45_Siddhant
|
NORMAL
|
2023-10-31T05:10:37.769870+00:00
|
2023-10-31T05:10:37.769902+00:00
| 545 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUpon reading the problem, the first thing that comes to our mind is how the XOR operation behaves. Since the prefix XOR array is essentially an accumulation of XOR operations, we think the inverse process would involve \'undoing\' the XOR operation. We remember that XOR has the following properties:\n\na \u2295 a = 0\na \u2295 0 = a\n\nXOR operation is both associative and commutative.\nThese properties hint towards the approach of using previous prefix values to deduce the current value.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe first key observation is that the first element of the original array is identical to the first element of the prefix array. This is because there\'s no preceding value to XOR with.\n\nFor each subsequent element in the prefix array, we can determine the corresponding element in the original array by performing an XOR operation between the current prefix value and the previous prefix value. This is derived from the properties of XOR, which allow us to effectively \'cancel out\' or \'undo\' previous accumulations.\n\nUtilizing this approach, we can iterate through the prefix array and populate our original array.\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```\nclass Solution {\npublic:\n vector<int> findArray(vector<int>& pref) {\n int n = pref.size();\n vector<int> ans(n);\n ans[0] = pref[0];\n\n for(int i = 1; i < n; i++){\n ans[i] = pref[i]^pref[i-1];\n }\n return ans;\n }\n};\n```
| 5 | 0 |
['Array', 'Bit Manipulation', 'C++']
| 6 |
find-the-original-array-of-prefix-xor
|
Easiest python solution with explanation
|
easiest-python-solution-with-explanation-hszr
|
Intuition\n Describe your first thoughts on how to solve this problem. \nfirst i thought of the brute force approach to like create a new array and arr[i] will
|
SilentKillerOP
|
NORMAL
|
2023-10-31T04:18:08.103754+00:00
|
2023-10-31T04:19:00.280196+00:00
| 263 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nfirst i thought of the brute force approach to like create a new array and arr[i] will be pref[i-1]^pref[i]. Then thought a was to reduce space complexity from o(n) to o(1). And came up with a solution to use a variable to store the previous element\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nStore the first element of prefix array in a variable say t.\nNow in each round of loop store the value of that element in a temp variable .\nThe value of original array will be xor with previous element that is t ^ current value\nSo we got the value of original array at i and just replace the value of t with temp variable and go one \n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def findArray(self, pref: List[int]) -> List[int]:\n if len(pref) <= 1: return pref\n\n t = pref[0]\n for i in range(1 , len(pref)):\n x = pref[i]\n pref[i] = t^pref[i]\n t = x\n return pref\n```
| 5 | 0 |
['Python3']
| 1 |
find-the-original-array-of-prefix-xor
|
😍BEATS 99.99% ✅|| EASY C++😊💯|| SIMPLE BEGINEER FRIENDLY🔥
|
beats-9999-easy-c-simple-begineer-friend-tun7
|
\n# Approach :\n Describe your approach to solving the problem. \nif u have knowledge about XOR operation U will easily understand this solution. here xor is do
|
DEvilBackInGame
|
NORMAL
|
2023-10-31T01:28:48.861636+00:00
|
2023-10-31T05:58:55.333045+00:00
| 621 | false |
\n# Approach :\n<!-- Describe your approach to solving the problem. -->\nif u have knowledge about XOR operation U will easily understand this solution. here xor is done between \'i\'th and \'i-1\'th element. how it working lefts see.. \n\nLets pref[i]=6 and pref[i-1]=3. then it will convert as follow:\n\nSTEP 1: \n\n6 in binary as=110\n 3 in binary as=001\n\nSTEP 2: Performing pref[i] ^ pref[i-1]:\n\n1 ^ 0 = 1.\n1 ^ 1 = 0.\n0 ^ 1 = 1.\n\nhence final xor answer=101 that is = 5 \n\nhence 5 is the new number that encodes the bitwise differences between these two numbers 6 and 3.\n\nXOR table:\n\nX\tY\tX^Y\n0\t0\t0\n0\t1\t1\n1\t0\t1\n1\t1\t0\n\n\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> findArray(vector<int>& pref) {\n vector<int> ans;\n ans.push_back(pref[0]);\n\n for(int i=1;i<pref.size();i++){\n int t=pref[i]^pref[i-1];\n ans.push_back(t);\n }\n return ans;\n }\n};\n```\n\n
| 5 | 0 |
['Bit Manipulation', 'C++']
| 6 |
find-the-original-array-of-prefix-xor
|
Python, C++,Java||Faster than 100%||Simple-Short-Solution||Easy To Understand
|
python-cjavafaster-than-100simple-short-lsal3
|
Please upvote to motivate me in my quest of documenting all leetcode solutions. HAPPY CODING:)\nAny suggestions and improvements are always welcome.\n___\n__\nQ
|
Anos
|
NORMAL
|
2022-10-13T18:07:44.625607+00:00
|
2022-10-13T18:07:44.625652+00:00
| 290 | false |
***Please upvote to motivate me in my quest of documenting all leetcode solutions. HAPPY CODING:)\nAny suggestions and improvements are always welcome*.**\n___________________\n_________________\n***Q2433. Find The Original Array of Prefix Xor***\n____________________________________________________________________________________________________________________\n____________________________________________________________________________________________________________________\n\u2705 **Python Code** :\n```\nclass Solution:\n def findArray(self, pref: List[int]) -> List[int]:\n for i in range(len(pref)-1,0,-1):\n pref[i]^=pref[i-1]\n return pref\n```\n____________________________________________________________________________________________________________________\n____________________________________________________________________________________________________________________\n\n\u2705 **Java Code** :\n```\nclass Solution {\n public int[] findArray(int[] pref) {\n for(int i=pref.length-1;i>0;--i)\n pref[i]^=pref[i-1];\n return pref;\n }\n}\n```\n\n____________________________________________________________________________________________________________________\n____________________________________________________________________________________________________________________\n\u2705 **C++ Code** :\n```\nclass Solution {\npublic:\n vector<int> findArray(vector<int>& pref) {\n for(int i=pref.size()-1;i>0;--i)\n pref[i]^=pref[i-1];\n return pref;\n }\n};\n```\n____________________________________________________________________________________________________________________\n____________________________________________________________________________________________________________________\nIf you like the solution, please upvote \uD83D\uDD3C\nFor any questions, or discussions, comment below. \uD83D\uDC47\uFE0F\n
| 5 | 0 |
['C', 'Python', 'Java']
| 2 |
find-the-original-array-of-prefix-xor
|
One for loop,That's it || O(n) solution
|
one-for-loopthats-it-on-solution-by-khem-7gls
|
Idea ::\n\nXor property::\n\nb = a^c => a=b^c;\n\nSince pref[i] = pref[i-1]^array[i] ,\ntherefore, array[i] = pref[i]^pre[i-1] \n\nwhere array[i] is ith element
|
khem_404
|
NORMAL
|
2022-10-09T04:05:22.523152+00:00
|
2022-10-09T04:17:47.372907+00:00
| 239 | false |
**Idea ::**\n\nXor property::\n\nb = a^c => a=b^c;\n\nSince pref[i] = pref[i-1]^array[i] ,\ntherefore, array[i] = pref[i]^pre[i-1] \n\nwhere array[i] is ith element in desired array\n\n\n\n```\nclass Solution \n{\npublic:\n vector<int> findArray(vector<int>& pref) \n {\n for(int i=pref.size()-1;i>=1;i--)\n pref[i]=pref[i]^pref[i-1];\n return pref;\n }\n};\n```
| 5 | 0 |
['C++']
| 1 |
find-the-original-array-of-prefix-xor
|
Kotlin Opposite of XOR is XOR easy
|
kotlin-opposite-of-xor-is-xor-easy-by-z3-7rxg
|
\nfun findArray(pref: IntArray): IntArray {\n\tvar curr = pref[0]\n\tvar result = mutableListOf(curr)\n\tfor (i in 1 until pref.size) {\n\t\tval new = curr xor
|
Z3ROsum
|
NORMAL
|
2022-10-09T04:03:10.857343+00:00
|
2022-10-09T04:03:10.857397+00:00
| 133 | false |
```\nfun findArray(pref: IntArray): IntArray {\n\tvar curr = pref[0]\n\tvar result = mutableListOf(curr)\n\tfor (i in 1 until pref.size) {\n\t\tval new = curr xor pref[i]\n\t\tresult.add(new)\n\t\tcurr = curr xor (new)\n\t}\n\treturn result.toIntArray()\n}\n```
| 5 | 0 |
['Kotlin']
| 1 |
find-the-original-array-of-prefix-xor
|
✅99.5% Beats🔥- Google - Bit Manipulation Solution 🔥🔥🔥
|
995-beats-google-bit-manipulation-soluti-9w6a
|
\n# Please Upvote It, if You find helpful :)\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the
|
sourav_n06
|
NORMAL
|
2023-10-31T01:33:22.497398+00:00
|
2023-10-31T01:33:22.497428+00:00
| 202 | false |
\n# Please Upvote It, if You find helpful :)\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n \nx1 = y0 ^ y1\nx2 = y1 ^ y2\nx3 = y2 ^ y3\nx4 = y3 ^ y4\nx5 = y4 ^ y5\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n) for Approach 1 and O(1) for Approach 2\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n// *** Approach - 1 ***\nclass Solution {\npublic:\n vector<int> findArray(vector<int>& pref) {\n vector<int> ans;\n ans.push_back(pref[0]);\n for(int i = 1; i < pref.size(); i++)\n {\n int ele = pref[i-1] ^ pref[i];\n ans.push_back(ele);\n }\n return ans;\n }\n};\n\n// *** Approach - 2 ***\n\nclass Solution {\npublic:\n vector<int> findArray(vector<int>& pref) {\n int curr = 0;\n for(int i = 1; i < pref.size(); i++)\n {\n curr = curr ^ pref[i-1];\n pref[i] = curr ^ pref[i];\n }\n return pref;\n }\n};\n\n\n\n```
| 4 | 0 |
['C++']
| 3 |
find-the-original-array-of-prefix-xor
|
🗓️ Daily LeetCoding Challenge October, Day 31
|
daily-leetcoding-challenge-october-day-3-mqtj
|
This problem is the Daily LeetCoding Challenge for October, Day 31. Feel free to share anything related to this problem here! You can ask questions, discuss wha
|
leetcode
|
OFFICIAL
|
2023-10-31T00:00:08.317611+00:00
|
2023-10-31T00:00:08.317647+00:00
| 3,346 | false |
This problem is the Daily LeetCoding Challenge for October, Day 31.
Feel free to share anything related to this problem here!
You can ask questions, discuss what you've learned from this problem, or show off how many days of streak you've made!
---
If you'd like to share a detailed solution to the problem, please create a new post in the discuss section and provide
- **Detailed Explanations**: Describe the algorithm you used to solve this problem. Include any insights you used to solve this problem.
- **Images** that help explain the algorithm.
- **Language and Code** you used to pass the problem.
- **Time and Space complexity analysis**.
---
**📌 Do you want to learn the problem thoroughly?**
Read [**⭐ LeetCode Official Solution⭐**](https://leetcode.com/problems/find-the-original-array-of-prefix-xor/solution) to learn the 3 approaches to the problem with detailed explanations to the algorithms, codes, and complexity analysis.
<details>
<summary> Spoiler Alert! We'll explain these 2 approaches in the official solution</summary>
**Approach 1:** Using XOR Properties
**Approach 2:** Using XOR Properties, Space Optimized
</details>
If you're new to Daily LeetCoding Challenge, [**check out this post**](https://leetcode.com/discuss/general-discussion/655704/)!
---
<br>
<p align="center">
<a href="https://leetcode.com/subscribe/?ref=ex_dc" target="_blank">
<img src="https://assets.leetcode.com/static_assets/marketing/daily_leetcoding_banner.png" width="560px" />
</a>
</p>
<br>
| 4 | 0 |
[]
| 45 |
find-the-original-array-of-prefix-xor
|
TIME O(n), SPACE O(1) || C++ || PREFIX XOR || MOST OPTIMIZED
|
time-on-space-o1-c-prefix-xor-most-optim-y1cm
|
Code\n\nclass Solution {\npublic:\n vector<int> findArray(vector<int>& pref) {\n int x = pref[0],y;\n for(int i = 1; i < pref.size(); i++){\n
|
ganeshkumawat8740
|
NORMAL
|
2023-06-19T10:26:16.195979+00:00
|
2023-06-19T10:26:16.195997+00:00
| 584 | false |
# Code\n```\nclass Solution {\npublic:\n vector<int> findArray(vector<int>& pref) {\n int x = pref[0],y;\n for(int i = 1; i < pref.size(); i++){\n y = pref[i];\n pref[i] = (pref[i]^x);\n x = y;\n }\n return pref;\n }\n};\n```
| 4 | 0 |
['Array', 'Bit Manipulation', 'C++']
| 1 |
find-the-original-array-of-prefix-xor
|
Beginner friendly [Java/JavaScript/Python] Solution
|
beginner-friendly-javajavascriptpython-s-krbu
|
Java\n\nclass Solution {\n public int[] findArray(int[] pref) {\n int xor = pref[0];\n for(int i=1; i<pref.length; i++){\n pref[i] ^
|
HimanshuBhoir
|
NORMAL
|
2022-10-10T17:31:06.386237+00:00
|
2022-10-10T17:31:06.386273+00:00
| 433 | false |
**Java**\n```\nclass Solution {\n public int[] findArray(int[] pref) {\n int xor = pref[0];\n for(int i=1; i<pref.length; i++){\n pref[i] ^= xor;\n xor ^= pref[i];\n }\n return pref;\n }\n}\n```\n**JavaScript**\n```\nvar findArray = function(pref) {\n let xor = pref[0];\n for(let i=1; i<pref.length; i++){\n pref[i] ^= xor;\n xor ^= pref[i];\n }\n return pref;\n};\n```\n**Python**\n```\nclass Solution(object):\n def findArray(self, pref):\n xor = pref[0]\n for i in range(1,len(pref)):\n pref[i] ^= xor\n xor ^= pref[i]\n return pref\n```
| 4 | 0 |
['Python', 'Java', 'JavaScript']
| 0 |
find-the-original-array-of-prefix-xor
|
Python [EXPLAINED] | O(n)
|
python-explained-on-by-diwakar_4-cbqb
|
Intuition \n- If we focus on a pattern :\n- a = 5 [0 1 0]\n- b = 7 [1 1 1]\n- c = a^b -> 2 [0 1 0]\n- c^a = 7 -> [1 1 1] = b\n\n- so for every pair of digits we
|
diwakar_4
|
NORMAL
|
2022-10-09T04:15:17.272307+00:00
|
2022-10-09T13:31:20.325832+00:00
| 242 | false |
# Intuition \n- If we focus on a pattern :\n- `a = 5 [0 1 0]`\n- `b = 7 [1 1 1]`\n- `c = a^b -> 2 [0 1 0]`\n- `c^a = 7 -> [1 1 1] = b`\n\n- so for every pair of digits we are already given `a` and `c` we just have to find `b`, that we can easily calculate with the aforementioned method.\n\n- It is just similar to we are given `a = 5`, `b = 7` and `c = a+b` and we have to find the value of `c`.\n- So `c = a+b` that is `c = 12.`\n\n# Approach\n- here we need to calculate prefix xor repeatedly so we can use a variable `XOR` to save time.\n- We will iterate through the array and we already have prefix xor in our `XOR` varible so `ans[i] = array[i]^XOR`.\n- then we will update `XOR` to `XOR = XOR^ans[i]`.\n\n- Here `a = arra[i]`, `b = XOR`, `c = a^b` and we have to find the value of `c` that is `ans[i]`.\n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(n)\n\n# Code\n```\nclass Solution:\n def findArray(self, pref: List[int]) -> List[int]:\n xor = 0\n ans = []\n for i in range(len(pref)):\n ans.append(pref[i]^xor)\n xor ^= ans[i]\n return ans\n```\n------------------\n**Upvote the post if you find it helpful.\nHappy coding.**
| 4 | 0 |
['Bit Manipulation', 'Python3']
| 1 |
find-the-original-array-of-prefix-xor
|
✅ C++ || Simple Approach || Easy to understand
|
c-simple-approach-easy-to-understand-by-e0som
|
\nclass Solution {\npublic:\n vector<int> findArray(vector<int>& pref) {\n int n=pref.size();\n \n vector<int> cnt;\n \n c
|
indresh149
|
NORMAL
|
2022-10-09T04:04:27.870643+00:00
|
2022-10-09T04:04:27.870676+00:00
| 557 | false |
```\nclass Solution {\npublic:\n vector<int> findArray(vector<int>& pref) {\n int n=pref.size();\n \n vector<int> cnt;\n \n cnt.push_back(pref[0]);\n \n for(int i=0;i<n-1;i++)\n {\n \n cnt.push_back(pref[i]^pref[i+1]);\n }\n \n return cnt;\n }\n};\n```\n**Don\'t forget to Upvote the post, if it\'s been any help to you**
| 4 | 0 |
['C']
| 2 |
find-the-original-array-of-prefix-xor
|
✅C++ || ✅Simple 4 Line || O(N) || O(1)
|
c-simple-4-line-on-o1-by-bhushan_mahajan-sud0
|
\nvector<int> findArray(vector<int>& pref) {\n int n = pref.size();\n \n vector<int> arr(n);\n arr[0] = pref[0];\n \n
|
Bhushan_Mahajan
|
NORMAL
|
2022-10-09T04:01:40.355587+00:00
|
2022-10-09T04:04:07.140993+00:00
| 905 | false |
```\nvector<int> findArray(vector<int>& pref) {\n int n = pref.size();\n \n vector<int> arr(n);\n arr[0] = pref[0];\n \n for( int i=1 ; i<pref.size() ; i++ ){\n \n arr[i] = pref[i-1]^pref[i] ;\n }\n return arr;\n }\n```
| 4 | 0 |
[]
| 2 |
find-the-original-array-of-prefix-xor
|
simple and easy Python solution
|
simple-and-easy-python-solution-by-shish-eesa
|
\n# if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n###### Let\'s Connect on LinkedIn: www.linkedin.com/in/shishirrsiam\n###### Let\'s Connect on Facebook
|
shishirRsiam
|
NORMAL
|
2024-09-29T16:04:19.368192+00:00
|
2024-09-29T16:04:19.368231+00:00
| 175 | false |
\n# if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n###### Let\'s Connect on LinkedIn: www.linkedin.com/in/shishirrsiam\n###### Let\'s Connect on Facebook: www.fb.com/shishirrsiam\n\n\n\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nclass Solution:\n def findArray(self, pref: List[int]) -> List[int]:\n n = len(pref)\n ans = [0] * n\n ans[0] = pref[0]\n for i in range(1, n):\n ans[i] = pref[i] ^ pref[i - 1]\n return ans\n```
| 3 | 0 |
['Array', 'Bit Manipulation', 'Python', 'Python3']
| 3 |
find-the-original-array-of-prefix-xor
|
simple and easy C++ solution
|
simple-and-easy-c-solution-by-shishirrsi-n2by
|
\n# if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n###### Let\'s Connect on LinkedIn: www.linkedin.com/in/shishirrsiam\n###### Let\'s Connect on Facebook
|
shishirRsiam
|
NORMAL
|
2024-09-29T16:01:48.893189+00:00
|
2024-09-29T16:01:48.893218+00:00
| 148 | false |
\n# if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n###### Let\'s Connect on LinkedIn: www.linkedin.com/in/shishirrsiam\n###### Let\'s Connect on Facebook: www.fb.com/shishirrsiam\n\n\n\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<int> findArray(vector<int>& pref) \n {\n int n = pref.size();\n vector<int>ans(n);\n ans[0] = pref[0];\n for(int i = 1; i < n; i++)\n ans[i] = pref[i] ^ pref[i - 1];\n return ans;\n }\n};\n```
| 3 | 0 |
['Array', 'Bit Manipulation', 'C++']
| 3 |
find-the-original-array-of-prefix-xor
|
Simple Java Solution O(n)
|
simple-java-solution-on-by-sharmanishcha-znhq
|
Intuition\n Describe your first thoughts on how to solve this problem. \n1. It initializes an integer array a with the same length as the input array pref.\n2.
|
sharmanishchay
|
NORMAL
|
2024-02-14T12:54:20.502189+00:00
|
2024-02-14T12:54:20.502220+00:00
| 11 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n1. It initializes an integer array a with the same length as the input array pref.\n2. It assigns the first element of a as the same as the first element of pref.\n3. Then, it iterates through the elements of pref starting from index 1.\n4. For each element pref[i], it calculates pref[i-1] XOR pref[i] and assigns the result to a[i].\n5. Finally, it returns the array a.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Initialize a new array a with the same length as pref to store the XOR results.\n2. Assign the first element of a as pref[0].\n3. Iterate through pref starting from index 1.\n4. For each element pref[i], calculate pref[i-1] XOR pref[i] and assign the result to a[i].\n5. Return the array a containing the XOR results.\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int[] findArray(int[] pref) {\n int[]a = new int[pref.length];\n a[0] = pref[0];\n for(int i = 1; i<pref.length;i++){\n a[i] = pref[i-1] ^ pref[i];\n }\n return a;\n }\n}\n```
| 3 | 0 |
['Array', 'Bit Manipulation', 'Java']
| 0 |
find-the-original-array-of-prefix-xor
|
✅☑[C++/Java/Python/JavaScript] || 1 line Code || EXPLAINED🔥
|
cjavapythonjavascript-1-line-code-explai-qpet
|
PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n(Also explained in the code)\n\n\n1. It checks if the size of the pref vector is less than or equal to 1. I
|
MarkSPhilip31
|
NORMAL
|
2023-10-31T15:32:29.779958+00:00
|
2023-10-31T15:32:29.779986+00:00
| 133 | false |
# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n\n1. It checks if the size of the `pref` vector is less than or equal to 1. If so, it returns the pref vector as it is, as there\'s not enough information to reconstruct an original array in such cases.\n\n1. If the `pref` vector has more than one element, it initializes an empty vector called `ans` to store the reconstructed original array.\n\n1. It then pushes the first element of the `pref` vector onto the `ans` vector. This is done because the first element of the original array is the same as the first element of the prefix array.\n\n1. The code enters a loop that iterates through the elements of the `pref` vector starting from the second element (at index 1).\n\n1. Inside the loop, it reconstructs the original array element by element. To find the next element in the original array, it takes the `XOR` (bitwise exclusive OR) of the current prefix element (**at index i**) and the previous one (**at index i - 1**).\n\n1. The result of the `XOR` operation is then pushed onto the `ans` vector, which is essentially building the original array element by element.\n\n1. After the loop has processed all elements in the `pref` vector, the reconstructed original array is stored in the `ans` vector.\n\n1. The function returns the `ans` vector, which now contains the reconstructed original array based on the given prefix array.\n\n\n\n# Complexity\n- *Time complexity:*\n $$O(n)$$\n \n\n- *Space complexity:*\n $$O(n)$$\n \n\n\n# Code\n```C++ []\n\nclass Solution {\npublic:\n // Function to find the original array from the prefix array.\n vector<int> findArray(vector<int>& pref) {\n // If the prefix array has one or zero elements, return it as is.\n if (pref.size() <= 1) {\n return pref;\n }\n\n vector<int> ans; // Initialize a vector to store the original array.\n ans.push_back(pref[0]); // The first element in the original array is the same as the first element in the prefix array.\n\n // Iterate through the prefix array to reconstruct the original array.\n for (int i = 1; i < pref.size(); i++) {\n // To find the next element in the original array, take the XOR (bitwise exclusive OR) of the current prefix element and the previous one.\n ans.push_back(pref[i - 1] ^ pref[i]);\n }\n\n return ans; // Return the reconstructed original array.\n }\n};\n\n\n```\n```C []\n\n\nint* findArray(int* pref, int prefSize, int* returnSize) {\n if (prefSize <= 1) {\n *returnSize = prefSize;\n return pref;\n }\n\n int* ans = (int*)malloc(prefSize * sizeof(int));\n ans[0] = pref[0];\n\n for (int i = 1; i < prefSize; i++) {\n ans[i] = pref[i - 1] ^ pref[i];\n }\n\n *returnSize = prefSize;\n return ans;\n}\n\n\n\n```\n\n```Java []\n\n\npublic class Solution {\n public int[] findArray(int[] pref) {\n if (pref.length <= 1) {\n return pref;\n }\n\n int[] ans = new int[pref.length];\n ans[0] = pref[0];\n\n for (int i = 1; i < pref.length; i++) {\n ans[i] = pref[i - 1] ^ pref[i];\n }\n\n return ans;\n }\n}\n\n\n```\n```python3 []\n\nclass Solution:\n def findArray(self, pref):\n if len(pref) <= 1:\n return pref\n\n ans = [pref[0]]\n for i in range(1, len(pref)):\n ans.append(pref[i - 1] ^ pref[i])\n\n return ans\n\n```\n\n\n```javascript []\nclass Solution {\n findArray(pref) {\n if (pref.length <= 1) {\n return pref;\n }\n\n const ans = [pref[0]];\n for (let i = 1; i < pref.length; i++) {\n ans.push(pref[i - 1] ^ pref[i]);\n }\n\n return ans;\n }\n}\n\n\n```\n\n\n---\n\n\n\n# PLEASE UPVOTE IF IT HELPED\n\n---\n---\n\n\n---
| 3 | 0 |
['Array', 'Bit Manipulation', 'C', 'C++', 'Java', 'Python3', 'JavaScript']
| 0 |
find-the-original-array-of-prefix-xor
|
✅Easy Solution🔥Java/C++/C/Python3/Python/JavaScript🔥
|
easy-solutionjavaccpython3pythonjavascri-g1po
|
\n\n\n# Code\nJava []\nclass Solution {\n public int[] findArray(int[] pref) {\n int[] ans = new int[pref.length];\n ans[0] = pref[0];\n
|
apurvjain7827
|
NORMAL
|
2023-10-31T10:40:46.951599+00:00
|
2023-10-31T10:40:46.951618+00:00
| 166 | false |
\n\n\n# Code\n```Java []\nclass Solution {\n public int[] findArray(int[] pref) {\n int[] ans = new int[pref.length];\n ans[0] = pref[0];\n for(int i=1; i<ans.length; i++){\n ans[i] = pref[i] ^ pref[i-1];\n }\n return ans;\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n std::vector<int> findArray(std::vector<int>& pref) {\n std::vector<int> ans(pref.size());\n ans[0] = pref[0];\n for (int i = 1; i < ans.size(); i++) {\n ans[i] = pref[i] ^ pref[i - 1];\n }\n return ans;\n }\n};\n```\n```C []\nint* findArray(int* pref, int prefSize, int* returnSize){\n int* ans = (int*)malloc(prefSize * sizeof(int));\n ans[0] = pref[0];\n for (int i = 1; i < prefSize; i++) {\n ans[i] = pref[i] ^ pref[i - 1];\n }\n \n *returnSize = prefSize;\n return ans;\n}\n```\n```Python3 []\nclass Solution:\n def findArray(self, pref: List[int]) -> List[int]:\n ans = [0] * len(pref)\n ans[0] = pref[0]\n for i in range(1, len(ans)):\n ans[i] = pref[i] ^ pref[i - 1]\n return ans\n```\n```Python []\nclass Solution(object):\n def findArray(self, pref):\n ans = [0] * len(pref)\n ans[0] = pref[0]\n for i in range(1, len(ans)):\n ans[i] = pref[i] ^ pref[i - 1]\n return ans\n```\n\n```JavaScript []\n/**\n * @param {number[]} pref\n * @return {number[]}\n */\nvar findArray = function(pref) {\n let ans = new Array(pref.length);\n ans[0] = pref[0];\n for (let i = 1; i < ans.length; i++) {\n ans[i] = pref[i] ^ pref[i - 1];\n }\n return ans;\n};\n\n```\n
| 3 | 0 |
['Array', 'Math', 'Bit Manipulation', 'C', 'Prefix Sum', 'Python', 'C++', 'Java', 'Python3', 'JavaScript']
| 0 |
find-the-original-array-of-prefix-xor
|
solution without using new array
|
solution-without-using-new-array-by-arya-mwgs
|
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
|
Aryan02_364
|
NORMAL
|
2023-10-31T06:35:20.058987+00:00
|
2023-10-31T06:35:20.059018+00:00
| 237 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n // vector<int> findArray(vector<int>& pref) {\n // int n = pref.size();\n // vector<int> ans;\n // ans.push_back(pref[0]);\n\n // for(int i = 1; i < n; i++){\n // int result = pref[i] ^ pref[i - 1];\n // ans.push_back(result);\n // }\n // return ans;\n // }\n \n //2nd method without using new array\n \n vector<int> findArray(vector<int>& pref) {\n int n = pref.size();\n \n for(int i = n-1; i > 0; i--){\n pref[i] = pref[i] ^ pref[i - 1];\n }\n return pref;\n }\n};\n```
| 3 | 0 |
['C++']
| 2 |
find-the-original-array-of-prefix-xor
|
✅ Beats 99.24% 🔥 || 3 Approaches 💡 ||
|
beats-9924-3-approaches-by-gourav-2002-hvn3
|
Approach 1: Prefix Sum\n\n\n\n# Intuition:\n\nIf we have an array of prefix sums pref, then the original array arr can be recovered by taking the prefix sum of
|
Gourav-2002
|
NORMAL
|
2023-10-31T03:57:18.249173+00:00
|
2023-10-31T03:57:18.249201+00:00
| 584 | false |
# Approach 1: Prefix Sum\n\n\n\n# Intuition:\n\n**If we have an array of prefix sums pref, then the original array arr can be recovered by taking the prefix sum of pref. That is, arr[i] = pref[i] ^ pref[i-1] for i > 0 and arr[0] = pref[0]. This is because pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i-1] ^ arr[i], so pref[i] ^ pref[i-1] = arr[i].** \n\n# Algorithm:\n1. Initialize ans = [0] * n, where n is the length of pref.\n2. ans[0] = pref[0] because pref[0] = arr[0] ^ arr[1] ^ ... ^ arr[n-1] = arr[0].\n3. For i in range(1, n), ans[i] = pref[i] ^ pref[i-1]. This is because pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i-1] ^ arr[i], so pref[i] ^ pref[i-1] = arr[i].\n4. Return ans.\n\n# Complexity Analysis:\n- Time Complexity: **O(n)**, where n is the length of pref.\n- Space Complexity: **O(n)**, the space used by ans.\n\n# Code\n``` Python []\nclass Solution:\n def findArray(self, pref: List[int]) -> List[int]:\n n = len(pref)\n ans = [0] * n\n ans[0]=pref[0]\n for i in range(1,n):\n ans[i]=pref[i]^pref[i-1]\n return ans\n```\n``` C++ []\nclass Solution {\npublic:\n vector<int> findArray(vector<int>& pref) {\n int n = pref.size();\n vector<int> ans(n, 0);\n ans[0] = pref[0];\n for (int i = 1; i < n; i++) {\n ans[i] = pref[i] ^ pref[i - 1];\n }\n return ans;\n }\n};\n```\n``` Java []\nclass Solution {\n public int[] findArray(int[] pref) {\n int n = pref.length;\n int[] ans = new int[n];\n ans[0] = pref[0];\n for (int i = 1; i < n; i++) {\n ans[i] = pref[i] ^ pref[i - 1];\n }\n return ans;\n }\n}\n```\n# Approach 2: Prefix Sum (In-Place)\n\n\n# Intuition:\n**If we have an array of prefix sums pref, then the original array arr can be recovered by taking the prefix sum of pref. That is, arr[i] = pref[i] ^ pref[i-1] for i > 0 and arr[0] = pref[0]. This is because pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i-1] ^ arr[i], so pref[i] ^ pref[i-1] = arr[i].**\n\n# Algorithm:\n1. For i in range(1, n), pref[i] ^= pref[i-1]. This is because pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i-1] ^ arr[i], so pref[i] ^ pref[i-1] = arr[i].\n2. Return pref.\n\n# Complexity Analysis:\n- Time Complexity: **O(n)**, where n is the length of pref.\n- Space Complexity: **O(1)**, the space used by pref.\n\n\n# Code\n``` Python []\nclass Solution:\n def findArray(self, pref: List[int]) -> List[int]:\n return [pref[0]] + [pref[i] ^ pref[i-1] for i in range(1, len(pref))]\n```\n``` C++ []\nclass Solution {\npublic:\n vector<int> findArray(vector<int>& pref) {\n vector<int> result(pref.size());\n result[0] = pref[0];\n for (int i = 1; i < pref.size(); i++) {\n result[i] = pref[i] ^ pref[i-1];\n }\n return result;\n }\n};\n```\n``` Java []\nclass Solution {\n public int[] findArray(int[] pref) {\n int[] result = new int[pref.length];\n result[0] = pref[0];\n for (int i = 1; i < pref.length; i++) {\n result[i] = pref[i] ^ pref[i-1];\n }\n return result;\n }\n}\n```\n\n# Approach 3: Reverse Prefix Sum (In-Place)\n\n\n\n# Intuition:\n**If we to find out the prefix sum of pref, we will be doing it in by pref[i]=pref[i]^pref[i-1]. But when we do it in reverse order. We don\'t \nhave to create a new array. We can just do it in place.**\n\n# Algorithm:\n1. For i in range(n-1, 0, -1), pref[i] ^= pref[i-1]. This is because pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i-1] ^ arr[i], so pref[i] ^ pref[i-1] = arr[i].\n2. Return pref.\n\n# Complexity Analysis:\n- Time Complexity: **O(n)**, where n is the length of pref.\n- Space Complexity: **O(1)**, the space used by pref.\n# Code\n``` Python []\nclass Solution:\n def findArray(self, pref):\n for i in range(len(pref) - 1, 0, -1):\n pref[i] = (pref[i] ^ pref[i-1])\n return pref\n```\n``` C++ []\nclass Solution {\npublic:\n vector<int> findArray(vector<int>& pref) {\n for (int i = pref.size() - 1; i > 0; i--) {\n pref[i] = (pref[i] ^ pref[i-1]);\n }\n return pref;\n }\n};\n```\n``` Java []\nclass Solution {\n public int[] findArray(int[] pref) {\n for (int i = pref.length - 1; i > 0; i--) {\n pref[i] = (pref[i] ^ pref[i-1]);\n }\n return pref;\n }\n}\n```
| 3 | 0 |
['Array', 'Math', 'Bit Manipulation', 'Prefix Sum', 'C++', 'Java', 'Python3']
| 2 |
find-the-original-array-of-prefix-xor
|
2 Easy C++ solution || Beginner and advanced approach || Beats 90% !!
|
2-easy-c-solution-beginner-and-advanced-escvr
|
From the \n\n# Code\n\n// Beginner approach\nclass Solution {\npublic:\n vector<int> findArray(vector<int>& pref) {\n int ans = 0;\n vector<int
|
prathams29
|
NORMAL
|
2023-06-26T14:43:29.676790+00:00
|
2023-06-26T14:43:50.614764+00:00
| 102 | false |
From the \n\n# Code\n```\n// Beginner approach\nclass Solution {\npublic:\n vector<int> findArray(vector<int>& pref) {\n int ans = 0;\n vector<int> a;\n for(int i=0; i<pref.size(); i++){\n a.push_back(ans^pref[i]);\n ans=pref[i];\n }\n return a;\n }\n};\n\n// Better approach (Not that advanced tbh)\nclass Solution {\npublic:\n vector<int> findArray(vector<int>& pref) {\n for(int i=pref.size()-1; i>0; i--){\n pref[i]^=pref[i-1];\n }\n return pref;\n }\n};\n```
| 3 | 0 |
['C++']
| 0 |
find-the-original-array-of-prefix-xor
|
one-pass || EASY TO UNDERSTAND || SHORT & SWEET || C++
|
one-pass-easy-to-understand-short-sweet-oh1b1
|
\nclass Solution {\npublic:\n vector<int> findArray(vector<int>& pref) {\n int a = pref[0],b=pref[0];\n for(int i = 1; i < pref.size(); i++){\n
|
yash___sharma_
|
NORMAL
|
2023-03-28T11:40:48.022513+00:00
|
2023-03-28T11:40:48.022596+00:00
| 491 | false |
````\nclass Solution {\npublic:\n vector<int> findArray(vector<int>& pref) {\n int a = pref[0],b=pref[0];\n for(int i = 1; i < pref.size(); i++){\n a = pref[i];\n pref[i] = (pref[i]^b);\n b = a;\n }\n return pref;\n }\n};\n````
| 3 | 0 |
['Bit Manipulation', 'C', 'C++']
| 0 |
find-the-original-array-of-prefix-xor
|
[JAVA] 2 liner easiest solution
|
java-2-liner-easiest-solution-by-juganta-qgxn
|
\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
|
Jugantar2020
|
NORMAL
|
2022-11-14T15:38:22.189923+00:00
|
2022-11-14T15:38:22.189962+00:00
| 281 | false |
\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int[] findArray(int[] pref) {\n for(int i = pref.length - 1; i > 0; i --) {\n pref[i] ^= pref[i - 1]; \n } \n return pref;\n }\n}\n```\n# PLEASE UPVOTE IF IT WAS HELPFULL
| 3 | 0 |
['Java']
| 1 |
find-the-original-array-of-prefix-xor
|
Go Simple Solution
|
go-simple-solution-by-x-color-7zjf
|
\nfunc findArray(pref []int) []int {\n\tans := make([]int, len(pref))\n\tans[0] = pref[0]\n\tfor i := 1; i < len(pref); i++ {\n\t\tans[i] = pref[i-1] ^ pref[i]\
|
x-color
|
NORMAL
|
2022-10-09T04:05:20.442245+00:00
|
2022-10-09T04:05:20.442288+00:00
| 63 | false |
```\nfunc findArray(pref []int) []int {\n\tans := make([]int, len(pref))\n\tans[0] = pref[0]\n\tfor i := 1; i < len(pref); i++ {\n\t\tans[i] = pref[i-1] ^ pref[i]\n\t}\n\treturn ans\n}\n```
| 3 | 0 |
['Go']
| 0 |
find-the-original-array-of-prefix-xor
|
Reverse XOR
|
reverse-xor-by-theakkirana-n9vh
|
Please upvote if find helpful :)\n\npref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i]\npref[i] is the calculated XOR array of 0 to i elements\n\nNow let\'s analyze the i
|
TheAkkirana
|
NORMAL
|
2022-10-09T04:04:59.369146+00:00
|
2022-10-09T04:11:47.714308+00:00
| 270 | false |
**Please upvote if find helpful :)**\n\n```pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i]```\npref[i] is the calculated XOR array of 0 to i elements\n\nNow let\'s analyze the input\n```\nInput: pref = [5,2,0,3,1]\nOutput: [5,7,2,3,2]\nExplanation: From the array [5,7,2,3,2] we have the following:\n- pref[0] = 5.\n- pref[1] = 5 ^ 7 = 2.\n- pref[2] = 5 ^ 7 ^ 2 = 0.\n- pref[3] = 5 ^ 7 ^ 2 ^ 3 = 3.\n- pref[4] = 5 ^ 7 ^ 2 ^ 3 ^ 2 = 1.\n\nfor i=0 , 5 is the answer\nfor i=1 , 5 ^ x = 2 , we need value of x , to get value of x we can do XOR on both sides with 5\n 5 ^ x ^ 5 =2 ^5 , x=2^5 , x=2 ^ prev\nfor i=2 , 5 ^ 7 ^ x = 0 , to get x same XOR on both sides with ( 5 ^ 7 ) but 5 ^ 7 can be represented with 2 which is the last value of pref \n```\n\n#### CODE\n```\nvector<int> findArray(vector<int>& pref) {\n vector<int>ans;\n int prev=0;\n for(int &p:pref){\n ans.push_back(p^prev);\n prev=p;\n }\n return ans;\n }\n```
| 3 | 0 |
['C++']
| 1 |
find-the-original-array-of-prefix-xor
|
Simple C++ solution
|
simple-c-solution-by-ashishks0211-xj86
|
```\nclass Solution {\npublic:\n vector findArray(vector& pref) {\n int n = pref.size();\n vector ans(n);\n ans[0] = pref[0];\n f
|
Ashishks0211
|
NORMAL
|
2022-10-09T04:02:24.765617+00:00
|
2022-10-09T04:02:24.765655+00:00
| 77 | false |
```\nclass Solution {\npublic:\n vector<int> findArray(vector<int>& pref) {\n int n = pref.size();\n vector<int> ans(n);\n ans[0] = pref[0];\n for(int i = 1;i<n;i++)\n ans[i] = pref[i-1] ^ pref[i];\n return ans; \n }\n};
| 3 | 0 |
['Bit Manipulation', 'C']
| 0 |
find-the-original-array-of-prefix-xor
|
Very Unique easy ways to Tackle this problem C++ / C# / python3 / Java / C / Python / Swift
|
very-unique-easy-ways-to-tackle-this-pro-f9ba
|
Intuition\n\n\n\n\n\n\nC++ []\nclass Solution {\npublic:\n vector<int> findArray(vector<int>& pref) {\n vector<int> arr(pref.size(), 0);\n arr[
|
Edwards310
|
NORMAL
|
2024-03-26T04:55:17.829647+00:00
|
2024-03-26T04:55:17.829677+00:00
| 16 | false |
# Intuition\n\n\n\n\n\n\n```C++ []\nclass Solution {\npublic:\n vector<int> findArray(vector<int>& pref) {\n vector<int> arr(pref.size(), 0);\n arr[0] = pref[0];\n for (int i = 1; i < pref.size(); ++i)\n arr[i] = pref[i - 1] ^ pref[i];\n return arr;\n }\n};\n```\n```python3 []\nclass Solution:\n def findArray(self, pref: List[int]) -> List[int]:\n arr = [0] * len(pref)\n arr[0] = pref[0]\n for i in range(1, len(pref)):\n arr[i] = pref[i - 1] ^ pref[i]\n\n return arr\n```\n```C []\n/**\n * Note: The returned array must be malloced, assume caller calls free().\n */\nint* findArray(int* pref, int prefSize, int* returnSize) {\n int* arr = malloc(sizeof(int) * prefSize);\n arr[0] = pref[0];\n for (int i = 1; i < prefSize; ++i)\n arr[i] = pref[i - 1] ^ pref[i];\n *returnSize = prefSize;\n return arr;\n}\n```\n```java []\nclass Solution {\n public int[] findArray(int[] pref) {\n int arr[] = new int[pref.length];\n arr[0] = pref[0];\n for (int i = 1; i < pref.length; ++i)\n arr[i] = pref[i - 1] ^ pref[i];\n return arr;\n }\n}\n```\n```python []\nclass Solution(object):\n def findArray(self, pref):\n """\n :type pref: List[int]\n :rtype: List[int]\n """\n arr = [0] * len(pref)\n arr[0] = pref[0]\n for i in range(1, len(pref)):\n arr[i] = pref[i - 1] ^ pref[i]\n\n return arr\n```\n```C# []\npublic class Solution {\n public int[] FindArray(int[] pref) {\n int []arr = new int[pref.Length];\n arr[0] = pref[0];\n for (int i = 1; i < pref.Length; ++i)\n arr[i] = pref[i - 1] ^ pref[i];\n return arr;\n }\n}\n```\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(n)\n# Code\n```\npublic class Solution {\n public int[] FindArray(int[] pref) {\n int []arr = new int[pref.Length];\n arr[0] = pref[0];\n for (int i = 1; i < pref.Length; ++i)\n arr[i] = pref[i - 1] ^ pref[i];\n return arr;\n }\n}\n```\n# Please find my solution & upvote although you don\'t need a solution for this question\n\n
| 2 | 0 |
['Stack', 'C', 'Python', 'C++', 'Java', 'Python3', 'C#']
| 1 |
find-the-original-array-of-prefix-xor
|
Prefix XOR
|
prefix-xor-by-akshita_12-damx
|
Intuition\n Describe your first thoughts on how to solve this problem. \nIf a^x=b, then b=b^a.\n\n# Approach\n Describe your approach to solving the problem. \n
|
akshita_12
|
NORMAL
|
2024-02-23T09:11:51.549596+00:00
|
2024-02-23T09:11:51.549619+00:00
| 3 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIf a^x=b, then b=b^a.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe keep xoring the elements of pref[i] using for loop and calculate ans[i].\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> findArray(vector<int>& pref) {\n \n vector<int> ans(pref.size(),0);\n ans[0]=pref[0];\n int xr=pref[0];\n for(int i=1; i<pref.size(); i++){\n \n ans[i]=pref[i]^xr;\n xr=xr^ans[i];\n }\n return ans;\n }\n};\n```
| 1 | 0 |
['C++']
| 0 |
find-the-original-array-of-prefix-xor
|
✅Super Easy Bit Manipulation (C++/Java/Python) Solution With Detailed Explanation✅
|
super-easy-bit-manipulation-cjavapython-qgsbi
|
Intuition\nThe algorithm reconstructs an original array from its prefix XOR array by iteratively computing each element as the XOR of the cumulative XOR up to t
|
suyogshete04
|
NORMAL
|
2024-02-22T03:49:31.743599+00:00
|
2024-02-22T03:49:31.743635+00:00
| 753 | false |
# Intuition\nThe algorithm reconstructs an original array from its prefix XOR array by iteratively computing each element as the XOR of the cumulative XOR up to the previous element and the current element of the prefix XOR array.\n\n# Approach\n\n1. **Initialization**: An integer `n` is initialized to store the size of the input prefix XOR array `pref`. A new vector `res` of size `n` is created to store the result, i.e., the original array.\n\n2. **Cumulative XOR Calculation**: An integer `x` is initialized to 0. This variable will hold the cumulative XOR of elements as they are added to the `res` array. It effectively represents the prefix XOR up to the previous element of the array being reconstructed.\n\n3. **Reconstruction Loop**:\n - The loop iterates over each index `i` of the `pref` array.\n - For each index `i`, the value of `res[i]` is determined by XORing `x` with `pref[i]`. Since `x` holds the XOR of all previous elements of the resulting array, XORing it with `pref[i]` effectively reverses the prefix XOR operation, yielding the original value at `res[i]`.\n - After calculating `res[i]`, `x` is updated by XORing it with `res[i]`, thus including the latest element in the cumulative XOR for the next iteration.\n\n4. **Return Result**: After the loop completes, the `res` vector, which now contains the original array, is returned.\n\n### Complexity Analysis\n\n- **Time Complexity**: The algorithm iterates once over the array `pref`, performing a constant number of operations for each element (specifically, two XOR operations and a couple of assignments). Therefore, the time complexity is `O(n)`, where `n` is the length of the input array `pref`.\n\n- **Space Complexity**: The space complexity is also `O(n)` due to the storage requirements of the `res` vector, which is the same size as the input array `pref`. The rest of the variables (`n` and `x`) use constant space.\n\n# Code\n```C++ []\nclass Solution {\npublic:\n vector<int> findArray(vector<int>& pref) {\n int n = pref.size();\n vector<int> res (n);\n int x = 0;\n for (int i=0; i<n; i++)\n {\n res[i] = x ^ pref[i];\n x ^= res[i];\n }\n\n return res;\n }\n};\n```\n```Java []\npublic class Solution {\n public int[] findArray(int[] pref) {\n int n = pref.length;\n int[] res = new int[n];\n int x = 0;\n for (int i = 0; i < n; i++) {\n res[i] = x ^ pref[i];\n x ^= res[i];\n }\n return res;\n }\n}\n\n```\n```Python []\nfrom typing import List\n\nclass Solution:\n def findArray(self, pref: List[int]) -> List[int]:\n n = len(pref)\n res = [0] * n\n x = 0\n for i in range(n):\n res[i] = x ^ pref[i]\n x ^= res[i]\n \n return res\n\n```
| 2 | 0 |
['Bit Manipulation', 'C++', 'Java', 'Python3']
| 0 |
find-the-original-array-of-prefix-xor
|
Ever used pairwise() ??
|
ever-used-pairwise-by-ribindal-xczj
|
Intuition\nI have knowledge of builtin modules.\n\n# Code\n\nclass Solution:\n def findArray(self, pref: List[int]) -> List[int]:\n return [pref[0]] +
|
ribindal
|
NORMAL
|
2023-10-31T18:55:00.908540+00:00
|
2023-10-31T18:55:00.908563+00:00
| 112 | false |
# Intuition\nI have knowledge of builtin modules.\n\n# Code\n```\nclass Solution:\n def findArray(self, pref: List[int]) -> List[int]:\n return [pref[0]] + [ a ^ b for a, b in pairwise(pref)]\n```\n\n> Comment a better solution than this.
| 2 | 0 |
['Python3']
| 0 |
find-the-original-array-of-prefix-xor
|
Single list-comprehension (without concat or ifs) using walrus operator
|
single-list-comprehension-without-concat-8ix5
|
Additional solution to the list, this time using python\'s walrus operator which allows us to build the array result in a single list comprehension expression.\
|
albertferras
|
NORMAL
|
2023-10-31T17:54:04.335390+00:00
|
2023-10-31T17:54:04.335418+00:00
| 106 | false |
Additional solution to the list, this time using python\'s `walrus operator` which allows us to build the array result in a single list comprehension expression.\nWith the idea of `i++` in other languages, we use the value of `x` and assign it to `last` for the next iteration.\n\nExample:\n```\nlast = 3\nx = 7\nresult = last^(last:=x)\n\n# After evaluating `result`, each variable equals to:\n# result = 3^7 = 4\n# last = 7\n# x = 7\n```\n\nAdd this to a list comprehension and you get a less-readable but faster array construction. It turns out to also be shorter than other one-liner solutions.\n\n\n# Code\n```\nclass Solution:\n def findArray(self, pref: List[int]) -> List[int]:\n last = 0\n return [last^(last:=x) for x in pref]\n```
| 2 | 0 |
['Python3']
| 0 |
find-the-original-array-of-prefix-xor
|
✅ 92.93% One Line XORing
|
9293-one-line-xoring-by-ankita2905-5fz0
|
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
|
Ankita2905
|
NORMAL
|
2023-10-31T17:49:30.921905+00:00
|
2023-10-31T17:49:30.921942+00:00
| 117 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> findArray(vector<int>& pref) {\n vector<int> result(pref.size());\n result[0] = pref[0];\n for(int i = 1; i < pref.size(); i++) {\n result[i] = pref[i] ^ pref[i-1];\n }\n return result;\n }\n};\n```
| 2 | 0 |
['C++']
| 0 |
find-the-original-array-of-prefix-xor
|
Easy and clean solution | O(n)/O(n)✅
|
easy-and-clean-solution-onon-by-delta7ac-sa7b
|
\n# Complexity\n- Time complexity: O(N), where N is the length of the pref array.\n\n- Space complexity: O(N), where N is the length of the pref array.\n Add yo
|
Delta7Actual
|
NORMAL
|
2023-10-31T13:48:03.252848+00:00
|
2023-10-31T13:48:03.252867+00:00
| 10 | false |
\n# Complexity\n- **Time complexity:** $$O(N)$$, where $$N$$ is the length of the `pref` array.\n\n- **Space complexity:** $$O(N)$$, where $$N$$ is the length of the `pref` array.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n---\n\n```C# []\npublic class Solution {\n public int[] FindArray(int[] pref) {\n int[] result = new int[pref.Length];\n result[0] = pref[0];\n for(int i = 1; i < pref.Length; i++)\n {\n result[i] = pref[i] ^ pref[i-1];\n }\n return result;\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n vector<int> findArray(vector<int>& pref) {\n std::vector<int> result(pref.size());\n result[0] = pref[0];\n for (int i = 1; i < pref.size(); i++) {\n result[i] = pref[i] ^ pref[i - 1];\n }\n return result;\n }\n};\n```\n```Python []\nclass Solution(object):\n def findArray(self, pref):\n result = [0] * len(pref)\n result[0] = pref[0]\n for i in range(1, len(pref)):\n result[i] = pref[i] ^ pref[i - 1]\n return result\n```\n```Javascript []\nvar findArray = function(pref) {\n const result = new Array(pref.length);\n result[0] = pref[0];\n for (let i = 1; i < pref.length; i++) {\n result[i] = pref[i] ^ pref[i - 1];\n }\n return result;\n};\n```\n\n---\n\n\n\n
| 2 | 0 |
['Array', 'Bit Manipulation', 'Python', 'C++', 'JavaScript', 'C#']
| 0 |
find-the-original-array-of-prefix-xor
|
Python 1-liner. Functional programming.
|
python-1-liner-functional-programming-by-05r8
|
Approach\nTL;DR, Similar to Editorial solution Approach 2 but shorter and functional.\n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(n), incl
|
darshan-as
|
NORMAL
|
2023-10-31T12:40:20.111365+00:00
|
2023-10-31T12:40:20.111392+00:00
| 5 | false |
# Approach\nTL;DR, Similar to [Editorial solution Approach 2](https://leetcode.com/problems/find-the-original-array-of-prefix-xor/editorial/?envType=daily-question&envId=2023-10-31) but shorter and functional.\n\n# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(n)$$, including the output else $$O(1)$$\n\nwhere,\n`n is length of pref array`.\n\n# Code\n```python\nclass Solution:\n def findArray(self, pref: list[int]) -> list[int]:\n return list(starmap(xor, pairwise(chain((0,), pref))))\n\n\n```
| 2 | 0 |
['Array', 'Bit Manipulation', 'Python', 'Python3']
| 1 |
find-the-original-array-of-prefix-xor
|
Simple Clean Code || Bit Manipulation
|
simple-clean-code-bit-manipulation-by-ab-5drc
|
Code\n\nvector<int> findArray(vector<int>& pref) {\n for(int i=pref.size()-1;i>0;i--){\n pref[i]=pref[i]^pref[i-1];}\n return pref;}\n
|
abhijeet5000kumar
|
NORMAL
|
2023-10-31T12:13:24.037506+00:00
|
2023-10-31T12:13:24.037540+00:00
| 63 | false |
# Code\n```\nvector<int> findArray(vector<int>& pref) {\n for(int i=pref.size()-1;i>0;i--){\n pref[i]=pref[i]^pref[i-1];}\n return pref;}\n```
| 2 | 0 |
['Array', 'Bit Manipulation', 'C++']
| 0 |
find-the-original-array-of-prefix-xor
|
dart solution fast and easy
|
dart-solution-fast-and-easy-by-beshoyfay-7vpp
|
\nclass Solution {\n List findArray(List pref) {\nif(pref.length<2)\n return pref;\n for(int i = pref.length-1;i>=1;i--)\n pref[i]
|
beshoyFayz
|
NORMAL
|
2023-10-31T11:30:34.909753+00:00
|
2023-10-31T11:30:34.909780+00:00
| 23 | false |
\nclass Solution {\n List<int> findArray(List<int> pref) {\nif(pref.length<2)\n return pref;\n for(int i = pref.length-1;i>=1;i--)\n pref[i] ^= pref[i-1]; \n return pref;\n }\n}
| 2 | 0 |
['Dart']
| 0 |
find-the-original-array-of-prefix-xor
|
2433. Find The Original Array of Prefix Xor
|
2433-find-the-original-array-of-prefix-x-n57v
|
\n# Code\n\nclass Solution:\n def findArray(self, pref: List[int]) -> List[int]:\n x = []\n res = 0\n for i in range(0,len(pref)):\n
|
satheeskumarb
|
NORMAL
|
2023-10-31T08:51:53.726963+00:00
|
2023-10-31T08:51:53.727012+00:00
| 62 | false |
\n# Code\n```\nclass Solution:\n def findArray(self, pref: List[int]) -> List[int]:\n x = []\n res = 0\n for i in range(0,len(pref)):\n if(i==0):\n x.append(pref[i])\n else:\n x.append(pref[i]^pref[i-1])\n return x\n\n \n```
| 2 | 0 |
['Python3']
| 0 |
find-the-original-array-of-prefix-xor
|
Python3 Readable Short solution
|
python3-readable-short-solution-by-wanni-3t7r
|
Intuition\nSame intuition as given in the Hints section\n\n# Approach\nMake an extra array arr containing the first element of prev. Then append prev[i] ^ prev[
|
wannix
|
NORMAL
|
2023-10-31T05:41:04.243332+00:00
|
2023-10-31T05:41:04.243364+00:00
| 33 | false |
# Intuition\nSame intuition as given in the Hints section\n\n# Approach\nMake an extra array `arr` containing the first element of `prev`. Then append `prev[i] ^ prev[i-1]` to the array in a loop from `1` to `N-1`. \n\n# Complexity\n- Time complexity:\nO(N) as it implements a single for loop from 1 to N-1\n\n- Space complexity:\nO(N) as it takes an extra array of length N\n\n# Code\n```\nclass Solution:\n def findArray(self, pref: List[int]) -> List[int]:\n arr = [pref[0]]\n for i in range(1, len(pref)):\n arr.append(pref[i] ^ pref[i - 1])\n return arr\n```
| 2 | 0 |
['Python3']
| 0 |
find-the-original-array-of-prefix-xor
|
Best Java Solution || Beats 100%
|
best-java-solution-beats-100-by-ravikuma-kkqa
|
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
|
ravikumar50
|
NORMAL
|
2023-10-31T04:46:36.243914+00:00
|
2023-10-31T04:46:36.243931+00:00
| 1,411 | 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[] findArray(int[] pref) {\n int n = pref.length;\n int arr[] = new int[n];\n arr[0] = pref[0];\n\n for(int i=1; i<n; i++){\n arr[i] = pref[i-1]^pref[i];\n }\n return arr;\n }\n}\n```
| 2 | 0 |
['Java']
| 1 |
find-the-original-array-of-prefix-xor
|
Revealing the Original Array: A Cumulative XOR Approach 🚀
|
revealing-the-original-array-a-cumulativ-gxm0
|
Intuition\n Describe your first thoughts on how to solve this problem. \nWhen I first looked at this problem, my initial thought was to make use of the property
|
hsakib8685
|
NORMAL
|
2023-10-31T03:53:17.760611+00:00
|
2023-10-31T03:53:17.760641+00:00
| 37 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWhen I first looked at this problem, my initial thought was to make use of the property of XOR: if ```a ^ b = c```, then ```a ^ c = b```. This property can be used to decipher the original array from the prefix XOR array.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nMy approach was to iterate through the prefix array and calculate the original array values cumulatively. I started by taking the first element as it is because ```pref[0]``` is equal to ```arr[0]```. For subsequent values, I applied the XOR operation between the previous original number and the current prefix value. This helped in uncovering the original numbers one by one and thus building the original array cumulatively.\n\n# Complexity\n- Time complexity: $$O(n)$$ (As we are iterating through the prefix array once)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$ (Since we are utilizing the input array to store the results and not using any extra space)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n#include <bits/stdc++.h>\nusing namespace std;\n#define ll long long\n#define db double\n#define pb push_back\n#define pi acos(-1.0)\n#define mod 1000000007\n\nclass Solution\n{\npublic:\n vector<int> findArray(vector<int> &pref)\n {\n int prevNum = pref[0];\n int n = pref.size();\n for (int i = 1; i < n; i++)\n {\n int temp = prevNum ^ pref[i];\n prevNum = pref[i];\n pref[i] = temp;\n }\n return pref;\n }\n};\n```
| 2 | 0 |
['Array', 'Bit Manipulation', 'C++']
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.