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
checking-existence-of-edge-length-limited-paths
Holy Moly !. Give it a try for this solution
holy-moly-give-it-a-try-for-this-solutio-9seg
Hint 1\nForget about multiple edges between two nodes. They are just to confuse. If we want the weight to be less than limitlimitlimit, just check with the mini
Ayush_Singh_610
NORMAL
2023-04-29T14:27:37.213623+00:00
2023-04-29T14:27:37.213667+00:00
210
false
# Hint 1\nForget about multiple edges between two nodes. They are just to confuse. If we want the weight to be less than limitlimitlimit, just check with the minimum weight. We can always traverse a\u2194ba \\leftrightarrow ba\u2194b via minimum weighted edge if minWeight<limitmin.\n\n# Hint 2\nNormal traversal from source to destination for each query will be TLE. What is the redundant work? If we could traverse 1\u22122\u22123\u22124 with limit=10, then we can also traverse from any source to destination pair in [1,2,3,4]with limit\u226510.\n\n# Hint 3\nSo, for a specific queries[i], assume there is a copy of the given graph but it has only those edges which has weight<limit. Then we can check if there is a path from source to destination, or in other words, whether source and destination belong to same component or not. What happens when we increase the limitlimitlimit?\n\n# Hint 4\nWhen we were able to traverse 1\u22122\u22123\u22124 with limit=10, suppose there was one edge 1\u21945 with weight=11, and we were not able to use it to reach 555. But if limitlimitlimit is increased to 12, then we can use it to go 1\u22125 and subsequently any source to destination pair in [1,2,3,4,5].\n\n# Hint 5\nWhen limit is increased, we can still use all the edges that were there in our copied graph. But we can use even more edges that has weight where oldLimit\u2264weight<newLimit. We can add these new edges that could not be used earlier, in our copied graph and check for a path again. To do this, we would like to have queries and edgeList sorted with weight or limit. But, before sorting queries, don\'t forget to store their original indices for final result array.\n\n# Hint 6\nLooks like we are still doing traversal in copied graph to check for path on same nodes again and again. How can we quickly check if two nodes belong to the same component in the copied graph? We can make Disjoint Sets of components and check for their parents (See [This](https://leetcode.com/discuss/general-discussion/1072418/Disjoint-Set-Union-(DSU)Union-Find-A-Complete-Guide/) if you want to learn DSU). For an increased limit, take union of those disjoint sets for those new edges.\n\n# Intuition & Approach\n\u2022 problem is to determine if there is a path between two nodes in an undirected graph such that each edge on the path has a distance strictly less than a given limit.\n\n\u2022 The input consists of the number of nodes, the edge list, and the queries.\n\n\u2022 The edge list is an array of arrays, where each sub-array represents an edge between two nodes and the distance between them.\n\n\u2022 The queries are an array of arrays, where each sub-array represents a query with two nodes and a limit.\n\n\u2022 The using the union-find algorithm to determine if there is a path between two nodes.\n\n\u2022 The union-find algorithm is used to group nodes into connected components.\n\n\u2022 First sorts the edges in the edge list by their distance in ascending order.\n\n\u2022 Then iterates over the sorted edges and performs a union operation on the nodes connected by the edge.\n\n\u2022 The union operation updates the parent and rank arrays to group the nodes into connected components.\n\n\u2022 Then iterates over the queries and checks if the two nodes are connected and if the distance between them is less than the given limit.\n\n\u2022 The isConnectedAndWithinLimit method uses the find method to determine if the two nodes are connected and if the distance between them is less than the given limit.\n\n\u2022 The find method uses the parent and weight arrays to find the root of the connected component and checks if the weight of the edge is less than the given limit.\n\n\u2022 The union method updates the parent, rank, and weight arrays to group the nodes into connected components and store the weight of the edge.\n\n\u2022 finally returns a boolean array where each element represents if there is a path between the two nodes in the corresponding query with edges less than the given limit.$ -->\n\n# Code\n```\nclass UnionFind:\n def __init__(self, size):\n self.parent = [i for i in range(size)]\n \n def union(self, a, b):\n self.parent[self.find(a)] = self.find(b)\n \n def find(self, a):\n if self.parent[a] != a:\n self.parent[a] = self.find(self.parent[a])\n return self.parent[a]\n\nclass Solution:\n def distanceLimitedPathsExist(self, n: int, edgeList: List[List[int]], queries: List[List[int]]) -> List[bool]:\n E = len(edgeList)\n Q = len(queries)\n uf = UnionFind(n)\n ans = [False] * Q\n for i in range(Q):\n queries[i].append(i)\n queries.sort(key=lambda x: x[2])\n edgeList.sort(key=lambda x: x[2])\n j = 0\n for i in range(Q):\n while j < E and edgeList[j][2] < queries[i][2]:\n uf.union(edgeList[j][0], edgeList[j][1])\n j += 1\n ans[queries[i][3]] = (uf.find(queries[i][0]) == uf.find(queries[i][1]))\n return ans\n\n\n"""\n# TLE and wrong ans\n\nclass Solution:\n def distanceLimitedPathsExist(self, n: int, edgeList: List[List[int]], queries: List[List[int]]) -> List[bool]:\n parents = defaultdict(lambda: None)\n sizes = defaultdict(int)\n \n def find(a):\n if a not in parents:\n parents[a] = a\n sizes[a] = 1\n return a\n\n root = a\n while parents[root] != root:\n root = parents[root]\n while parents[a] != a:\n nxt = parents[a]\n parents[a] = root\n a = nxt\n return root\n \n def union(a,b):\n roota = find(a)\n rootb = find(b)\n if roota == rootb:\n return\n if sizes[roota] > sizes[rootb]:\n sizes[roota] += sizes[rootb]\n sizes[rootb] = 0\n parents[rootb] = roota\n else:\n sizes[rootb] += sizes[roota]\n sizes[roota] = 0\n parents[roota] = rootb\n\n Q, E = len(queries), len(edgeList)\n\n #print(edgeList) \n edgeList.sort(key=lambda x: x[2])\n #print(edgeList)\n queries = sorted(((u,v,l,idx) for idx,(u,v,l) in enumerate(queries)), key=lambda x: x[2])\n #print(queries)\n\n res = [False] * Q\n e_idx = 0\n for p, q, l, i in queries:\n while e_idx < E and edgeList[e_idx][2] < l:\n u, v, _ = edgeList[e_idx]\n union(u, v)\n res[i] = find(p) == find(q)\n e_idx += 1\n return res\n"""\n```
1
0
['Array', 'Union Find', 'Graph', 'Sorting', 'Python3']
0
checking-existence-of-edge-length-limited-paths
Java Solution (Union Find ~ 100%)
java-solution-union-find-100-by-semotpan-wypy
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n- Sort edge list by lim
semotpan
NORMAL
2023-04-29T12:18:35.971572+00:00
2023-04-29T12:31:51.969119+00:00
399
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- Sort edge list by limit, to have min edge with min limit with a higher rank\n- Build Union Find components with limits\n- Query UF to find connected componets based on limit\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 boolean[] distanceLimitedPathsExist(int n, int[][] edgeList, int[][] queries) {\n var uf = new UF(n);\n Arrays.sort(edgeList, Comparator.comparingInt(a -> a[2]));\n\n for (var e : edgeList)\n uf.union(e[0], e[1], e[2]);\n \n var answer = new boolean[queries.length];\n for (var i = 0; i < queries.length; ++i)\n answer[i] = uf.connected(queries[i][0], queries[i][1], queries[i][2]);\n\n return answer;\n }\n}\n\nclass UF {\n\n private final int[] id, rank, limits;\n\n UF(int N) {\n this.id = new int[N];\n this.rank = new int[N];\n this.limits = new int[N];\n\n for (var i = 0; i < N; ++i)\n id[i] = i;\n }\n\n void union(int p, int q, int limit) {\n var pId = find(p);\n var qId = find(q);\n\n if (pId == qId)\n return;\n\n if (rank[pId] < rank[qId]) {\n id[pId] = qId;\n limits[pId] = limit;\n } else if (rank[pId] > rank[qId]) {\n id[qId] = pId;\n limits[qId] = limit;\n } else {\n id[qId] = pId;\n limits[qId] = limit;\n rank[pId]++;\n }\n }\n\n boolean connected(int p, int q, int limit) {\n return find(p, limit) == find(q, limit);\n }\n\n private int find(int p) {\n while (p != id[p])\n p = id[p];\n \n return p;\n }\n\n private int find(int p, int limit) {\n while (p != id[p] && limits[p] < limit)\n p = id[p];\n \n return p;\n }\n}\n```
1
0
['Union Find', 'Java']
0
checking-existence-of-edge-length-limited-paths
C# Solution | Union Find | Sorting
c-solution-union-find-sorting-by-anshulg-8fz4
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
anshulgarg904
NORMAL
2023-04-29T08:49:30.561027+00:00
2023-04-29T08:49:30.561068+00:00
112
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\npublic class Solution {\n public bool[] DistanceLimitedPathsExist(int n, int[][] edgeList, int[][] queries) {\n int edgesCount = edgeList.Length, queriesCount = queries.Length;\n DSU dsu = new DSU(n);\n\n for (int i = 0; i < queriesCount; i++) \n queries[i] = new int[]{queries[i][0], queries[i][1], queries[i][2], i}; \n\n Array.Sort(queries, (a, b) => a[2] - b[2]);\n Array.Sort(edgeList, (a, b) => a[2] - b[2]);\n bool[] res = new bool[queriesCount];\n\n for (int i = 0, j = 0; i < queriesCount; i++) {\n var query = queries[i];\n\n while (j < edgesCount && edgeList[j][2] < queries[i][2])\n dsu.union(edgeList[j][0], edgeList[j++][1]);\n\n res[queries[i][3]] = dsu.find(queries[i][0]) == dsu.find(queries[i][1]);\n }\n\n return res;\n }\n\n class DSU {\n public int[] parent;\n\n public DSU(int n) {\n parent = new int[n];\n\n for (int i = 0; i < n; i++) parent[i] = i;\n }\n\n public int find(int x) {\n if (parent[x] != x) parent[x] = find(parent[x]);\n return parent[x];\n }\n\n public void union(int x, int y) {\n parent[find(x)] = parent[find(y)];\n }\n }\n}\n```
1
0
['Array', 'Union Find', 'Graph', 'Sorting', 'C#']
0
checking-existence-of-edge-length-limited-paths
JAVA || Union Find || Disjoint Set
java-union-find-disjoint-set-by-da_arya-dbye
\nclass Solution {\n \n int[] parent;\n int[] rank;\n \n Solution(){\n int n = 100004;\n parent = new int[n];\n rank = new i
DA_ARYA
NORMAL
2023-04-29T08:37:27.730749+00:00
2023-04-29T08:37:27.730792+00:00
167
false
```\nclass Solution {\n \n int[] parent;\n int[] rank;\n \n Solution(){\n int n = 100004;\n parent = new int[n];\n rank = new int[n];\n for(int i = 0;i<n;i++)\n parent[i] = i;\n }\n \n public void union(int u, int v){\n int pu = findParent(u), pv = findParent(v);\n int ru = rank[pu] , rv = rank[pv];\n \n if(pu == pv)\n return;\n if(ru < rv){\n parent[pu] = pv;\n }else if(rv < ru)\n parent[pv] = pu;\n else{\n parent[pu] = pv;\n rank[pv]++;\n }\n return;\n }\n \n public int findParent(int u){\n if( u != parent[u])\n parent[u] = findParent(parent[u]);\n return parent[u] ;\n }\n \n public boolean connected(int u, int v){\n return findParent(u) == findParent(v);\n }\n \n public void sort(int[][] query){\n Arrays.sort(query, new Comparator<int[] >(){\n @Override\n public int compare(int[] first, int[] second){\n return first[2] - second[2]; \n }\n });\n }\n \n public boolean[] distanceLimitedPathsExist(int n, int[][] edgeList, int[][] queries) {\n int no_of_query = queries.length;\n int[][] query = new int[no_of_query][4];\n int i = 0, j = 0;\n for( i =0 ;i < no_of_query ; i++){\n query[i][0] = queries[i][0];\n query[i][1] = queries[i][1];\n query[i][2] = queries[i][2];\n query[i][3] = i;\n }\n\n sort(query);\n sort(edgeList);\n \n int currentEdge = 0;\n int edges = edgeList.length;\n boolean[] ans = new boolean[no_of_query];\n for(i = 0;i < no_of_query ; i++){\n int u = query[i][0], v = query[i][1], limit = query[i][2], ind = query[i][3];\n while( currentEdge < edges && edgeList[currentEdge][2] < limit){\n int p = edgeList[currentEdge][0], q = edgeList[currentEdge][1] ;\n union(p,q);\n currentEdge++;\n }\n ans[ind] = findParent(u) == findParent(v);\n }\n return ans;\n }\n}\n```
1
0
['Union Find', 'Graph', 'Sorting', 'Java']
0
checking-existence-of-edge-length-limited-paths
Clean And Simple Code
clean-and-simple-code-by-rajat_kapoor-zp0p
Complexity\n- Time complexity: O(nlogn)\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
Rajat_Kapoor
NORMAL
2023-04-29T06:39:25.672086+00:00
2023-04-29T06:39:25.672136+00:00
353
false
# Complexity\n- Time complexity: O(nlogn)\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```\nclass Solution {\n public boolean[] distanceLimitedPathsExist(int n, int[][] edgeList, int[][] queries) {\n int nn = edgeList.length;\n int len = queries.length;\n boolean res[] = new boolean[len];\n int arr[][] = new int[len][4];\n for(int i = 0;i<len;i++){\n arr[i][0] = queries[i][0];\n arr[i][1] = queries[i][1];\n arr[i][2] = queries[i][2];\n arr[i][3] = i;\n }\n Arrays.sort(arr,(a,b) -> a[2] - b[2]);\n Arrays.sort(edgeList,(a,b) -> a[2] - b[2]);\n DSU obj = new DSU(n);\n int j = 0;\n for(int i = 0;i<len;i++){\n int a = arr[i][0];\n int b = arr[i][1];\n int dis = arr[i][2];\n int idx = arr[i][3];\n while(j<nn && edgeList[j][2] < dis){\n obj.union(edgeList[j][0], edgeList[j++][1]);\n }\n res[idx] = obj.findPar(a) == obj.findPar(b);\n }\n return res;\n }\n}\nclass DSU{\n int par[];\n int rank[];\n DSU(int n){\n par = new int[n];\n rank = new int[n];\n for(int i = 0;i<n;i++){\n par[i] = i;\n }\n }\n int findPar(int n){\n if(n == par[n]) return n;\n return par[n] = findPar(par[n]);\n }\n void union(int u, int v){\n u = findPar(u);\n v = findPar(v);\n if(rank[u] < rank[v]){\n par[u] = v;\n }else if(rank[v] < rank[u]){\n par[v] = u;\n }else{\n par[v] = u;\n rank[u]++;\n }\n }\n}\n```
1
0
['Array', 'Union Find', 'Graph', 'Sorting', 'Java']
0
checking-existence-of-edge-length-limited-paths
Brute Force To Optimize|| Disjoint Set
brute-force-to-optimize-disjoint-set-by-ok6z8
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
shahid_2048
NORMAL
2023-04-29T05:23:41.902686+00:00
2023-04-29T05:23:41.902733+00:00
74
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 f(int u,vector<int>&par)\n {\n if(par[u]==u) return u;\n return par[u]=f(par[u],par);\n }\n void unionBySize(int u,int v,vector<int>&par,vector<int>&sz)\n {\n int paru=f(u,par);\n int parv=f(v,par);\n if(paru==parv) return;\n if(sz[paru]>sz[parv])\n {\n par[parv]=paru;\n sz[paru]+=sz[parv];\n }\n else\n {\n par[paru]=parv;\n sz[parv]+=sz[paru];\n }\n }\n\n static bool cmp(vector<int>&a,vector<int>&b)\n {\n return a[2]<b[2];\n }\n vector<bool> distanceLimitedPathsExist(int n, vector<vector<int>>& edgeList, vector<vector<int>>& queries) {\n vector<int>par;\n vector<int>sz(n,0);\n vector<bool>ans(queries.size(),0);\n for(int i=0;i<n;i++) par.push_back(i);\n for(int i=0;i<queries.size();i++)\n queries[i].push_back(i);\n sort(queries.begin(),queries.end(),cmp);\n sort(edgeList.begin(),edgeList.end(),cmp);\n int i=0;\n for(auto v:queries)\n {\n int lim=v[2];\n while(i<edgeList.size())\n {\n if(edgeList[i][2]<lim)\n unionBySize(edgeList[i][0],edgeList[i][1],par,sz);\n else break;\n i++;\n }\n if(f(v[0],par)==f(v[1],par)) ans[v[3]]=1;\n }\n return ans;\n }\n};\n```
1
1
['Union Find', 'Graph', 'Sorting', 'Shortest Path', 'C++']
0
checking-existence-of-edge-length-limited-paths
Distance Limited Paths Exist using Disjoint Set Union in C++// Easy to Understand
distance-limited-paths-exist-using-disjo-1cfy
Intuition\nTo solve the problem, we can use Kruskal\'s algorithm to find the minimum spanning tree of the given graph, and then use this tree to answer the quer
Red-hawk
NORMAL
2023-04-29T04:16:37.685261+00:00
2023-04-29T04:18:23.010397+00:00
48
false
# Intuition\nTo solve the problem, we can use Kruskal\'s algorithm to find the minimum spanning tree of the given graph, and then use this tree to answer the queries.\n\nWe first sort the edges of the graph in non-decreasing order of their weights. We then pick the edges one by one, and add them to the tree if they do not create a cycle. To check if an edge creates a cycle, we can use a disjoint set data structure. We then process the queries one by one, and check if the two nodes of each query are connected in the minimum spanning tree and the distance between them is less than the given limit.\n\nIf the two nodes of a query are connected in the minimum spanning tree and the distance between them is less than the given limit, then we mark the answer for this query as true, otherwise we mark it as false. Finally, we return the array of answers for all the queries.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Sort the edgeList in non-descending order of their weights.\n2. For each query in queries, sort the edgeList up to the limit of the query.\n3. Use a modified version of Dijkstra\'s algorithm to find a path between the two nodes of each query.\n4. In the modified Dijkstra\'s algorithm, stop exploring the neighboring nodes once the weight of the edge between the current node and a neighboring node exceeds the limit of the query.\n5. If a path is found between the two nodes of a query, mark the query as true in the answer array. Otherwise, mark it as false.\n6. Return the answer array.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n- The TimeComplexity O((m+n) log m), where m is the number of edges in edgeList and n is the number of queries in queries. This is because the edges are sorted using quicksort, which has an average-case time complexity of O(m log m), and the queries are also sorted, which takes O(n log n) time. \n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n- The space complexity of the code is O(m+n), where m is the number of edges in edgeList and n is the number of queries in queries. \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n\n...............................................................................................................\nPLEASE UPVOTE IF YOU FIND THAT IT HELPED YOU ...............................................................................................................\n\n# Code\n```\nclass DisjointSet{\n public:\n vector<int>size;\n vector<int>head;\n DisjointSet(int n){\n size.resize(n,1);\n head.resize(n);\n for(int i=0;i<n;i++)head[i]=i;\n }\n \n int findUpar(int node){\n if(node==head[node])return node;\n\n return head[node]=findUpar(head[node]);\n }\n\n void UnionBySize(int u,int v){\n int jms=findUpar(u);\n int rms=findUpar(v);\n if(jms==rms)return ;\n if(size[jms]<size[rms]){\n head[jms]=rms;\n size[rms]+=size[jms];\n }\n else{\n head[rms]=jms;\n size[jms]+=size[rms];\n }\n \n }\n};\n\nclass Solution {\npublic:\n static bool cmp(vector<int>&a,vector<int>&b){\n return a[2]<b[2];\n }\n vector<bool> distanceLimitedPathsExist(int n, vector<vector<int>>& edgeList, vector<vector<int>>& queries) {\n DisjointSet ds(n);\n \n for(int i=0;i<queries.size();i++){\n queries[i].push_back(i);\n }\n vector<bool>ans(queries.size(),false);\n sort(queries.begin(),queries.end(),cmp);\n sort(edgeList.begin(),edgeList.end(),cmp);\n int j=0;\n for(int i=0;i<queries.size();i++){\n while(j<edgeList.size()&&edgeList[j][2]<queries[i][2]){\n ds.UnionBySize(edgeList[j][0],edgeList[j][1]);\n j++;\n }\n if(ds.findUpar(queries[i][0])==ds.findUpar(queries[i][1])){\n ans[queries[i][3]]=true;\n }\n }\n return ans;\n\n }\n};\n\n\n\n```
1
0
['C++']
0
checking-existence-of-edge-length-limited-paths
Python: build graph from smallest dist to bigger
python-build-graph-from-smallest-dist-to-h8ji
Sort queries by limit\n2. Sort edges by dist\n3. Iterate over queries as l:\n3.1. Connect all nodes that have edges with d < l. \n3.2. Check the query\'s p and
vokasik
NORMAL
2023-04-29T02:18:55.546471+00:00
2023-05-01T20:29:29.479815+00:00
61
false
1. Sort *queries* by `l`imit\n2. Sort *edges* by `d`ist\n3. Iterate over `queries` as `l`:\n3.1. Connect all nodes that have edges with `d` < `l`. \n3.2. Check the query\'s `p` and `q` belong to the same `component`.\n4. Repeat for all queries\n\n```\nclass Solution:\n def distanceLimitedPathsExist(self, n: int, edgeList: List[List[int]], queries: List[List[int]]) -> List[bool]:\n parents = defaultdict(lambda: None)\n sizes = defaultdict(int)\n \n def find(a):\n if a not in parents:\n parents[a] = a\n sizes[a] = 1\n return a\n\n root = a\n while parents[root] != root:\n root = parents[root]\n\n while parents[a] != a:\n nxt = parents[a]\n parents[a] = root\n a = nxt\n \n return root\n \n def union(a,b):\n roota = find(a)\n rootb = find(b)\n \n if roota == rootb:\n return\n \n if sizes[roota] > sizes[rootb]:\n sizes[roota] += sizes[rootb]\n sizes[rootb] = 0\n parents[rootb] = roota\n else:\n sizes[rootb] += sizes[roota]\n sizes[roota] = 0\n parents[roota] = rootb\n \n Q, E = len(queries), len(edgeList)\n \n edgeList.sort(key=lambda x: x[2])\n queries = sorted(((u,v,l,i) for i,(u,v,l) in enumerate(queries)), key=lambda x: x[2])\n \n res = [False] * Q\n e_idx = 0\n for p, q, l, i in queries:\n while e_idx < E and edgeList[e_idx][2] < l:\n u, v, _ = edgeList[e_idx]\n union(u, v)\n e_idx += 1\n res[i] = find(p) == find(q)\n return res\n```
1
0
['Graph', 'Python']
1
checking-existence-of-edge-length-limited-paths
Dijkstra's Algorithm || C++ Easy Solution || Beginner Friendly
dijkstras-algorithm-c-easy-solution-begi-kksr
\n\n# Code\n\nclass Solution {\npublic:\n vector<bool> distanceLimitedPathsExist(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {\n
iamsanko
NORMAL
2023-04-29T02:16:20.477700+00:00
2023-04-29T02:16:20.477742+00:00
293
false
\n\n# Code\n```\nclass Solution {\npublic:\n vector<bool> distanceLimitedPathsExist(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {\n for(int i = 0; i<=n; i++) parent[i] = i;\n \n\t\t// Sorting the edges array based on dist of each pair of node. \n sort(edges.begin(),edges.end(),[](vector<int>&a, vector<int>&b){\n if(a[2]<b[2]) return true;\n return false;\n });\n\n\t\t// We will need the indices of query elements coz after sorting, the order will change. \n\t\t// So we push the index in the same element vector of query.\n for(int i = 0; i<queries.size(); i++) queries[i].push_back(i);\n\t\t\t\n\t\t// Sorting queries based on limits. \n sort(queries.begin(),queries.end(),[](vector<int>&a,vector<int>&b){\n if(a[2]<b[2]) return true;\n return false;\n });\n \n vector <bool> ans(queries.size(),false);\n int idx = 0;\n for(int i = 0; i<queries.size(); i++){\n // Here we loop on edges vector and join the two nodes having dist < curr_limit.\n\t\t\twhile(idx<edges.size() and edges[idx][2]<queries[i][2]){\n join(edges[idx][0],edges[idx][1]);\n idx++;\n }\n\t\t\t// If the two nodes of current query has same godfather, we set this queries ans as true\n if(find(parent[queries[i][0]]) == find(parent[queries[i][1]])) ans[queries[i][3]] = true;\n }\n return ans;\n }\nprotected:\n int find(int x){\n if(parent[x]==x) return x;\n return parent[x] = find(parent[x]);\n }\n void join(int a, int b){\n a = find(a);\n b = find(b);\n \n if(a!=b) parent[b] = a;\n }\n};\n```
1
0
['Array', 'Math', 'Union Find', 'Sorting', 'C++']
1
checking-existence-of-edge-length-limited-paths
C Union Find with explanation
c-union-find-with-explanation-by-jerrych-kz2k
\n\n/**\n * Note: The returned array must be malloced, assume caller calls free().\n */\nint* root;\nint** qcopy;\n\nint find(int x) {\n if(x==root[x])\n
JerryChiang87
NORMAL
2023-04-29T02:05:22.793944+00:00
2023-04-29T02:05:22.793976+00:00
78
false
\n```\n/**\n * Note: The returned array must be malloced, assume caller calls free().\n */\nint* root;\nint** qcopy;\n\nint find(int x) {\n if(x==root[x])\n return x;\n else\n return root[x] = find(root[x]);\n}\n\nint cmp(void const* a, void const* b) {\n return (*(int**)a)[2] - (*(int**)b)[2];\n}\n\nint cmp2(void const* a, void const* b) {\n return qcopy[*(int*)a][2] - qcopy[*(int*)b][2];\n}\n\nbool* distanceLimitedPathsExist(int n, int** edgeList, int edgeListSize, int* edgeListColSize, int** queries, int queriesSize, int* queriesColSize, int* returnSize){\n *returnSize = queriesSize;\n int i;\n //init union set\n root = (int*)malloc(sizeof(int)*n);\n for (i = 0; i < n; i++)\n root[i] = i;\n //init answer array\n bool* ans = (bool*)malloc(sizeof(bool) * queriesSize);\n\n int idx[queriesSize];//index of queries\n for (i = 0; i < queriesSize; ++i)\n idx[i] = i;\n\n qcopy = queries;\n qsort(idx, queriesSize, sizeof(int), cmp2);//sort the index base on the queries limit length\n qsort(edgeList, edgeListSize, sizeof(int*), cmp); //sort by edge distance\n \n int j=0;\n for (i = 0; i < queriesSize; ++i) {\n int curr = idx[i];//current queries index in sorted queries\n int len = queries[curr][2];//limit length\n \n //update union set when distance less than limit \n while(j < edgeListSize && edgeList[j][2] < len){\n int a = find(edgeList[j][0]);\n int b = find(edgeList[j][1]);\n root[b] = a;\n j++;\n }\n\n //check if nodes has same root\n if (find(queries[curr][0]) == find(queries[curr][1]))\n ans[curr] = 1;\n else \n ans[curr] = 0;\n }\n\n return ans;\n}\n```
1
0
['C']
0
checking-existence-of-edge-length-limited-paths
[JS] Union Find
js-union-find-by-mdesanker-cocq
Approach\nAfter sorting query and edge arrays, we iterate through queries and connect all edges that have a distance below the limit of the current query. Then
quasi00
NORMAL
2023-04-29T01:52:09.848440+00:00
2023-04-29T01:52:09.848467+00:00
80
false
# Approach\nAfter sorting query and edge arrays, we iterate through queries and connect all edges that have a distance below the limit of the current query. Then we check whether the two nodes of the query are connected.\n\n# Complexity\n- Time complexity:\n$$O(n + eloge + qlogq + (e + q))$$ - n to initialize parent and rank arrays, eloge and qlogq to sort edgeList and queriesWithIndex, e + q for union find on every edge and query\n\n- Space complexity:\n$$O(n + q)$$ - n for parent and rank arrays, q for queriesWithIndex\n\n# Code\n```\nvar distanceLimitedPathsExist = function(n, edgeList, queries) {\n const par = [];\n for (let i = 0; i < n; i++) par.push(i);\n const rank = new Array(n).fill(1);\n\n function find(n) {\n if (n === par[n]) return n;\n return par[n] = find(par[n]);\n }\n\n function union(n1, n2) {\n let p1 = find(n1), p2 = find(n2);\n if (p1 === p2) return false;\n if (rank[p1] > rank[p2]) {\n par[p2] = p1;\n rank[p1] += rank[p2];\n } else {\n par[p1] = p2;\n rank[p2] += rank[p1];\n }\n return true;\n }\n\n // add index to queries so we know where it goes in result array after sorting\n const queriesWithIndex = [];\n for (let i = 0; i < queries.length; i++) {\n queriesWithIndex[i] = [...queries[i], i];\n }\n\n // sort new queries array and edgeList by distance\n queriesWithIndex.sort((a, b) => a[2] - b[2]);\n edgeList.sort((a, b) => a[2] - b[2]);\n\n const res = new Array(queries.length);\n\n let edgesIndex = 0;\n // iterate through queries, connecting all edges that are below the limit\n for (let [p, q, limit, i] of queriesWithIndex) {\n while (edgesIndex < edgeList.length && edgeList[edgesIndex][2] < limit) {\n union(edgeList[edgesIndex][0], edgeList[edgesIndex][1]);\n edgesIndex++;\n }\n // check if the two query edges are connected\n res[i] = (find(p) === find(q));\n }\n return res;\n}\n// TC: O(n + eloge + qlogq + (e + q)) n to initialize parent and rank arrays, eloge and qlogq to sort edgeList and queriesWithIndex, e + q for union find\n// SC: O(n + q) n for parent and rank arrays, q for queriesWithIndex\n```
1
0
['JavaScript']
0
checking-existence-of-edge-length-limited-paths
Java Union Find Solution
java-union-find-solution-by-skipper97-5iuk
Intuition\n Describe your first thoughts on how to solve this problem. \nSorting the Queries + Computing UNION-FIND of the Edgelist via Sorted Approach.\n# Appr
sKipper97
NORMAL
2023-04-29T01:46:41.607915+00:00
2023-04-29T01:46:41.607948+00:00
36
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSorting the Queries + Computing UNION-FIND of the Edgelist via Sorted Approach.\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 boolean[] distanceLimitedPathsExist(int n, int[][] edgeList, int[][] queries) {\n int[][] modifiedQueries = new int[queries.length][4];\n for(int i=0;i<queries.length;i++) {\n modifiedQueries[i][0] = queries[i][0];\n modifiedQueries[i][1] = queries[i][1];\n modifiedQueries[i][2] = queries[i][2];\n modifiedQueries[i][3] = i;\n }\n Arrays.sort(modifiedQueries,(a, b) -> a[2] - b[2]);\n Arrays.sort(edgeList, (a, b) -> a[2] - b[2]);\n int i = 0, j = 0;\n boolean[] answer = new boolean[modifiedQueries.length];\n DisjointSet disjointSet = new DisjointSet(n);\n\n while(i<modifiedQueries.length) {\n while(j < edgeList.length && edgeList[j][2] < modifiedQueries[i][2]) {\n disjointSet.union(edgeList[j][0], edgeList[j][1]);\n j++;\n }\n answer[modifiedQueries[i][3]] = disjointSet.findParent(modifiedQueries[i][0]) == disjointSet.findParent(modifiedQueries[i][1]);\n i++;\n }\n return answer;\n }\n}\n\nclass DisjointSet {\n\n private int[] parent;\n private int[] rank;\n\n public DisjointSet(int n) {\n this.parent = new int[n];\n this.rank = new int[n];\n for(int i=1;i<n;i++) {\n this.parent[i] = i;\n }\n }\n\n public int findParent(int node) {\n if(this.parent[node]!=node) this.parent[node] = findParent(this.parent[node]);\n return this.parent[node];\n }\n\n public void union(int u, int v) {\n int uPar = findParent(u);\n int vPar = findParent(v);\n\n if(uPar == vPar) return;\n if(this.rank[uPar] < this.rank[vPar]) this.parent[uPar] = vPar;\n else if(this.rank[vPar] < this.rank[uPar]) this.parent[vPar] = uPar;\n else {\n this.parent[uPar] = vPar;\n this.rank[vPar]++;\n }\n }\n\n}\n```
1
0
['Java']
0
checking-existence-of-edge-length-limited-paths
Simple Javascript solution
simple-javascript-solution-by-kamalbhera-94tq
\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
kamalbhera
NORMAL
2023-04-29T01:24:24.440760+00:00
2023-04-29T01:24:24.440787+00:00
188
false
\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/**\n * @param {number} n\n * @param {number[][]} edgeList\n * @param {number[][]} queries\n * @return {boolean[]}\n */\nvar distanceLimitedPathsExist = function(n, edgeList, queries) {\n let index = new Array(n).fill().map((_,i) => i);\n let keys = new Array(queries.length).fill().map((_,i) => i)\n let result = new Array(queries.length), j = 0\n\n const find = (x) => x !== index[x] ? index[x] = find(index[x]) : index[x]\n const union = (x,y) => index[find(x)] = find(y)\n edgeList.sort((a,b) => a[2] - b[2])\n keys.sort((a,b) => queries[a][2] - queries[b][2])\n\n for (let i of keys) {\n let [a,b,c] = queries[i]\n while (edgeList[j]?.[2] < c) union(edgeList[j][0], edgeList[j++][1])\n result[i] = find(a) === find(b)\n }\n return result\n};\n```
1
0
['JavaScript']
0
checking-existence-of-edge-length-limited-paths
Python3 Solution
python3-solution-by-motaharozzaman1996-669d
\n\nclass UnionFind:\n def __init__(self, N: int):\n self.parent = list(range(N))\n self.rank = [1] * N\n\n def find(self, p: int) -> int:\n
Motaharozzaman1996
NORMAL
2023-04-29T01:17:06.377967+00:00
2023-04-29T01:17:06.378004+00:00
412
false
\n```\nclass UnionFind:\n def __init__(self, N: int):\n self.parent = list(range(N))\n self.rank = [1] * N\n\n def find(self, p: int) -> int:\n if p != self.parent[p]:\n self.parent[p] = self.find(self.parent[p])\n return self.parent[p]\n\n def union(self, p: int, q: int) -> bool:\n prt, qrt = self.find(p), self.find(q)\n if prt == qrt: return False \n if self.rank[prt] > self.rank[qrt]: \n prt, qrt = qrt, prt \n self.parent[prt] = qrt \n self.rank[qrt] += self.rank[prt] \n return True \n\n\nclass Solution:\n def distanceLimitedPathsExist(self, n: int, edgeList: List[List[int]], queries: List[List[int]]) -> List[bool]:\n queries = sorted((w, p, q, i) for i, (p, q, w) in enumerate(queries))\n edgeList = sorted((w, u, v) for u, v, w in edgeList)\n \n uf = UnionFind(n)\n \n ans = [None] * len(queries)\n ii = 0\n for w, p, q, i in queries: \n while ii < len(edgeList) and edgeList[ii][0] < w: \n _, u, v = edgeList[ii]\n uf.union(u, v)\n ii += 1\n ans[i] = uf.find(p) == uf.find(q)\n return ans \n```
1
0
['Python', 'Python3']
0
checking-existence-of-edge-length-limited-paths
Python disjoint-set union
python-disjoint-set-union-by-mjgallag-kvi1
python []\nclass DSU:\n def __init__(self, n):\n self.parent = list(range(n))\n self.rank = [0] * n\n\n def find(self, x):\n if self.
mjgallag
NORMAL
2023-04-29T00:30:04.453247+00:00
2023-04-29T00:32:23.864404+00:00
130
false
```python []\nclass DSU:\n def __init__(self, n):\n self.parent = list(range(n))\n self.rank = [0] * n\n\n def find(self, x):\n if self.parent[x] != x:\n self.parent[x] = self.find(self.parent[x])\n return self.parent[x]\n\n def union(self, x, y):\n x_root, y_root = self.find(x), self.find(y)\n if x_root == y_root:\n return\n if self.rank[x_root] < self.rank[y_root]:\n x_root, y_root = y_root, x_root\n self.parent[y_root] = x_root\n if self.rank[x_root] == self.rank[y_root]:\n self.rank[x_root] += 1\n\n\nclass Solution:\n def distanceLimitedPathsExist(self, n: int, edges: List[List[int]], queries: List[List[int]]) -> List[bool]:\n queries = [[i] + q for i, q in enumerate(queries)]\n queries.sort(key=lambda x: x[3])\n edges.sort(key=lambda x: x[2])\n dsu = DSU(n)\n res = [0] * len(queries)\n j = 0\n for i, u, v, lim in queries:\n while j < len(edges) and edges[j][2] < lim:\n p, q = edges[j][:2]\n dsu.union(p, q)\n j += 1\n res[i] = dsu.find(u) == dsu.find(v)\n return res\n\n```
1
0
['Union Find', 'Sorting', 'Python', 'Python3']
0
checking-existence-of-edge-length-limited-paths
Python, UnionFind, with comments
python-unionfind-with-comments-by-valero-3br1
Sort both edges and queries by distance. For each query connect only nodes closer than the query threshold. All further queries would reuse previous connected g
valerom
NORMAL
2022-07-07T21:03:14.653094+00:00
2022-07-08T04:09:36.265566+00:00
57
false
Sort both edges and queries by distance. For each query connect only nodes closer than the query threshold. All further queries would reuse previous connected graph with possibly adding some own edges.\n\ntime: O(N log(N) + M log(M)) space: O(N)\n\n```\n# standard UnionFind implementation\nclass UnionFind:\n def __init__(self, n):\n self.roots = [i for i in range(n)]\n self.ranks = [1] * n\n #self.sizes = [1] * n\n #self.count = n\n\n def find(self, x):\n root = self.roots[x]\n if root != self.roots[root]:\n self.roots[x] = self.find(root) \n return self.roots[x]\n\n def union(self, x, y):\n rootx = self.find(x)\n rooty = self.find(y)\n if rootx != rooty:\n if self.ranks[rootx] > self.ranks[rooty]:\n self.roots[rooty] = rootx\n #self.sizes[rootx] += self.sizes[rooty]\n elif self.ranks[rootx] < self.ranks[rooty]:\n self.roots[rootx] = rooty\n #self.sizes[rooty] += self.sizes[rootx]\n else:\n self.roots[rooty] = rootx\n #self.sizes[rootx] += self.sizes[rooty]\n self.ranks[rootx] += 1\n #self.count -= 1\n\n def connected(self, x, y):\n return self.find(x) == self.find(y)\n \n #def getCount(self):\n # return self.count\n \n #def getCompSize(self, x):\n # return self.sizes[x]\n \nclass Solution:\n def distanceLimitedPathsExist(self, n: int, edgeList: List[List[int]], queries: List[List[int]]) -> List[bool]:\n \n m = len(queries)\n # sort edges by distance\n edgeList.sort(key=lambda x: x[2])\n # sort queries added their indexes by distance\n idx_queries = sorted(zip(queries, range(m)), key=lambda x: x[0][2])\n \n res = [False] * m\n edge_idx = 0\n \n uf = UnionFind(n + 1)\n # review all queries in acsending order\n for (u, v, t), idx in idx_queries:\n # add only edges which are less than the current query threshold\n # only those edges may be reachable for this query\n\t\t\t# they will also automatically be reachable for all further queries\n while edge_idx < len(edgeList) and edgeList[edge_idx][2] < t:\n # connect nodes\n uf.union(edgeList[edge_idx][0], edgeList[edge_idx][1])\n edge_idx += 1\n # see if the query nodes connected\n res[idx] = uf.connected(u, v)\n \n return res\n```
1
0
[]
0
checking-existence-of-edge-length-limited-paths
[C++] || Disjoint Set Union Data Structure
c-disjoint-set-union-data-structure-by-r-6djn
Sort queries based on limits .\n\n Sort edgeList based on weights.\n\n Find lower_bound of limit in edgeList . This indicates that upto idx index all the weighs
rahul921
NORMAL
2022-06-12T10:17:17.425941+00:00
2022-06-12T10:23:14.088774+00:00
204
false
* Sort queries based on limits .\n\n* Sort edgeList based on weights.\n\n* Find lower_bound of limit in edgeList . This indicates that upto `idx` index all the weighs in edgesList will be **strictly smaller** than `limit`.\n\n* For all the connections in edgeList make components/sets using DSU. (DSU is the best data strcuture for this purpose).\n\n* If Two elements come under a common set , then this shows that every edge in their path is strictly smalller than `limit`.\n\n\n\n\n```\nclass DSU{\nprivate:\n int n ; \n vector<int> parent, rank ;\n \npublic:\n DSU(int n){\n this->n = n ;\n parent.resize(n);\n iota(begin(parent),end(parent),0);\n rank.resize(n,1) ;\n }\n \n int find_parent(int node){\n if(node == parent[node]) return node ;\n return parent[node] = find_parent(parent[node]) ;\n }\n void Union(int u , int v){\n int U = find_parent(u) , V = find_parent(v) ;\n if(U == V) return ;\n if(rank[U] < rank[V]) swap(U,V) ;\n rank[U] += rank[V] ;\n parent[V] = U ;\n }\n \n};\n\nstruct cmp{\n bool operator()(const vector<int> &v1 , const vector<int> &v2){\n return v1[2] < v2[2] ;\n }\n};\n\nclass Solution {\npublic:\n \n vector<bool> distanceLimitedPathsExist(int n, vector<vector<int>>& edgeList, vector<vector<int>>& queries) {\n DSU dsu(n) ;\n vector<bool> ans(queries.size(),false) ;\n for(int i = 0 ; i < queries.size() ; ++i ) queries[i].push_back(i) ;\n \n sort(begin(queries),end(queries),[&](const vector<int> &v1 ,const vector<int> &v2)->bool{\n return v1[2] < v2[2] ; \n });\n sort(begin(edgeList),end(edgeList),[&](const vector<int> &v1 , const vector<int> &v2)->bool{\n return v1[2] < v2[2] ; \n });\n \n // for(auto &x : edgeList) cout << x[2] << " " ; cout << endl ;\n // for(auto &x : queries) cout << x[2] << " " ; cout << endl ;\n \n int prev = 0 ;\n for(auto &x : queries){\n int p = x[0] , q = x[1] , limit = x[2] , i = x[3] ;\n\t\t\t// to make sure comparision is done based on 2nd index in edgeList form a custom comparator cmp\n int idx = lower_bound(begin(edgeList) + prev , end(edgeList),vector<int>{INT_MIN,INT_MIN,limit},cmp()) - begin(edgeList) - 1 ;\n \n for(int j = prev ; j <= idx ; ++j ){\n //cout << j << endl ;\n int u = edgeList[j][0] , v = edgeList[j][1] , dis = edgeList[j][2] ;\n dsu.Union(u,v) ;\n }\n prev = idx + 1 ;\n\t\t\t//Check if p and q fall under the same set or not ?\n if(dsu.find_parent(p) == dsu.find_parent(q)) ans[i] = true ;\n }\n return ans ;\n }\n};\n```
1
0
['Graph', 'C']
0
checking-existence-of-edge-length-limited-paths
Java Solution
java-solution-by-vipfly-6g1y
First solution is a BFS solution which gives TLE: \n\nclass Solution {\n public boolean[] distanceLimitedPathsExist(int n, int[][] edgeList, int[][] queries)
vipfly
NORMAL
2022-06-11T08:29:22.020008+00:00
2022-06-11T08:29:22.020035+00:00
251
false
**First solution is a BFS solution which gives TLE: **\n\nclass Solution {\n public boolean[] distanceLimitedPathsExist(int n, int[][] edgeList, int[][] queries) {\n boolean[] output = new boolean[queries.length];\n \n Graph g = new Graph(n);\n \n for (int i=0; i<edgeList.length; i++) {\n g.addEdge(edgeList[i][0], edgeList[i][1], edgeList[i][2]);\n }\n \n for (int i=0; i<queries.length; i++) {\n int source = queries[i][0];\n int dest = queries[i][1];\n int limit = queries[i][2];\n boolean[] visited = new boolean[n];\n \n PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[1] - b[1]);\n \n visited[source] = true;\n for (int j=0; j<g.arr.get(source).size(); j++) {\n int v = g.arr.get(source).get(j).v;\n int w = g.arr.get(source).get(j).weight;\n \n if (w < limit) {\n pq.add(new int[]{v, w});\n }\n \n }\n \n pq.add(new int[]{source, 0});\n \n while (!pq.isEmpty()) {\n int[] current = pq.remove();\n \n int u = current[0];\n int dist = current[1];\n \n if (u == dest) {\n output[i] = true;\n break;\n }\n visited[u] = true;\n \n \n // System.out.println(u);\n for (int j=0; j<g.arr.get(u).size(); j++) {\n int v = g.arr.get(u).get(j).v;\n int w = g.arr.get(u).get(j).weight;\n \n \n \n if (!visited[v] && w < limit) {\n // System.out.println(v + " " + w);\n pq.add(new int[]{v, w});\n }\n } \n }\n }\n \n return output;\n }\n}\n\nclass Node {\n int v;\n int weight;\n \n public Node (int v, int weight) {\n this.v = v;\n this.weight = weight;\n } \n}\n\nclass Graph{\n int V;\n List<List<Node>> arr;\n \n public Graph(int v) {\n V = v;\n \n arr = new ArrayList<>();\n \n for (int i=0; i<v; i++) {\n arr.add(new ArrayList<>());\n }\n }\n \n public void addEdge(int u, int v, int w) {\n arr.get(u).add(new Node(v, w));\n arr.get(v).add(new Node(u, w));\n }\n}\n\n**Next solution uses Union Find and DSU algorthm which is clean and accepted - **\n\nclass Solution {\n public boolean[] distanceLimitedPathsExist(int n, int[][] edgeList, int[][] queries) {\n UnionFind uf = new UnionFind(n);\n \n Arrays.sort(edgeList, (a, b) -> a[2] - b[2]);\n \n int[][] sortedQueries = new int[queries.length][4];\n \n for (int i=0; i<queries.length; i++) {\n sortedQueries[i][0] = queries[i][0];\n sortedQueries[i][1] = queries[i][1];\n sortedQueries[i][2] = queries[i][2];\n sortedQueries[i][3] = i;\n }\n \n Arrays.sort(sortedQueries, (a, b) -> a[2] - b[2]);\n \n int start = 0;\n boolean[] output = new boolean[queries.length];\n \n for (int i=0; i<sortedQueries.length; i++) {\n int[] query = sortedQueries[i];\n \n int w = query[2];\n \n while (start < edgeList.length && edgeList[start][2] < w) {\n uf.union(edgeList[start][0], edgeList[start][1]);\n start++;\n }\n \n if (uf.find(query[0]) == uf.find(query[1])) {\n output[query[3]] = true;\n }\n }\n \n return output;\n }\n}\n\nclass UnionFind {\n int[] parent;\n \n public UnionFind(int n) {\n parent = new int[n];\n \n for (int i=0; i<n; i++) {\n parent[i] = i;\n }\n }\n \n public int find(int x) {\n while (x != parent[x]) {\n x = parent[x];\n }\n \n return x;\n }\n \n public void union(int x, int y) {\n int xParent = find(x);\n int yParent = find(y);\n \n parent[xParent] = yParent;\n }\n}\n\n
1
0
['Breadth-First Search', 'Union Find', 'Heap (Priority Queue)']
0
checking-existence-of-edge-length-limited-paths
Java || Union Find || O(Vlog(V) + Elog(E)) || faster than 96.7%
java-union-find-ovlogv-eloge-faster-than-y7j9
\nclass Solution {\n public boolean[] distanceLimitedPathsExist(int n, int[][] edgeList, int[][] queries) {\n int queryLen = queries.length;\n
funingteng
NORMAL
2022-05-27T21:28:36.205984+00:00
2022-05-27T21:28:36.206013+00:00
239
false
```\nclass Solution {\n public boolean[] distanceLimitedPathsExist(int n, int[][] edgeList, int[][] queries) {\n int queryLen = queries.length;\n int[][] queryWithIds = new int[queryLen][4];\n \n for (int i = 0; i < queryLen; i++) {\n queryWithIds[i] = new int[] {\n i, queries[i][0], queries[i][1], queries[i][2] \n };\n }\n // sort quries by limit\n Arrays.parallelSort(queryWithIds, (r1, r2) -> Integer.compare(r1[3], r2[3]));\n // sort edges by dis\n Arrays.parallelSort(edgeList, (r1, r2) -> Integer.compare(r1[2], r2[2]));\n int edgeTop = 0;\n boolean[] result = new boolean[queryLen];\n // initialize UnionFind object\n UnionFind uf = new UnionFind(n);\n for (int i = 0; i < queryLen; i++) {\n int limit = queryWithIds[i][3];\n while (edgeTop < edgeList.length && edgeList[edgeTop][2] < limit) {\n uf.union(edgeList[edgeTop][0], edgeList[edgeTop][1]);\n edgeTop++;\n }\n result[queryWithIds[i][0]] = uf.find(queryWithIds[i][1]) == uf.find(queryWithIds[i][2]);\n }\n return result;\n }\n private static class UnionFind {\n private int[] root;\n private int[] rank;\n public UnionFind(int n) {\n this.root = new int[n];\n this.rank = new int[n];\n Arrays.fill(this.root, -1);\n }\n public int find(int target) {\n if (root[target] == -1) return target;\n return root[target] = find(root[target]);\n }\n public void union(int t1, int t2) {\n int r1 = find(t1);\n int r2 = find(t2);\n if (r1 != r2) {\n if (rank[r1] > rank[r2]) {\n root[r2] = r1;\n } else if (rank[r2] > rank[r1]) {\n root[r1] = r2;\n } else {\n root[r2] = r1;\n rank[r1]++;\n }\n }\n }\n }\n}\n```
1
0
['Union Find', 'Java']
0
checking-existence-of-edge-length-limited-paths
[Golang] Union find solution by golang
golang-union-find-solution-by-golang-by-g3i4y
Sort queries by limit\n2. Sort edges by distance\n3. For each query, Connect all the edges whose distances are less than limit by union find\n4. If queries[0] a
genius52
NORMAL
2021-11-27T06:44:53.316530+00:00
2021-11-27T06:45:27.840009+00:00
185
false
1. Sort queries by limit\n2. Sort edges by distance\n3. For each query, Connect all the edges whose distances are less than limit by union find\n4. If queries[0] and queries[1] meet the requirement, they should be in same group.\n```\nfunc DistanceLimitedPathsExist(n int, edgeList [][]int, queries [][]int) []bool {\n\tvar q_len int = len(queries)\n\tvar record []int = make([]int,q_len)\n\tfor i := 0;i < q_len;i++{\n\t\trecord[i] = i\n\t}\n\ttype funcType func (groups []int,node int)int\n\tvar get_parent funcType\n\tget_parent = func (groups []int,node int)int{\n\t\tif groups[node] != node{\n\t\t\tgroups[node] = get_parent(groups,groups[node])\n\t\t}\n\t\treturn groups[node]\n\t}\n\tsort.Slice(record, func(i, j int) bool {\n\t\treturn queries[record[i]][2] < queries[record[j]][2]\n\t})\n\tsort.Slice(edgeList, func(i, j int) bool {\n\t\treturn edgeList[i][2] < edgeList[j][2]\n\t})\n\tvar groups []int = make([]int,n)\n\tfor i := 0;i < n;i++{\n\t\tgroups[i] = i\n\t}\n\tvar res []bool = make([]bool,q_len)\n\tvar edge_idx int = 0\n\tvar edge_len int = len(edgeList)\n\tfor i := 0;i < q_len;i++{\n\t\tfor edge_idx < edge_len && edgeList[edge_idx][2] < queries[record[i]][2]{\n\t\t\tnode1 := edgeList[edge_idx][0]\n\t\t\tnode2 := edgeList[edge_idx][1]\n\t\t\tgroup1 := get_parent(groups,node1)\n\t\t\tgroup2 := get_parent(groups,node2)\n\t\t\tif group1 != group2{\n\t\t\t\tif group1 < group2{\n\t\t\t\t\tgroups[group2] = group1\n\t\t\t\t}else{\n\t\t\t\t\tgroups[group1] = group2\n\t\t\t\t}\n\t\t\t}\n\t\t\tedge_idx++\n\t\t}\n\t\tn1 := queries[record[i]][0]\n\t\tn2 := queries[record[i]][1]\n\t\tif get_parent(groups,n1) == get_parent(groups,n2){\n\t\t\tres[record[i]] = true\n\t\t}else{\n\t\t\tres[record[i]] = false\n\t\t}\n\t}\n\treturn res\n}\n```
1
0
['Go']
0
checking-existence-of-edge-length-limited-paths
C++ | DSU Solution Explained
c-dsu-solution-explained-by-harshnadar23-a2hj
\nbool cmp(vector<int>& a, vector<int>& b){\n return a[2]<b[2];\n}\nclass Solution {\npublic:\n int par[100002];\n \n int find(int a){\n if(p
harshnadar23
NORMAL
2021-09-10T03:54:54.327897+00:00
2021-09-10T03:54:54.327938+00:00
189
false
```\nbool cmp(vector<int>& a, vector<int>& b){\n return a[2]<b[2];\n}\nclass Solution {\npublic:\n int par[100002];\n \n int find(int a){\n if(par[a]==a) return a;\n return par[a]=find(par[a]);\n }\n \n void uni(int a, int b){\n a=find(a);\n b=find(b);\n if(a==b) return;\n if(a<b) swap(a,b);\n par[b]=a;\n }\n\t\n vector<bool> distanceLimitedPathsExist(int n, vector<vector<int>>& edge, vector<vector<int>>& queries) {\n int i=0,j=0;\n int q=queries.size();\n \n vector<vector<int> > qu;\n\t\t\n for(i=0;i<queries.size();i++){\n qu.push_back({queries[i][0],queries[i][1],queries[i][2],i}); //storing the index of query to keep mark of after sorting\n }\n\t\t\n sort(edge.begin(), edge.end(), cmp); //sort edge according to distance\n sort(qu.begin(), qu.end(),cmp); //sort queries according to limit\n \n for(i=0;i<n+1;i++){\n par[i]=i;\n }\n i=0;\n vector<bool> ans(q);\n\t\t\n while(i<q){\n while(j<edge.size() && edge[j][2]<qu[i][2]){ //checking if edge dist is less than current limit, then union \n uni(edge[j][0], edge[j][1]);\n j++;\n }\n if(find(qu[i][0]) == find(qu[i][1])) ans[qu[i][3]]=true;\n else ans[qu[i][3]]=false;\n i++;\n }\n return ans;\n }\n};\n```
1
0
['Union Find']
0
checking-existence-of-edge-length-limited-paths
DP+BinaryLifting
dpbinarylifting-by-feynman_1729_67-6tvd
\nvector<set<int>>g;\nmap<vector<int>,int>cost;\nvector<int>h,vis;\nmap<int,int>par;\nint ances[100005][18],dp[100005][18];\nvoid dfs(int u,int p){\n vis[u]=
isparsh_671
NORMAL
2021-08-11T05:32:49.927990+00:00
2021-08-11T05:32:49.928030+00:00
128
false
```\nvector<set<int>>g;\nmap<vector<int>,int>cost;\nvector<int>h,vis;\nmap<int,int>par;\nint ances[100005][18],dp[100005][18];\nvoid dfs(int u,int p){\n vis[u]=1;\n ances[u][0]=p;\n vector<int>tmp={p,u};\n dp[u][0]=cost[tmp];\n for(int i=1;i<18;i++){\n dp[u][i]=max(dp[ances[u][i-1]][i-1],dp[u][i-1]);\n ances[u][i]=ances[ances[u][i-1]][i-1];\n }\n h[u]=h[p]+1;\n for(int child:g[u]){\n if(vis[child])continue;\n dfs(child,u);\n }\n}\nint climb(int u,int ht,int &res){\n int bit=17;\n while(ht>0 and bit>=0){\n if((ht&(1<<bit))>0){\n ht-=(1<<bit);\n res=max(dp[u][bit],res);\n u=ances[u][bit];\n }\n bit--;\n }\n return u;\n}\nint find(int u){\n if(!par.count(u) or par[u]==u)return par[u]=u;\n return par[u]=find(par[u]);\n}\nint lca(int u,int v,int& res){\n int res1=0;\n if(h[u]<h[v])swap(u,v);\n u=climb(u,h[u]-h[v],res1);\n res=max(res1,res);\n res1=0;\n if(u==v)return u;\n int bit=17;\n while(ances[u][0]!=ances[v][0] and bit>=0){\n if(ances[u][bit]==ances[v][bit]){\n bit--;\n continue;\n }\n res=max(dp[u][bit],res);\n res=max(dp[v][bit],res);\n u=ances[u][bit];\n v=ances[v][bit];\n bit--;\n }\n res=max(res,dp[u][0]);\n res=max(res,dp[v][0]);\n return ances[u][0];\n}\n\nclass Solution {\npublic:\nvector<bool> distanceLimitedPathsExist(int n, vector<vector<int>>& e, vector<vector<int>>& q) {\n memset(dp,0,sizeof(dp));\n memset(ances,0,sizeof(ances));\n h=vector<int>(n,0);\n g=vector<set<int>>(n);\n vis=vector<int>(n,0);\n cost.clear();\n par.clear();\n vector<vector<int>>el(0);\n for(auto v:e){\n el.push_back({v[2],v[0],v[1]});\n }\n sort(el.begin(),el.end());\n for(auto v:el){\n \n int p1=find(v[1]);\n int p2=find(v[2]);\n if(p1==p2)continue;\n par[p1]=p2;\n vector<int>tmp={v[1],v[2]};\n vector<int>tmp1={v[2],v[1]};\n cost[tmp1]=v[0];\n cost[tmp]=v[0];\n g[v[1]].insert(v[2]);\n g[v[2]].insert(v[1]);\n }\n for(int i=0;i<n;i++){\n if(vis[i])continue;\n cost[{i,i}]=0;\n dfs(i,i);\n }\n vector<bool>res(0);\n for(auto v:q){\n int ans=0;\n lca(v[0],v[1],ans);\n \n if(ans<v[2] and find(v[0])==find(v[1]))res.push_back(1);\n else res.push_back(0);\n }\n return res;\n}\n};\n```
1
0
[]
0
checking-existence-of-edge-length-limited-paths
C++ | O(N log N) | Union Find
c-on-log-n-union-find-by-sbarthol-ik5x
\n\tvoid merge(int a, int b, vector<int>& sets){\n int x=find(a,sets),y=find(b,sets);\n if(x!=y){\n sets[x]=y;\n }\n }\n i
sbarthol
NORMAL
2021-08-08T12:18:16.268570+00:00
2021-08-08T12:18:16.268606+00:00
149
false
```\n\tvoid merge(int a, int b, vector<int>& sets){\n int x=find(a,sets),y=find(b,sets);\n if(x!=y){\n sets[x]=y;\n }\n }\n int find(int a, vector<int>& sets){\n return sets[a]==a?a:sets[a]=find(sets[a],sets);\n }\n vector<bool> distanceLimitedPathsExist(int n, vector<vector<int>>& edgeList, vector<vector<int>>& queries) {\n sort(edgeList.begin(), edgeList.end(), [](vector<int> a, vector<int> b){\n return a[2]<b[2];\n });\n int m=queries.size();\n int idx[m];\n for(int i=0;i<m;i++){\n idx[i]=i;\n }\n sort(idx,idx+m,[&queries](int a, int b){\n return queries[a][2]<queries[b][2];\n });\n vector<int> sets(n);\n for(int i=0;i<n;i++){\n sets[i]=i;\n }\n vector<bool> ans(m);\n int i=0;\n for(int j=0;j<m;j++){\n while(i<edgeList.size() && edgeList[i][2]<queries[idx[j]][2]){\n merge(edgeList[i][0],edgeList[i][1],sets);\n i++;\n }\n ans[idx[j]]=find(queries[idx[j]][0],sets)==find(queries[idx[j]][1],sets);\n }\n return ans;\n }\n```
1
0
[]
0
checking-existence-of-edge-length-limited-paths
C++ online queries(MST and lowest common ancestor(powers of 2)) and offline (sorting,2 pointers))
c-online-queriesmst-and-lowest-common-an-83hj
Online: \n\nclass Solution {\n#define pb push_back\n#define pi pair\n#define fi first\n#define sc second\nvectorparent,lvl;\nvector>lis;\nvector>g,lca;\nvectorv
arghyadeep_coder
NORMAL
2021-07-19T06:07:26.555821+00:00
2021-07-19T06:07:26.555861+00:00
123
false
Online: \n\nclass Solution {\n#define pb push_back\n#define pi pair<int,int>\n#define fi first\n#define sc second\nvector<int>parent,lvl;\nvector<vector<int>>lis;\nvector<vector<pi>>g,lca;\nvector<bool>vis;\nint INF=1e9+5;\n\nstatic bool comp(vector<int>&x,vector<int>&y){\n return x[0]<=y[0];\n}\n \nbool Union(int u,int v){\n u=parent[u];\n v=parent[v];\n if(u==v){\n return 0;\n }\n if(lis[u].size()>lis[v].size()){\n swap(u,v);\n }\n for(auto &child:lis[u]){\n parent[child]=v;\n lis[v].pb(child);\n }\n return 1;\n}\n \nvoid dfs(int node,int height){\n vis[node]=1;\n lvl[node]=height;\n for(auto &p:g[node]){\n int child=p.fi,cost=p.sc;\n if(!vis[child]){\n lca[child][0]={node,cost};\n dfs(child,height+1);\n }\n }\n}\n\nint solve(int u,int v){\n if(lvl[u]<lvl[v]){\n swap(u,v);\n }\n int dist=lvl[u]-lvl[v];\n int ans=0;\n for(int bit=0;bit<17;++bit){\n if(dist & (1<<bit)){\n ans=max(ans,lca[u][bit].sc);\n u=lca[u][bit].fi;\n }\n }\n if(u==v){\n return ans;\n }\n for(int lift=16;lift>=0;lift--){\n if(lca[u][lift].fi!=-1 && lca[u][lift].fi!=lca[v][lift].fi){\n ans=max(ans,lca[u][lift].sc);\n ans=max(ans,lca[v][lift].sc);\n u=lca[u][lift].fi;\n v=lca[v][lift].fi;\n }\n }\n ans=max(ans,lca[u][0].sc);\n ans=max(ans,lca[v][0].sc);\n return ans;\n}\n \npublic:\n vector<bool> distanceLimitedPathsExist(int n, vector<vector<int>>& edgeList, vector<vector<int>>& queries) {\n parent.resize(n);\n lis.resize(n);\n vis.resize(n);\n g.resize(n);\n lvl.resize(n);\n lca.resize(n,vector<pi>(17,{-1,INF}));\n for(int i=0;i<n;i++){\n parent[i]=i;\n lis[i].pb(i);\n }\n vector<vector<int>>modifiedEdgeList;\n for(auto &v:edgeList){\n modifiedEdgeList.push_back(vector<int>{v[2],v[0],v[1]});\n }\n sort(modifiedEdgeList.begin(),modifiedEdgeList.end(),comp);\n for(auto &x:modifiedEdgeList){\n int u=x[1],v=x[2],cost=x[0];\n if(Union(u,v)){\n g[u].pb({v,cost});\n g[v].pb({u,cost});\n }\n }\n for(int i=0;i<n;i++){\n if(!vis[parent[i]]){\n dfs(parent[i],1);\n }\n }\n for(int lift=1;lift<17;++lift){\n for(int i=0;i<n;++i){\n int x=lca[i][lift-1].fi;\n if(x!=-1 && lca[x][lift-1].fi!=-1){\n lca[i][lift]={lca[x][lift-1].fi,max(lca[i][lift-1].sc,lca[x][lift-1].sc)};\n }\n }\n }\n vector<bool>ans;\n for(auto &x:queries){\n int u=x[0],v=x[1],limit=x[2];\n if(parent[u]!=parent[v]){\n ans.pb(false);\n continue;\n }\n int maxi=solve(u,v);\n ans.pb(maxi<limit);\n }\n return ans;\n }\n};\n\nOffline: \n\nclass Solution {\n#define pb push_back\n#define fi first\n#define sc second\nvector<int>parent;\nvector<vector<int>>lis;\n \nvoid Union(int u,int v){\n u=parent[u];\n v=parent[v];\n if(u==v){\n return ;\n }\n if(lis[u].size()>lis[v].size()){\n swap(u,v);\n }\n for(auto &x:lis[u]){\n parent[x]=v;\n lis[v].pb(x);\n }\n}\n \npublic:\n vector<bool> distanceLimitedPathsExist(int n, vector<vector<int>>& edgeList, vector<vector<int>>& queries) {\n vector<vector<int>>modifiedQueries,modifiedEdgeList;\n for(int i=0;i<queries.size();i++){\n modifiedQueries.pb(vector<int>{queries[i][2],i,queries[i][0],queries[i][1]});\n }\n for(auto &v:edgeList){\n modifiedEdgeList.pb(vector<int>{v[2],v[0],v[1]});\n }\n sort(modifiedQueries.begin(),modifiedQueries.end());\n sort(modifiedEdgeList.begin(),modifiedEdgeList.end());\n parent.resize(n);\n lis.resize(n);\n for(int i=0;i<n;i++){\n parent[i]=i;\n lis[i].pb(i);\n }\n int p=0;\n vector<bool>ans(queries.size());\n for(auto &x:modifiedQueries){\n int limit=x[0],index=x[1],u=x[2],v=x[3];\n while(p<modifiedEdgeList.size() && modifiedEdgeList[p][0]<limit){\n int u1=modifiedEdgeList[p][1];\n int v1=modifiedEdgeList[p][2];\n Union(u1,v1);\n p++;\n }\n ans[index]=parent[u]==parent[v];\n }\n return ans;\n }\n};
1
1
[]
0
checking-existence-of-edge-length-limited-paths
Java Union Find 97.69% faster
java-union-find-9769-faster-by-sunnydhot-8e6p
```\n\tint[] parent;\n public boolean[] distanceLimitedPathsExist(int n, int[][] edgeList, int[][] queries) {\n int qSize= queries.length, eSize= edge
sunnydhotre
NORMAL
2021-03-26T22:09:57.823075+00:00
2021-03-26T22:09:57.823107+00:00
121
false
```\n\tint[] parent;\n public boolean[] distanceLimitedPathsExist(int n, int[][] edgeList, int[][] queries) {\n int qSize= queries.length, eSize= edgeList.length;\n parent= new int[n];\n for(int i=0; i<n; i++) parent[i]= i;\n Arrays.sort(edgeList,(a,b)->a[2]-b[2]);\n int[][] sortedQ= new int[qSize][];\n boolean[] res= new boolean[qSize];\n for(int i=0; i<qSize; i++){\n sortedQ[i]= new int[]{queries[i][0],queries[i][1],queries[i][2],i};\n }\n Arrays.sort(sortedQ,(a,b)->a[2]-b[2]);\n int index= 0;\n for(int[] query: sortedQ){\n while(index<eSize && edgeList[index][2]<query[2]) union(edgeList[index][0],edgeList[index++][1]);\n res[query[3]]= find(query[0])==find(query[1]);\n }\n return res;\n }\n public void union(int v1, int v2){\n int group1= find(v1), group2= find(v2);\n parent[group1]= group2;\n }\n public int find(int v){\n while(v!=parent[v]){\n parent[v]= parent[parent[parent[v]]];\n v= parent[v];\n }\n return v;\n }
1
0
[]
0
checking-existence-of-edge-length-limited-paths
C++ concise sort then union find
c-concise-sort-then-union-find-by-sanzen-kln4
```\nclass Solution {\npublic:\n vector distanceLimitedPathsExist(int n, vector>& edgeList, vector>& queries) {\n vroot.resize(n);\n for(int i=
sanzenin_aria
NORMAL
2021-02-04T03:33:16.526992+00:00
2021-02-04T03:33:51.734784+00:00
199
false
```\nclass Solution {\npublic:\n vector<bool> distanceLimitedPathsExist(int n, vector<vector<int>>& edgeList, vector<vector<int>>& queries) {\n vroot.resize(n);\n for(int i=0;i<n;i++) vroot[i] = i;\n for(int i=0;i<queries.size();i++) queries[i].push_back(i);\n sort(queries.begin(), queries.end(), [](auto& v1, auto& v2){return v1[2] < v2[2];});\n sort(edgeList.begin(), edgeList.end(), [](auto& v1, auto& v2) {return v1[2] < v2[2];});\n \n vector<bool> res(queries.size());\n auto it = edgeList.begin(), end = edgeList.end();\n for(auto& v:queries){\n int p = v[0], q = v[1], limit = v[2], i = v[3];\n while(it != end && (*it)[2] < limit){\n connect((*it)[0], (*it)[1]);\n ++it;\n }\n res[i] = isConnect(p, q);\n }\n return res;\n }\n \n void connect(int i, int j){\n auto ri = root(i), rj = root(j);\n vroot[ri] = rj;\n }\n \n bool isConnect(int i, int j){\n return root(i) == root(j);\n }\n \n int root(int i){\n if(vroot[i] != i) vroot[i] = root(vroot[i]);\n return vroot[i];\n }\n \n vector<int> vroot;\n};
1
1
[]
0
checking-existence-of-edge-length-limited-paths
Ruby - Union-find
ruby-union-find-by-shhavel-k0y4
Sort edges and queries by weight remembering initial queries order.\n\nIterate queries in weight ascending order. Combain vertices with edges having weight < qu
shhavel
NORMAL
2021-01-31T21:11:25.285740+00:00
2021-01-31T21:11:25.285786+00:00
98
false
Sort edges and queries by weight remembering initial queries order.\n\nIterate queries in weight ascending order. Combain vertices with edges having weight < query weight.\n\nFor each query check if vertices are combined (belong to the same group).\n \n```ruby\ndef distance_limited_paths_exist(n, edge_list, queries)\n # Union-find\n par = *0...n # parent vertices for combined groups\n find = ->(x) { par[x] == x ? x : (par[x] = find[par[x]]) }\n merge = ->(x, y, _w) { par[find[x]] = find[y] }\n\n ret = Array.new(queries.size, false)\n\n edges = edge_list.sort_by(&:last) # sort by weight\n qs = queries.map.with_index { |(u, v, w), i| [w, u, v, i] }.sort\n \n for w, u, v, i in qs\n merge[*edges.shift] while edges.any? && edges.first.last < w\n ret[i] = find[u] == find[v]\n end\n ret\nend\n```
1
0
['Union Find', 'Ruby']
0
checking-existence-of-edge-length-limited-paths
Java Union Find solution o(nlogn) + o(n)
java-union-find-solution-onlogn-on-by-do-u03y
```\nclass Solution {\n private int[] f;\n \n private void init(int n) {\n f = new int[n];\n \n for (int i = 0; i < n; i++) {\n
doudoukuaipao
NORMAL
2021-01-26T01:54:22.566236+00:00
2021-01-26T01:54:22.566282+00:00
143
false
```\nclass Solution {\n private int[] f;\n \n private void init(int n) {\n f = new int[n];\n \n for (int i = 0; i < n; i++) {\n f[i] = i;\n }\n }\n \n private int find(int x) {\n if (f[x] == x) {\n return x;\n }\n \n return f[x] = find(f[x]);\n }\n \n private void union(int x, int y) {\n int p = find(x);\n int q = find(y);\n \n if (p != q) {\n f[p] = q;\n }\n }\n \n class Query implements Comparable<Query> {\n int[] qry;\n int index;\n \n public Query(int[] qry, int index) {\n this.qry = qry;\n this.index = index;\n }\n \n public int compareTo(Query q) {\n return this.qry[2] - q.qry[2];\n }\n }\n \n public boolean[] distanceLimitedPathsExist(int n, int[][] edgeList, int[][] queries) {\n if (edgeList == null || edgeList.length == 0 || queries == null || queries.length == 0) {\n return new boolean[0];\n }\n \n Arrays.sort(edgeList, (e1, e2) -> e1[2] - e2[2]);\n \n List<Query> list = new ArrayList();\n \n for (int i = 0; i < queries.length; i++) {\n list.add(new Query(queries[i], i));\n }\n \n Collections.sort(list);\n \n init(n);\n \n boolean[] res = new boolean[queries.length];\n \n int prevLimit = 0;\n int curLimit = 0;\n int prevIndex = 0;\n \n for (int i = 0; i < list.size(); i++) {\n Query q = list.get(i);\n \n curLimit = q.qry[2];\n \n // add new edges to union\n prevIndex = addEdges(prevIndex, prevLimit, curLimit, edgeList);\n \n // if two nodes has a valid path, put true\n if (find(q.qry[0]) == find(q.qry[1])) {\n res[q.index] = true;\n }\n \n prevLimit = curLimit;\n }\n \n \n return res;\n }\n \n // add new edges to uf\n private int addEdges(int prevIndex, int prevLimit, int curLimit, int[][] edges) {\n int i = prevIndex;\n \n for (i = prevIndex; i < edges.length; i++) {\n if (edges[i][2] >= prevLimit && edges[i][2] < curLimit) {\n union(edges[i][0], edges[i][1]);\n }\n else {\n break;\n }\n }\n \n return i;\n }\n}
1
0
[]
0
checking-existence-of-edge-length-limited-paths
C++ solution using Union find method
c-solution-using-union-find-method-by-vv-igef
\nclass Solution {\npublic:\n \n \n int find(int n,int parent[])\n {\n if(parent[n]==-1)\n return n;\n return parent[n]=fin
vvd4
NORMAL
2021-01-03T09:52:28.104687+00:00
2021-01-03T09:52:28.104718+00:00
140
false
```\nclass Solution {\npublic:\n \n \n int find(int n,int parent[])\n {\n if(parent[n]==-1)\n return n;\n return parent[n]=find(parent[n],parent);\n }\n \n bool compare(vector<int> &a,vector<int>&b)\n {\n return a[2]<b[2];\n }\n \n vector<bool> distanceLimitedPathsExist(int n, vector<vector<int>>& edgeList, vector<vector<int>>& queries) {\n multimap<int,array<int,3>> mmp;\n for(int i=0;i<queries.size();i++)\n {\n mmp.insert({queries[i][2],{queries[i][0],queries[i][1],i}});\n }\n // sort(edgeList.begin(),edgeList.end(),compare);\n sort(begin(edgeList), end(edgeList), [](vector<int> &a, vector<int> &b) { return a[2] < b[2]; });\n int parent[n];\n memset(parent,-1,sizeof(parent));\n vector<bool> ans(queries.size());\n \n int index_edge=0;\n \n for(auto &querie:mmp)\n {\n while(index_edge<edgeList.size() and querie.first>edgeList[index_edge][2])\n {\n int parent1=find(edgeList[index_edge][0],parent);\n int parent2=find(edgeList[index_edge][1],parent);\n // parent[edgeList[index_edge][0]]=parent1;\n // parent[edgeList[index_edge][1]]=parent2;\n // cout<<parent1<<" "<<parent2<<endl;\n if(parent1!=parent2)\n {\n parent[parent1]=parent2; \n }\n index_edge++;\n // cout<<index_edge<<" "<<querie.first<<" "<<edgeList[index_edge][2]<<" "<<edgeList.size()<<endl;\n }\n if(find(querie.second[0],parent)==find(querie.second[1],parent))\n ans[querie.second[2]]=true;\n else\n ans[querie.second[2]]=false;\n \n }\n for(int i=0;i<edgeList.size();i++)\n cout<<edgeList[i][2]<<" ";\n // for(int i=0;i<n;i++)\n // cout<<parent[i]<<" ";\n return ans;\n \n }\n};\n```
1
0
[]
0
checking-existence-of-edge-length-limited-paths
Very simple solution with explanations
very-simple-solution-with-explanations-b-1tv8
Using DSU, we can add edges from small weight to large weight, and query from small limit to large limit. \n\nTime complexity:O(E log E) + O(Q log Q)\nSpace com
cal_apple
NORMAL
2020-12-25T18:07:34.139764+00:00
2020-12-25T18:10:25.887346+00:00
233
false
Using DSU, we can add edges from small weight to large weight, and query from small limit to large limit. \n\nTime complexity:` O(E log E) + O(Q log Q)`\nSpace complexity: `O(n)`\n\n```\n class DSU {\n vector<int> parent, rank;\n public:\n DSU(int n) {\n parent.resize(n);\n for (int x = 0; x < n; x++) {\n parent[x] = x;\n }\n rank.resize(n);\n }\n int find(int x) {\n int p = parent[x];\n if (p == x) return x;\n return parent[x] = find(p);\n }\n void unions(int x, int y) {\n x = find(x); y = find(y);\n if (x == y) return;\n \n if (rank[x] == rank[y]) rank[x]++;\n else if (rank[x] < rank[y]) swap(x, y);\n parent[y] = x;\n }\n };\n \npublic:\n vector<bool> distanceLimitedPathsExist(int n, vector<vector<int>>& edgeList, vector<vector<int>>& queries) {\n auto cmp = [&](vector<int> &a, vector<int> &b) {\n return a[2] < b[2]; \n };\n sort(edgeList.begin(), edgeList.end(), cmp); // sort by weight\n \n for (int i = 0; i < queries.size(); i++) queries[i].push_back(i); // record index\n sort(queries.begin(), queries.end(), cmp); // sort by limit\n \n DSU dsu(n);\n vector<bool> res(queries.size());\n int i = 0;\n for (auto &q : queries) {\n while(i < edgeList.size() && edgeList[i][2] < q[2]) { // only take edges with smaller weight than limit\n dsu.unions(edgeList[i][0], edgeList[i][1]);\n i++;\n }\n res[q[3]] = dsu.find(q[0]) == dsu.find(q[1]);\n }\n return res;\n }
1
0
[]
0
checking-existence-of-edge-length-limited-paths
[Javascript] Union Find with disjoint set rank optimization
javascript-union-find-with-disjoint-set-j5ccx
Haven\'t touched UF for a while, use this as a point to write a general implementation for disjoint sets. \n\nMost folks do is use an array of integer for paren
alicextt_goog
NORMAL
2020-12-23T21:22:31.091736+00:00
2020-12-23T21:22:31.091781+00:00
186
false
Haven\'t touched UF for a while, use this as a point to write a general implementation for disjoint sets. \n\nMost folks do is use an array of integer for parents. Instead used map and don\'t initiazlize the size of DS in the beginning, so the class is a little more inclusive. For this problem we are giving the nodes as integer, but if I am going to present this problem with alphabetic letters, the array solution would have to create a map and reverse map for coding/decoding.\n\nHere is the code:\n\n```\n/**\n * @param {number} n\n * @param {number[][]} edgeList\n * @param {number[][]} queries\n * @return {boolean[]}\n */\nclass DisjointSet {\n constructor (){\n this.parents = {};\n this.ranks = {};\n }\n \n union (x, y) {\n let xr = this.find(x), yr = this.find(y);\n if(this.ranks[xr] < this.ranks[yr]){\n this.parents[xr] = yr;\n }else{\n this.parents[yr] = xr;\n if(this.ranks[xr] == this.ranks[yr]) this.ranks[yr] += 1\n }\n }\n \n find(x) {\n if(!(x in this.ranks)){\n this.parents[x] = x;\n this.ranks[x] = 0;\n }\n if(this.parents[x] != x){\n this.parents[x] = this.find(this.parents[x])\n }\n return this.parents[x];\n }\n \n isConnected(x, y){\n return this.find(x) == this.find(y)\n }\n}\n// disjoint set with both sorted\nvar distanceLimitedPathsExist = function(n, edgeList, queries) {\n edgeList.sort((a, b) => a[2] - b[2])\n queries = queries.map((v, ind) => [...v, ind]).sort((a, b) => a[2] - b[2])\n \n let ds = new DisjointSet(), res = Array(queries.length).fill(false), i = 0, j = 0;\n while(i < queries.length){\n while(j < edgeList.length && queries[i][2] > edgeList[j][2]){\n ds.union(edgeList[j][0], edgeList[j][1])\n j++;\n }\n res[queries[i][3]] = ds.isConnected(queries[i][0], queries[i][1])\n i++;\n }\n return res;\n};\n```
1
0
[]
0
array-reduce-transformation
🤓5 Diff Method | Solution in TypeScript and JS | Learn JS with Question ✅ | Day-6 ✊🏃
5-diff-method-solution-in-typescript-and-q2k5
Intuition\nThereduce functionis a higher-order function that takes an array, a reducer function, and an initial value, and returns a single accumulated value by
vermaamanmr
NORMAL
2023-05-10T00:24:10.326187+00:00
2023-05-10T05:48:09.762438+00:00
31,206
false
# Intuition\nThe` reduce function `is a higher-order function that takes an array, a reducer function, and an initial value, and returns a single accumulated value by applying the reducer function to each element of the array.\n\n# Approach\nTo implement the `reduce function`, we can iterate over each element of the array, apply the reducer function to the current value and the current element, and update the accumulated value. We can use a for loop, forEach method, or a for...of loop to perform the iteration.\n\n# Complexity\n- Time complexity:\nThe time complexity of the reduce function implementation is O(n), where n is the length of the array, because the function iterates over each element of the array exactly once. \n\n- Space complexity:\nO(1), as it only uses a single variable to store the accumulated value.\n\n# What We Learn \nBy implementing the reduce function, we learn how to use higher-order functions to transform and reduce data in an array. We also learn how to use different approaches, such as for loops, forEach method, or for...of loops, to iterate over arrays.\n\n# Additional information:\nThe `fn parameter `is a function that takes two arguments: the accumulated value and the current element of the` array.` The purpose of the fn function is to perform a specific operation on these two values and return the result.\n\n# Code In JavaScript\n```\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init) {\n let val = init;\n for (let i = 0; i < nums.length; i++) {\n val = fn(val, nums[i]);\n }\n return val;\n};\n```\n\n# Code In TypeScript \n```\ntype Reducer<T, U> = (acc: T, curr: U) => T;\n\nfunction reduce<T, U>(nums: U[], fn: Reducer<T, U>, init: T): T {\n let val: T = init;\n for (let i = 0; i < nums.length; i++) {\n val = fn(val, nums[i]);\n }\n return val;\n}\n\n```\n# Using forEach loop\n```\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init) {\n let val = init;\n nums.forEach(num => {\n val = fn(val, num);\n });\n return val;\n};\n\n```\n\n# Using reduceRight\n\n```\nfunction reduceArray(nums, fn, init) {\n return nums.reverse().reduceRight((val, num) => fn(val, num), init);\n}\n\n```\n\n# Using recursion\n```\nfunction reduceArray(nums, fn, init) {\n if (nums.length === 0) {\n return init;\n } else {\n const head = nums[0];\n const tail = nums.slice(1);\n const val = fn(init, head);\n return reduceArray4(tail, fn, val);\n }\n}\n\n```\n\n# Using for...of loop\n```\nfunction reduceArray(nums, fn, init) {\n let val = init;\n for (const num of nums) {\n val = fn(val, num);\n }\n return val;\n}\n\n```\n\n![upvote-1.png](https://assets.leetcode.com/users/images/85bf72b5-16de-4457-9093-91536e0d5586_1683678139.3167114.png)\n\n
311
0
['TypeScript', 'JavaScript']
26
array-reduce-transformation
✔️2626. Array Reduce✔️Level up🚀your JavaScript skills with these intuitive implementations󠁓🚀
2626-array-reducelevel-upyour-javascript-q11y
Intuition\n Describe your first thoughts on how to solve this problem. \n>The reduce function takes an array of integers, a reducer function, and an initial val
Vikas-Pathak-123
NORMAL
2023-05-10T05:07:13.496207+00:00
2023-05-11T08:16:21.207265+00:00
1,791
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n>The `reduce` function takes an array of integers, a reducer function, and an initial value as input. It returns a single value that is the result of applying the reducer function to every element in the array. The reducer function takes two parameters - an accumulator and a current value - and returns a new accumulator value. The `reduce` function applies the reducer function to the initial value and the first element in the array to get a new accumulator value, and then applies the reducer function to the new accumulator value and the second element in the array, and so on, until every element in the array has been processed. The final accumulator value is returned as the result.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n>We start by checking if the input array is empty. If it is, we simply return the initial value.\n\n>If the input array is not empty, we initialize the accumulator to the initial value. We then loop through the array, applying the reducer function to the accumulator and the current element in each iteration. The result of each iteration becomes the new accumulator value for the next iteration.\n\n>After looping through all the elements in the array, we return the final accumulator value.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n>The time complexity of the `reduce` function is O(n), where n is the length of the input array. This is because we need to loop through every element in the array and apply the reducer function to it.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n>The space complexity of the `reduce` function is O(1), because we only use a constant amount of additional memory to store the accumulator and the loop index variable. The space required by the input array and the reducer function is not counted as additional memory usage by the `reduce` function.\n\n# Code\n``` JS []\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init) {\n if (nums.length === 0) {\n return init;\n }\n let val = init;\n for (let i = 0; i < nums.length; i++) {\n val = fn(val, nums[i]);\n }\n return val;\n};\n```\n```TS []\nfunction reduce(nums: number[], fn: Function, init: number): number {\n if (nums.length === 0) {\n return init;\n }\n let val: number = init;\n for (let i = 0; i < nums.length; i++) {\n val = fn(val, nums[i]);\n }\n return val;\n}\n\n```\n![image.png](https://assets.leetcode.com/users/images/b427e686-2e5d-469a-8e7a-db5140022a6b_1677715904.0948765.png)\n# Please Upvote\uD83D\uDC4D\uD83D\uDC4D\n```\nThanks for visiting my solution.\uD83D\uDE0A Keep Learning\nPlease give my solution an upvote! \uD83D\uDC4D\nIt\'s a simple way to show your appreciation and\nkeep me motivated. Thank you! \uD83D\uDE0A\n```\n> There are multiple ways to implement the reduce function. Here are a few alternatives:\n\n\n1. Using the `forEach` method:\n```\nfunction reduce(nums, fn, init) {\n let val = init;\n nums.forEach(num => val = fn(val, num));\n return val;\n}\n\n```\n2. Using the `reduceRight` method:\n```\nfunction reduce(nums, fn, init) {\n return nums.reduceRight(fn, init);\n}\n\n```\n3. Using a `for...of` loop:\n```\nfunction filter(arr, fn) {\n return Array.from(arr, (val, index) => fn(val, index) && val);\n}\n```\n4. Using recursion:\n```\nfunction reduce(nums, fn, init) {\n if (nums.length === 0) {\n return init;\n } else if (nums.length === 1) {\n return fn(init, nums[0]);\n } else {\n const mid = Math.floor(nums.length / 2);\n const left = nums.slice(0, mid);\n const right = nums.slice(mid);\n return fn(reduce(left, fn, init), reduce(right, fn, init));\n }\n}\n\n```\n5. Using `Array.prototype.reduce.call`:\n```\nfunction reduce(nums, fn, init) {\n return Array.prototype.reduce.call(nums, fn, init);\n}\n```\n\n6. Using the `Array.from` method:\n```\nfunction reduce(nums, fn, init) {\n return Array.from(nums).reduce(fn, init);\n}\n\n```\n# Important topic to Learn\n\n| Sr No. | Topic |\n|-----|-----|\n1.|Array methods|\n2.|Functional programming|\n3.|Higher-order functions|\n\n\n# Please Comment\uD83D\uDC4D\uD83D\uDC4D\n```\nThanks for visiting my solution comment below if you like it.\uD83D\uDE0A\n```\n\n\n\n\n\n\n\n\n\n\n\n\n
33
0
['TypeScript', 'JavaScript']
2
array-reduce-transformation
74% Beats | JavaScript
74-beats-javascript-by-ma7med-a43u
Code
Ma7med
NORMAL
2025-01-06T20:34:22.228370+00:00
2025-01-15T08:48:49.930562+00:00
2,913
false
# Code ```javascript [] /** * @param {number[]} nums * @param {Function} fn * @param {number} init * @return {number} */ var reduce = function(nums, fn, init) { let result = init; // Start with the initial value for (let i = 0; i < nums.length; i++) { result = fn(result, nums[i]); // Apply the reducer function sequentially } return result; // Return the final accumulated value }; ```
23
0
['JavaScript']
1
array-reduce-transformation
Easy Javascript Solution Using reduce method ✅✅
easy-javascript-solution-using-reduce-me-o954
Intuition\n Describe your first thoughts on how to solve this problem. \n Since we have to reduce array to a single value , we will use reduce method of javascr
Boolean_Autocrats
NORMAL
2023-05-10T01:54:22.090387+00:00
2023-05-10T03:11:40.450910+00:00
2,251
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n Since we have to reduce array to a single value , we will use reduce method of javascript.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n We will implement our own reduce method.\n 1. Initialize val=init\n ```\n for(var v of nums)\n {\n val=fn(val,v);\n }\n```\n 3. val is our result.\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```\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init) {\n let val=init;\n for(var x of nums)\n {\n val=fn(val,x);\n }\n return val;\n};\n```
11
0
['TypeScript', 'JavaScript']
1
array-reduce-transformation
Using for loop | Beats 99.89%
using-for-loop-beats-9989-by-aadit-phrb
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
aadit_
NORMAL
2024-10-28T04:29:59.199064+00:00
2024-10-28T04:29:59.199095+00:00
1,141
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```javascript []\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init) {\n let val=init;\n for (let i=0; i<nums.length;i++){\n val=fn(val,nums[i])\n }\n return val;\n};\n```
10
0
['JavaScript']
0
array-reduce-transformation
🤯 More than you ever wanted to know about this topic 🤯
more-than-you-ever-wanted-to-know-about-7zbbj
2626. Array Reduce Transformation\n\nView this Write-up on GitHub\n\n## Summary\n\nThe solution needs to process all the array elements and pass them through a
VehicleOfPuzzle
NORMAL
2024-09-07T16:28:45.853124+00:00
2024-09-07T16:28:45.853148+00:00
816
false
# 2626. Array Reduce Transformation\n\n[View this Write-up on GitHub](https://github.com/code-chronicles-code/leetcode-curriculum/blob/main/workspaces/javascript-leetcode-month/problems/2626-array-reduce-transformation/solution.md)\n\n## Summary\n\nThe solution needs to process all the array elements and pass them through a reducing function. Unlike the [`Array.prototype.reduce`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) built-in we\'re replicating, we don\'t have to pass in an index to the reducer function, but order still matters.\n\nAny approach that processes elements in the appropriate order will work well. I\'d recommend an iterative solution using a simple loop, though in the context of interview prep it may be worthwhile to become comfortable with recursive implementations.\n\nWe can also get accepted by simply using the built-in `.reduce`, since LeetCode doesn\'t enforce that we don\'t. Or, we could use [`.reduceRight`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight) instead and claim that it\'s technically not `.reduce`.\n\n## Background\n\n---\n\n###### \uD83D\uDCA1 If you\'ve been following [my recommended order for LeetCode\'s JavaScript problems](https://github.com/code-chronicles-code/leetcode-curriculum/tree/reduce-write-up/workspaces/javascript-leetcode-month) you might have already encountered the following discussion of reducing in [another write-up](https://leetcode.com/problems/apply-transform-over-each-element-in-array/solutions/5729627/content/). Feel free to skip ahead to the solutions.\n\n---\n\n### Reducing\n\nIf you\'re a veteran of [functional programming](https://en.wikipedia.org/wiki/Functional_programming) you likely know about the concept of reducing, also known as folding. If not, it\'s useful to learn, because it\'s the concept behind popular JavaScript libraries like [Redux](https://redux.js.org/) and the handy [`useReducer` React hook](https://react.dev/reference/react/useReducer).\n\nA full explanation of reducing is beyond the scope of this write-up, but the gist of it is that we can use it to combine some multi-dimensional data in some way, and _reduce_ its number of dimensions. To build up your intuition of this concept, imagine that we have some list of numbers like 3, 1, 4, 1, 5, 9 and we decide to reduce it using the addition operation. That would entail putting a + between adjacent numbers to get 3 + 1 + 4 + 1 + 5 + 9 which reduces the (one-dimensional) list to a single ("zero-dimensional") number, 23. If we were to reduce the list using multiplication instead, we\'d get a different result. So the reduce result depends on the operation used.\n\nIn the above examples, both addition and multiplication take in numbers, two at a time, and combine them into one. The reduce works by repeatedly applying the operation until there\'s only one number left. However, the result of a reduce operation doesn\'t have to be of the same type as the elements of the list. In TypeScript terms, a "reducer" function should satisfy the following signature, using generics:\n\n```typescript []\ntype Reducer<ResultType, ElementType> = (\n accumulator: ResultType,\n element: ElementType,\n) => ResultType;\n```\n\nIn other words, it should take an "accumulator" of type `ResultType` and an element of type `ElementType` and combine them into a new value of type `ReturnType`, where `ResultType` and `ElementType` will depend on the context. This allows for much more complex operations to be expressed as a reduce. In cases where `ResultType` and `ElementType` are different, we will also need to provide an initial value for the accumulator, so we have a value of type `ResultType` to kick off the reduce -- without an initial value the first step of the reduce is to combine the first two elements of the list, which wouldn\'t align with the reducer\'s signature.\n\nThe initial value also ensures a meaningful result when trying to reduce an empty list. For example, the sum of an empty list is usually defined to be zero, and we can achieve this by specifying an initial value of zero when expressing summing as a reduce via addition.\n\n## Solutions\n\nIt\'s solution time!\n\n### Using `Array.prototype.reduce`\n\nLet\'s kick off using the built-ins, for some quick gratification. Delegating to the built-in is very concise in pure JavaScript:\n\n[View Submission](https://leetcode.com/problems/array-reduce-transformation/submissions/1378766665/)\n\n```javascript []\n/**\n * @param {number[]} arr\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nconst reduce = (arr, fn, init) => arr.reduce(fn, init);\n```\n\nIn TypeScript, let\'s modify LeetCode\'s solution template and generalize our function using generics. We\'ll use one type parameter for the type of the array elements and one for the type of the result, as described in the Background section.\n\n[View Submission](https://leetcode.com/problems/array-reduce-transformation/submissions/1378765352/)\n\n```typescript []\nconst reduce = <TElement, TResult>(\n arr: readonly TElement[],\n fn: (accumulator: TResult, element: TElement) => TResult,\n init: TResult,\n): TResult => arr.reduce(fn, init);\n```\n\nWe can also get weird. If you\'re new to JavaScript, please ignore this next solution, it\'s not meant to be easy to interpret.\n\n[View Submission](https://leetcode.com/problems/array-reduce-transformation/submissions/1378767802/)\n\n```javascript []\n/**\n * @param {number[]} arr\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nconst reduce = Function.prototype.call.bind(Array.prototype.reduce);\n```\n\nUnderstanding why the above works was a bonus question in [another write-up](https://leetcode.com/problems/apply-transform-over-each-element-in-array/solutions/5729627/content/). Read about it there if you\'re curious, but otherwise don\'t worry about this code too much.\n\n### Using `Array.prototype.reduceRight`\n\nFor a clearer conscience, we can also go with `.reduceRight`, but we\'ll have to reverse the array to make sure elements are processed in the appropriate order. The built-in `.reverse` mutates the array it\'s invoked on, so if we want to avoid mutating the input, we\'ll have to copy it, using [spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) for example.\n\n[View Submission](https://leetcode.com/problems/array-reduce-transformation/submissions/1378777231/)\n\n```typescript []\nconst reduce = <TElement, TResult>(\n arr: readonly TElement[],\n fn: (accumulator: TResult, element: TElement) => TResult,\n init: TResult,\n): TResult => [...arr].reverse().reduceRight(fn, init);\n```\n\nWe can also use the more recently-added [`.toReversed`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toReversed) to get a reversed copy of the input. The function is available in LeetCode\'s JavaScript environment, but TypeScript doesn\'t know that it is, so we\'ll have to help it out by adding appropriate type definitions to the built-in interfaces for `Array` and `ReadonlyArray`.\n\n[View Submission](https://leetcode.com/problems/array-reduce-transformation/submissions/1378778477/)\n\n```typescript []\ndeclare global {\n interface Array<T> {\n toReversed(this: T[]): T[];\n }\n\n interface ReadonlyArray<T> {\n toReversed(this: readonly T[]): T[];\n }\n}\n\nconst reduce = <TElement, TResult>(\n arr: readonly TElement[],\n fn: (accumulator: TResult, element: TElement) => TResult,\n init: TResult,\n): TResult => arr.toReversed().reduceRight(fn, init);\n```\n\n---\n\n###### \u2753 **What would happen if we used `.reduceRight` without reversing?** Can you think of a reducer function that would break? My answer is at the bottom of this write-up.\n\n---\n\n### Iterative\n\nThe iterative solutions are the ones I recommend for this problem, because I think they read quite nicely. For example, a simple `for...of` loop works great, since we don\'t care about indexes:\n\n[View Submission](https://leetcode.com/problems/array-reduce-transformation/submissions/1378776182/)\n\n```typescript []\nfunction reduce<TElement, TResult>(\n arr: readonly TElement[],\n fn: (accumulator: TResult, element: TElement) => TResult,\n init: TResult,\n): TResult {\n let res = init;\n\n for (const element of arr) {\n res = fn(res, element);\n }\n\n return res;\n}\n```\n\nAlternatively, try a `.forEach`:\n\n[View Submission](https://leetcode.com/problems/array-reduce-transformation/submissions/1378776438/)\n\n```typescript []\nfunction reduce<TElement, TResult>(\n arr: readonly TElement[],\n fn: (accumulator: TResult, element: TElement) => TResult,\n init: TResult,\n): TResult {\n let res = init;\n\n arr.forEach((element) => {\n res = fn(res, element);\n });\n\n return res;\n}\n```\n\nIf we don\'t mind mutating the input array, we can also remove elements from it, one by one, and destructively reduce to a result:\n\n[View Submission](https://leetcode.com/problems/array-reduce-transformation/submissions/1378781727/)\n\n```typescript []\nfunction reduce<TElement, TResult>(\n arr: TElement[],\n fn: (accumulator: TResult, element: TElement) => TResult,\n init: TResult,\n): TResult {\n let res = init;\n\n arr.reverse();\n while (arr.length > 0) {\n res = fn(res, arr.pop());\n }\n\n return res;\n}\n```\n\n---\n\n###### \u2753 **Why use `.reverse` and `.pop` instead of `.shift` in the destructive implementation?** The answer is at the bottom of this doc.\n\n---\n\n### Recursive\n\nIn a recursive solution, a nice base case would be an empty array, wherein we can simply return `init`. For non-empty arrays, each recursion step should process one element from the array, removing it, so the array size is reduced by one and we\'re inching closer to the empty array base case:\n\n[View Submission](https://leetcode.com/problems/array-reduce-transformation/submissions/1378782688/)\n\n```typescript []\nconst reduce = <TElement, TResult>(\n arr: TElement[],\n fn: (accumulator: TResult, element: TElement) => TResult,\n init: TResult,\n): TResult =>\n arr.length === 0 ? init : reduce(arr, fn, fn(init, arr.shift()));\n```\n\nHowever, the code above has quadratic time complexity, because we\'re doing a `.shift` (which is a linear operation) within the linear operation of processing all the array elements. To achieve a linear solution, we should avoid repeatedly removing from the front of the array. We can instead rely on an index to track our progress, defaulting it to 0, so that users of our function aren\'t forced to provide it:\n\n[View Submission](https://leetcode.com/problems/array-reduce-transformation/submissions/1378769940/)\n\n```typescript []\nconst reduce = <TElement, TResult>(\n arr: readonly TElement[],\n fn: (accumulator: TResult, element: TElement) => TResult,\n init: TResult,\n index: number = 0,\n): TResult =>\n index === arr.length\n ? init\n : reduce(arr, fn, fn(init, arr[index]), index + 1);\n```\n\nNote that adding another argument to the function in this way can be considered polluting the API. One could argue that not only should users of our function not _have_ to provide an index, they shouldn\'t even be _able_ to, but with the above code they are. We can address this by hiding the index in an inner function:\n\n[View Submission](https://leetcode.com/problems/array-reduce-transformation/submissions/1378772700/)\n\n```typescript []\nfunction reduce<TElement, TResult>(\n arr: readonly TElement[],\n fn: (accumulator: TResult, element: TElement) => TResult,\n init: TResult,\n): TResult {\n const doReduce = (accumulator: TResult, index: number) =>\n index === arr.length\n ? accumulator\n : doReduce(fn(accumulator, arr[index]), index + 1);\n return doReduce(init, 0);\n}\n```\n\nAll of the above considerations are why I recommend a simple iterative solution using a `for...of` loop. However, I think we can get an elegant recursive solution (that\'s still linear in time complexity) by going through our own `reduceRight`. Since we\'re destroying the input anyway, we don\'t have to worry that `.reverse` mutates the array it\'s invoked on:\n\n[View Submission](https://leetcode.com/problems/array-reduce-transformation/submissions/1382233039/)\n\n```typescript []\nconst reduceRight = <TElement, TResult>(\n arr: TElement[],\n fn: (accumulator: TResult, element: TElement) => TResult,\n init: TResult,\n): TResult =>\n arr.length === 0 ? init : reduceRight(arr, fn, fn(init, arr.pop()));\n\nconst reduce = <TElement, TResult>(\n arr: TElement[],\n fn: (accumulator: TResult, element: TElement) => TResult,\n init: TResult,\n): TResult => reduceRight(arr.reverse(), fn, init);\n```\n\n## Answers to Bonus Questions\n\n1. **What would happen if we used `.reduceRight` without reversing the array to implement reducing?**\n\n It would still work correctly some of the time, for example if the reducer is [commutative](https://en.wikipedia.org/wiki/Commutative_property) and [associative](https://en.wikipedia.org/wiki/Associative_property), like summing: `(accumulator, element) => accumulator + element`.\n\n However, order matters if our reducer doesn\'t have these properties, for example `(accumulator, element) => 2 * accumulator + element`. Elements that are combined into the accumulator earlier will experience more multiplications by 2:\n\n ```javascript []\n const reducer = (accumulator, element) => 2 * accumulator + element;\n const arr = [3, 1, 4];\n\n // The running values with a standard `.reduce` will be:\n // 0\n // 2 * 0 + 3 = 3\n // 2 * (2 * 0 + 3) + 1 = 7\n // 2 * (2 * (2 * 0 + 3) + 1) + 4 = 18\n console.log(arr.reduce(reducer, 0)); // prints 18\n\n // The running values with a `.reduceRight` will be:\n // 0\n // 2 * 0 + 4 = 4\n // 2 * (2 * 0 + 4) + 1 = 9\n // 2 * (2 * (2 * 0 + 4) + 1) + 3 = 21\n console.log(arr.reduceRight(reducer, 0)); // prints 21\n ```\n\n2. **Why use `.reverse` and `.pop` instead of `.shift` in the destructive iterative implementation?**\n\n The reason was also discussed in the section on recursive solutions. It\'s a matter of time complexity.\n\n Removing from the back of an array is cheaper than removing from the front. As its name highlights, `.shift` involves shifting the entire contents of the array in order to reindex, making it O(N) for an array of size N. By contrast, `.pop` only needs to remove the last element, without impacting the other positions in the array, so its cost is O(1).\n\n A reverse is also O(N) since it processes the whole array, but we can pay it as a one-time up-front cost, and then we can use exclusively O(1) removes from the back for the rest of the implementation. If we instead did `.shift` within an O(N) loop, the overall complexity would become quadratic.\n\n---\n\n###### Thanks for reading! If you enjoyed this write-up, feel free to up-vote it! \n\n# \uD83D\uDE4F\n
10
0
['TypeScript', 'JavaScript']
0
array-reduce-transformation
Very simple and self explanatory solution using for loop
very-simple-and-self-explanatory-solutio-os69
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nUsing for loop\n# Compl
HadrienSmet
NORMAL
2023-04-12T11:54:26.863155+00:00
2023-04-12T11:54:26.863199+00:00
3,057
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nUsing for loop\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```\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init) {\n let answer = init;\n for (let i = 0; i < nums.length; i++) {\n answer = fn(answer, nums[i])\n }\n return answer\n};\n```
8
0
['JavaScript']
3
array-reduce-transformation
one line sol || 7/30 JAVASCRIPT
one-line-sol-730-javascript-by-doaaosama-3lah
\n# Code\n\nvar reduce = function(nums, fn, init) {\n return nums.reduce(fn,init)\n \n};\n
DoaaOsamaK
NORMAL
2024-06-20T18:56:22.844367+00:00
2024-06-20T18:56:22.844417+00:00
1,088
false
\n# Code\n```\nvar reduce = function(nums, fn, init) {\n return nums.reduce(fn,init)\n \n};\n```
7
0
['JavaScript']
4
array-reduce-transformation
reduce
reduce-by-rinatmambetov-2s7e
# Intuition \n\n\n\n\n\n\n\n\n\n\n\n# Code\n\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar
RinatMambetov
NORMAL
2023-04-18T13:49:26.028746+00:00
2023-04-18T13:49:26.028778+00:00
1,564
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/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function (nums, fn, init) {\n let res = init;\n\n for (const i of nums) {\n res = fn(res, i);\n }\n \n return res;\n};\n```
6
0
['JavaScript']
1
array-reduce-transformation
One line solution using reduce
one-line-solution-using-reduce-by-abdur_-2rug
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
ABDUR_07
NORMAL
2024-06-26T19:43:09.038423+00:00
2024-06-26T19:43:09.038445+00:00
314
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/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init) {\n return nums.reduce(fn,init)\n};\n```
5
0
['JavaScript']
1
array-reduce-transformation
Easiest Solution
easiest-solution-by-kriti___raj-rhxg
# Intuition \n\n\n\n\n\n# Complexity\n- Time complexity:O(n)\n\n\n- Space complexity:O(1)\n\n\n# Code\n\n/**\n * @param {number[]} nums\n * @param {Function}
kriti___raj
NORMAL
2023-11-07T18:30:59.971022+00:00
2023-11-07T18:30:59.971093+00:00
214
false
<!-- # Intuition -->\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n<!-- # Approach -->\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:$$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init) {\n for(var i=0; i<nums.length; i++){\n init = fn(init, nums[i]);\n }\n return init;\n};\n```\n\n---\n\n![Upvote.jpeg](https://assets.leetcode.com/users/images/6371bfb1-e4cd-42bb-8078-8faa1570f752_1699381855.2903202.jpeg)\n
5
0
['JavaScript']
0
array-reduce-transformation
EASY javascript solution || Beat 100% run-time || O(n)
easy-javascript-solution-beat-100-run-ti-u4s0
Intuition\nWe are reusing the returned value from fn(init,nums[i]). \n\n# Complexity\n- Time complexity:\nO(n)\n\n# Code\n\nvar reduce = function(nums, fn, init
shashicr7123
NORMAL
2023-05-10T10:40:13.700303+00:00
2023-05-10T10:40:13.700328+00:00
219
false
# Intuition\nWe are reusing the returned value from fn(init,nums[i]). \n\n# Complexity\n- Time complexity:\nO(n)\n\n# Code\n```\nvar reduce = function(nums, fn, init) {\n if(nums.length==0) return init;\n for(let i = 0;i<nums.length;i++) {\n init = fn(init,nums[i])\n }\n return init;\n};\n```\nUPVOTE IF IT HELPS \uD83D\uDE03
5
0
['JavaScript']
1
array-reduce-transformation
[Fully Explained] O(N) 😱+ array.reduce() with bakery example 🍰✅+Flow Diagram+Why array.reduce()?🤔
fully-explained-on-arrayreduce-with-bake-np2a
Introduction \n\nIn this problem, we are given an array nums, a reducer function fn, and an initial value init. We need to return a reduced array by applying th
poojagera0_0
NORMAL
2023-05-10T06:37:16.017753+00:00
2023-05-10T06:37:16.017807+00:00
498
false
# Introduction \n\nIn this problem, we are given an array `nums`, a reducer function `fn`, and an initial value `init`. We need to return a reduced array by applying the given operation on every element of the input array, starting from the initial value.\n\nWe need to solve this problem without using the built-in `Array.reduce()` method. In this solution, we will discuss an approach to solve this problem and the reasons why we should use the `array.reduce()` method instead of the corresponding brute force array transformation.\n\n# How does array.reduce() work?\n\nThe `array.reduce()` method in JavaScript is a powerful tool that can be used to perform a wide range of operations on arrays. The method takes a reducer function as an argument and applies it to each element in the array, resulting in a single, accumulated value.\n\nTo understand how `array.reduce()` works, let\'s consider a real-life example. Imagine that you are organizing a bake sale for a charity event. You have a list of baked goods and their corresponding prices that you want to sell, and you need to calculate the total amount of money that you expect to raise from the sale.\n\n![](https://media.giphy.com/media/DZXgs2OSwOqGY/giphy.gif)\n\nOne way to do this is to use the `array.reduce()` method. You can create an array of the prices of each baked good, and then use the method to add up all the prices to get the total amount.\n\nHere is an example implementation in JavaScript:\n\n```javascript\nconst bakedGoods = [\n { name: \'Chocolate Chip Cookies\', price: 2.50 },\n { name: \'Cupcakes\', price: 3.00 },\n { name: \'Brownies\', price: 2.00 },\n { name: \'Lemon Bars\', price: 2.50 }\n];\n\nconst totalAmount = bakedGoods.reduce((acc, item) => acc + item.price, 0);\n\nconsole.log(totalAmount); // Output: 10.00\n```\n\nIn this example, we have an array `bakedGoods` that contains four objects, each representing a baked good and its price. We use `array.reduce()` to iterate through the array and add up all the prices, starting from an initial value of 0. The reducer function takes two arguments: an accumulator `acc`, which is the accumulated value from the previous iteration, and the current `item` in the array. We add the price of the current `item` to the accumulator and return the updated accumulator value.\n\nThe final result of `array.reduce()` is the total amount of money that we expect to raise from the bake sale.\n\n# Approach to Solve the Problem \n\nIn this problem, we need to apply a reducer function on each element of the input array, starting from the initial value, until we have processed every element of the array. We can implement this logic using a `for-loop` or a `forEach()` method.\n\nHowever, since we are not allowed to use the built-in `array.reduce()` method, we will use a loop to iterate through the input array and apply the reducer function on each element. We will store the intermediate results in a new array and return the final element of this array as the answer.\n\nHere is a flow diagram of this approach:\n\n![](https://res.cloudinary.com/dzy4r0fgy/image/upload/v1683700427/Untitled-2023-02-28-0954-28_g4dnfb.png)\n\nLet\'s implement this approach in JavaScript:\n\n## Code\n```\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init) {\n let len = nums.length;\n if(len==0) return init;\n let newArr = [];\n nums.forEach((element,index)=>{\n newArr[index] = index == 0 ? fn(init,nums[index]) : fn(newArr[index-1],nums[index]);\n })\n return newArr[len-1];\n};\n```\n\n\n# Complexity Analysis\n\n- The **time complexity** of this code is **O(n)**, where n is the length of the `nums` array, because the code iterates through the `nums` array once using the `forEach()` method, which has a time complexity of O(n). Inside the `forEach()` method, each operation is constant time, so the total time complexity is O(n).\n\n- The **space complexity** of this code is **O(n)**, where n is the length of the `nums` array, because a new array `newArr` is created with the same length as `nums`. Therefore, the space required by this algorithm increases linearly with the size of the input `nums` array. Additionally, the space complexity does not depend on the size of the `init` parameter, since it is a constant size.\n\n# Why do we use array.reduce() and not its corresponding brute force transformation?\n\n- The `array.reduce()` method provides a simple and elegant way to reduce an array to a single value. It is a higher-order function that abstracts away the details of iteration and accumulation of values, and allows us to focus on the reducer function.\n\n- Using a brute force array transformation requires us to write more code and handle the iteration and accumulation of values ourselves. It can also be error-prone and harder to read, especially for more complex operations.\n
5
0
['JavaScript']
1
array-reduce-transformation
Day 6 ✌️| Easy | Commented with Examples ✅
day-6-easy-commented-with-examples-by-dr-n3pr
The reduce function is a higher-order function in JavaScript that allows you to reduce an array of values to a single value using a provided function.\nIt takes
DronTitan
NORMAL
2023-05-10T02:44:06.062738+00:00
2023-05-10T02:45:24.940702+00:00
805
false
The **reduce** function is a higher-order function in JavaScript that allows you to reduce an array of values to a single value using a provided function.\nIt takes three arguments:\nnums: An array of values to be reduced.\nfn: A function that is used to perform the reduction. \nThis function takes two **arguments**, an accumulator and the current value from the array, and returns a new accumulator.\n***init: An optional initial value for the accumulator.***\nThe reduce function works by iterating over each value in the array and applying the provided function to the current accumulator and the current value. \nThe result of this function call becomes the new accumulator, which is then used in the next iteration.\n\nHere\'s an example of using the reduce function to sum the values in an array:\n\n```\nconst nums = [1, 2, 3, 4, 5];\nconst sum = reduce(nums, (acc, val) => acc + val, 0);\nconsole.log(sum); // Output: 15\n\n```\nIn this example, the ***reduce function*** is used to sum the values in the nums array. The fn argument is a function that takes the current accumulator acc and adds the current value val to it.\nThe initial value for the accumulator init is set to 0.\n\nAnother example is to use the ***reduce function*** to find the maximum value in an array:\n\n```\nconst nums = [1, 2, 3, 4, 5];\nconst max = reduce(nums, (acc, val) => Math.max(acc, val), -Infinity);\nconsole.log(max); // Output: 5\n\n```\n\nIn this example, the ***reduce function*** is used to find the maximum value in the nums array. The fn argument is a function that takes the current accumulator acc and the current value val and returns the maximum of the two using the ***Math.max functio***n. The initial value for the accumulator init is set to -Infinity to ensure that any value in the array is greater than the ***initial accumulator valu***e.\n\n***Here is the solution to the given problem :-***\n\n\n```\n\nvar reduce = function(nums, fn, init) {\n let ans = init;\n for (let i = 0; i < nums.length; i++) {\n ans = fn(ans, nums[i]);\n }\n return ans;\n};\n```
5
0
['Array', 'JavaScript']
2
array-reduce-transformation
Beats 83.9%✔ | Beginner friendly Brute Force Solution
beats-839-beginner-friendly-brute-force-uin65
IntuitionWe are asked to implement the working of arrays.reduce() method in javascript which is a higher-order function that takes an array, a reducer function,
Abdul_Mateen14
NORMAL
2025-03-15T14:29:26.984558+00:00
2025-03-15T14:29:26.984558+00:00
232
false
# Intuition We are asked to implement the working of arrays.reduce() method in javascript which is a higher-order function that takes an array, a reducer function, and an initial value, and returns a single accumulated value by applying the reducer function to each element of the array. # Approach Firstly, I analyzed the problem and implemented what was asked i.e., an explicit check for length of the array and used for loop and using the ternary operator checked the condition and returned the value. In the second solution, trying to refactor the code, I came up with a for...of loop solution and explored that the length condition mentioned in the question was implicitly being handled. # Complexity - Time complexity: The time complexity of the reduce function implementation is O(n), where n is the length of the array, because the function iterates over each element of the array exactly once. - Space complexity: The time complexity of the reduce function implementation is O(1), because the function only uses a single accumulator variable (val) and does not allocate any extra space proportional to the input size. # Code ```javascript [] /** * @param {number[]} nums * @param {Function} fn * @param {number} init * @return {number} */ var reduce = function(nums, fn, init) { // 1st Solution // if(nums.length===0) return init; // let temp=0; // for(let i=0;i<nums.length;i++) i==0?temp=fn(init,nums[i]):temp=fn(temp,nums[i]); // return temp; // 2nd Using for...of loop let val = init; for (const element of nums) { val = fn(val,element); } return val; }; ``` Please, Upvote and share your thoughts. Happy Coding..!💗
4
0
['JavaScript']
0
array-reduce-transformation
🟧JavaScript Solution🟧
javascript-solution-by-agus_eb-2pt4
Intuition\nThe problem requires implementing a custom reduce function that sequentially applies a given function "fn" to elements of an array "nums", starting w
Agus_eb
NORMAL
2024-07-14T15:51:25.456461+00:00
2024-07-14T15:51:25.456491+00:00
680
false
# Intuition\nThe problem requires implementing a custom reduce function that sequentially applies a given function "fn" to elements of an array "nums", starting with an initial value "init". The goal is to accumulate the result of these applications and return the final accumulated value.\n\n\n\n# Approach\n1. **Initialization:** Start by setting the accumulator accum to the initial value init.\n2. **Iteration:** Iterate through each element of the array nums.\n3. **Function Application:** In each iteration, update the accumulator accum by applying the function fn to the current value of accum and the current element of nums.\n4. **Return Result:** After processing all elements, return the accumulated value accum.\n\n# Complexity\n- **Time Complexity:** The time complexity is O(n), where \n\uD835\uDC5B\nn is the length of the array nums. This is because we need to iterate through all elements of the array once.\n- **Space Complexity:** The space complexity is O(1) because we are using a constant amount of extra space for the accumulator and the loop variable, regardless of the size of the input array.\n\n# Code\n```\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init) {\n var accum = init\n\n for (var i = 0; i < nums.length; i++) {\n accum = fn(accum, nums[i]);\n }\n\n return accum;\n};\n```
4
0
['JavaScript']
1
array-reduce-transformation
JavaScript Clean Simple || 2 Solutions With Detail Explanation
javascript-clean-simple-2-solutions-with-hm07
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
Shree_Govind_Jee
NORMAL
2024-07-08T16:01:42.912157+00:00
2024-07-08T16:01:42.912194+00:00
654
false
# Complexity\n- Time complexity:$$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\n// var reduce = function (nums, fn, init) {\n// // edge case\n// if (nums.length === 0) {\n// return init;\n// }\n\n// // solve it\n// let res = init;\n// for (let i = 0; i < nums.length; i++) {\n// res = fn(res, nums[i])\n// }\n// return res;\n// };\n\nvar reduce = function (nums, fn, init) {\n let res = init\n nums.forEach((num)=>{\n res = fn(res, num)\n })\n return res\n}\n```
4
0
['Array', 'JavaScript']
1
array-reduce-transformation
One Line Solution 🚀🚀
one-line-solution-by-keerthivarmank-lzrw
Intuition\n\nThe intuition behind this code is to provide a wrapper function for the reduce() method of JavaScript arrays, allowing users to pass a custom funct
KeerthiVarmanK
NORMAL
2024-03-11T13:20:06.694535+00:00
2024-03-11T13:20:06.694568+00:00
758
false
# Intuition\n\nThe intuition behind this code is to provide a wrapper function for the reduce() method of JavaScript arrays, allowing users to pass a custom function to perform a reduction operation on an array.\n\n# Approach\n\n1. The function reduce takes an array nums, a function fn, and an initial value init.\n2. It reduces the array nums using the reduce() method, which applies the provided function fn to each element of the array, accumulating the result starting with the initial value init.\n3. It returns the final accumulated value after the reduction operation.\n\n# Complexity\n**Time complexity**:\n- The time complexity of the reduce() method itself is O(n), where n is the length of the input array nums. This is because it needs to iterate through each element of the array to apply the provided function and perform the reduction operation.\n- The time complexity of applying the provided function fn depends on the complexity of the function itself. Let\'s denote it as O(f), where f is the complexity of fn.\n- Therefore, the overall time complexity is O(n * f), where n is the length of the input array and f is the complexity of the provided function.\n\n**Space complexity**:\n\n- The space complexity is O(1) because the function returns a single accumulated value, regardless of the size of the input array.\n- The space complexity does not depend on the size of the input array but rather on the space required to store the final accumulated value.\n- Thus, the space complexity is O(1).\n\n\n\n\n\n\n# Code\n```\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init) {\n return nums.reduce(fn,init)\n \n};\n```
4
0
['JavaScript']
3
array-reduce-transformation
Easy and short
easy-and-short-by-apophis29-p74l
\nvar reduce = function (nums, fn, init) {\n let res = init;\n\n for (const i of nums) {\n res = fn(res, i);\n }\n \n return res;\n};\n\n\nThanks:)
Apophis29
NORMAL
2024-01-17T16:31:23.497899+00:00
2024-01-17T16:31:23.497931+00:00
602
false
```\nvar reduce = function (nums, fn, init) {\n let res = init;\n\n for (const i of nums) {\n res = fn(res, i);\n }\n \n return res;\n};\n```\n\nThanks:)
3
0
[]
1
array-reduce-transformation
2626. Array Reduce Transformation
2626-array-reduce-transformation-by-ngan-6rlx
Intuition\nThe code appears to implement a simplified version of the reduce function commonly found in JavaScript arrays. The reduce function is used to reduce
nganthudoan2001
NORMAL
2024-01-02T02:52:03.691526+00:00
2024-01-02T02:52:03.691557+00:00
592
false
# Intuition\nThe code appears to implement a simplified version of the `reduce` function commonly found in JavaScript arrays. The `reduce` function is used to reduce an array to a single value by applying a specified function to each element of the array.\n\n# Approach\nThe approach seems straightforward. The function `reduce` takes an array `nums`, a function `fn` (which is presumably the reducer function), and an initial value `init`. It iterates over each element of the array, applying the reducer function to the accumulator and the current element. The result is then stored in the accumulator, and the process continues until all elements are processed. The final accumulated value is then returned.\n\n# Complexity\n- Time complexity: \\(O(n)\\), where \\(n\\) is the length of the input array `nums`. This is because the function iterates through each element of the array once.\n\n- Space complexity: \\(O(1)\\), as the function uses a constant amount of space (only the `accum` variable) regardless of the size of the input array.\n\n# Code\n```javascript\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init) {\n let accum = init;\n for (let i = 0; i < nums.length; ++i) {\n accum = fn(accum, nums[i]);\n }\n return accum;\n};\n```\n\nThe code seems correct and follows the typical pattern of a reducer function. The result is returned after iterating through all elements of the array.
3
0
['JavaScript']
0
array-reduce-transformation
Explained Solution in JavaScript and TypeScript | Daily Problem of JavaScript 30 days |
explained-solution-in-javascript-and-typ-9gxt
Intuition\nTransform array according to given function.\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n1) Edge case: if arr.length
SaikatDass
NORMAL
2023-05-10T03:20:25.677221+00:00
2023-05-10T03:20:25.677261+00:00
1,799
false
# Intuition\nTransform array according to given function.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1) Edge case: if `arr.length == 0` then return `init`.\n2) The first `val` will be passed in the function as `init`, after 1st iteration `init` will be replaced by `val`.\n```\nif(n > 1){\n val = fn(init, nums[0]);\n for(var i = 1; i < n; i++){\n val = fn(val, nums[i]);\n }\n }\n```\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n- $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n- $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n---\n> I am in initial stage of learning javascript. If you have any suggestion to improve myself please suggest.\n---\n\n# Code\n``` JavaScript []\nvar reduce = function(nums, fn, init) {\n var n = nums.length, val = 0;\n if(n == 0){\n return init;\n }\n if(n == 1){\n val = fn(init, nums[0]);\n return val;\n }\n if(n > 1){\n val = fn(init, nums[0]);\n for(var i = 1; i < n; i++){\n val = fn(val, nums[i]);\n }\n }\n return val;\n};\n```\n``` TypeScript []\ntype Fn = (accum: number, curr: number) => number\n\nfunction reduce(nums: number[], fn: Fn, init: number): number {\n var n = nums.length, val = 0;\n if(n == 0){\n return init;\n }\n if(n == 1){\n val = fn(init, nums[0]);\n return val;\n }\n if(n > 1){\n val = fn(init, nums[0]);\n for(var i = 1; i < n; i++){\n val = fn(val, nums[i]);\n }\n }\n return val;\n};\n```
3
0
['TypeScript', 'JavaScript']
1
array-reduce-transformation
Java Script Solution for Array Reduce Transformation Problem
java-script-solution-for-array-reduce-tr-4egd
Intuition\n Describe your first thoughts on how to solve this problem. \nThe given code implements the reduce function, which applies a given function to each e
Aman_Raj_Sinha
NORMAL
2023-05-10T03:09:00.237968+00:00
2023-05-10T03:09:00.238004+00:00
271
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe given code implements the reduce function, which applies a given function to each element of an array, accumulating the results into a single value. The reduce function takes an array, a function, and an initial value as input parameters.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Initialize the accumulator variable with the provided initial value.\n- Iterate over each element in the given array using a for...in loop.\n- Apply the given function to the current element and the accumulator, updating the accumulator with the result.\n- Return the final value of the accumulator after iterating through all elements in the array.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of this solution is O(n), where n is the number of elements in the input array. The code iterates over each element in the array exactly once.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is O(1) because the code only uses a constant amount of additional space to store the accumulator and loop variables. The space usage does not depend on the size of the input array.\n\n# Code\n```\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init) {\n let accumulator = init;\n for (const index in nums) {\n accumulator = fn(accumulator, nums[index]);\n } \n return accumulator;\n};\n```
3
0
['JavaScript']
1
array-reduce-transformation
Easy_approach_100%-understandable
easy_approach_100-understandable-by-chak-cf7m
This is my first JS program to participate\nso, encourage me to do more and more...\nvote up to do more problem....\n\n/**\n * @param {number[]} nums\n * @param
chakradhar2210
NORMAL
2023-05-10T00:17:30.958968+00:00
2023-05-10T00:25:13.611035+00:00
250
false
This is my first JS program to participate\nso, encourage me to do more and more...\nvote up to do more problem....\n```\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init){\n if(nums.length==0){\n return init;\n }\n let x=fn(init,nums[0]);\n let i =1;\n for(i=1;i<nums.length;i++){\n x=fn(x,nums[i]);\n }\n return x;\n};\n```\n**vote up for more solutions**\n**\uD83D\uDC49VOTE UP\uD83D\uDC48**
3
0
['Array', 'JavaScript']
2
array-reduce-transformation
one-liner trick with `forEach` you should remember
one-liner-trick-with-foreach-you-should-j34gb
Intuition\nSelf-explanatory\n\n# Code\n\nreduce=(s,f,i)=>s.forEach(n=>i=f(i,n))||i\n
NotJohnVonNeumann
NORMAL
2023-04-27T03:42:34.261056+00:00
2023-04-27T03:42:34.261080+00:00
735
false
# Intuition\nSelf-explanatory\n\n# Code\n```\nreduce=(s,f,i)=>s.forEach(n=>i=f(i,n))||i\n```
3
0
['JavaScript']
2
array-reduce-transformation
Easy to understand 100% Space and Time Solution
easy-to-understand-100-space-and-time-so-a4jr
Intuition \uD83E\uDD14\nThe problem is to create a function that applies a function to each element of an array and returns a single value by reducing the array
TechSpiritSS
NORMAL
2023-04-12T14:51:38.607090+00:00
2023-04-12T14:51:38.607127+00:00
1,740
false
# Intuition \uD83E\uDD14\nThe problem is to create a function that applies a function to each element of an array and returns a single value by reducing the array to a single value.\n\n# Approach \uD83D\uDE80\nThe approach used in the provided code is to create a reduce function that takes an array, a function to apply, and an initial value as arguments, and returns a single value. The function starts by setting the initial value to ans. It then iterates over each element of the input array and applies the provided function fn to accumulate the values into a single output.\n\nThis approach ensures that the function can be used to apply any function to an array and accumulate the output into a single value.\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```\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init) {\n let ans = init;\n for (let i of nums)\n ans = fn(ans, i);\n \n return ans;\n};\n```
3
0
['JavaScript']
1
array-reduce-transformation
TypeScript: recursive one-liner
typescript-recursive-one-liner-by-jmconr-1ep0
Fun but probably not performant, since we with each call we create a new array via Array.slice().\n\ni think whether there\'s tail-call optimization depends on
jmconroy
NORMAL
2023-04-12T05:17:33.264976+00:00
2023-04-12T05:17:33.265018+00:00
580
false
Fun but probably not performant, since we with each call we create a new array via `Array.slice()`.\n\ni think whether there\'s tail-call optimization depends on the JavaScript engine used.\n\n```typescript\ntype Fn = (accum: number, curr: number) => number\n\nfunction reduce(nums: number[], fn: Fn, init: number): number {\n return nums.length === 0\n ? init\n : reduce(nums.slice(1), fn, fn(init, nums[0]));\n};\n```
3
0
['Recursion', 'TypeScript']
1
array-reduce-transformation
✅EASY JAVASCRIPT SOLUTION
easy-javascript-solution-by-swayam28-n4q3
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
swayam28
NORMAL
2024-08-12T07:25:42.695051+00:00
2024-08-12T07:25:42.695079+00:00
452
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![Upvote.png](https://assets.leetcode.com/users/images/70fb5c69-5be7-47eb-a055-9c6330448b21_1723447539.762153.png)\n\n```\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init) {\n let val = init;\n for (let i = 0; i < nums.length; i++) {\n val = fn(val, nums[i]);\n }\n return val;\n};\n```
2
0
['JavaScript']
1
array-reduce-transformation
JavaScript Array Reduce Transformation
javascript-array-reduce-transformation-b-zecu
Intuition\n Describe your first thoughts on how to solve this problem. \nWe need to reduce an integer array using a custom reduction function and an initial val
samabdullaev
NORMAL
2023-11-07T01:29:18.361586+00:00
2023-11-07T01:29:18.361620+00:00
838
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe need to reduce an integer array using a custom reduction function and an initial value. This includes iteratively applying the reduction function to each element in the array and the current accumulated value. If the array is empty, we should return the initial value.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. These are comment delimiters for a multi-line comment to help explain and document code while preventing ignored text from executing. These comments are commonly used in formal documentation for better code understanding.\n\n ```\n /**\n * Multi-line comment\n */\n ```\n\n2. This is a special type of comment called a JSDoc comment that explains that the function should take parameters named `nums`, `fn` and `init`, which are expected to be an array of numbers, a function and a number.\n\n ```\n @param {number[]} nums\n @param {Function} fn\n @param {number} init\n ```\n\n3. This is a special type of comment called a JSDoc comment that explains what the code should return, which, in this case, is a number. It helps developers and tools like code editors and documentation generators know what the function is supposed to produce.\n\n ```\n @return {number}\n ```\n\n4. This is how we define a function named reduce that takes an array `nums`, a function `fn` and a number `init` as input parameters.\n\n ```\n var reduce = function(nums, fn, init) {\n // code to be executed\n };\n ```\n\n5. This is how we can initialize a variable `sum` with the value of `init` that will be used to store the final result.\n\n ```\n let sum = init\n ```\n\n6. This starts a for loop that iterates through the elements of the input array `nums` using the variable `i` as the index.\n\n ```\n for(let i = 0; i < nums.length; i++) {\n // code to be executed\n }\n ```\n\n7. Inside the loop, we apply the custom function `fn` to the current value of `sum` and the current element in the `nums` array, updating the value of `sum`.\n\n ```\n sum = fn(sum, nums[i])\n ```\n\n8. After the loop, we should return the final value of `sum`, which is the result of reducing the array.\n\n ```\n return sum\n ```\n\n# Complexity\n- Time complexity: $O(n)$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n`n` is the length of the input array. This is because the function iterates through each element in the array once.\n\n- Space complexity: $O(1)$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThis is because it only uses a constant amount of additional space to store the `sum` and the loop counter.\n\n# Code\n```\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init) {\n let sum = init\n for(let i = 0; i < nums.length; i++) {\n sum = fn(sum, nums[i])\n }\n return sum\n};\n```
2
0
['JavaScript']
0
array-reduce-transformation
<JavaScript>
javascript-by-preeom-7vej
Code\n\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init) {\n l
PreeOm
NORMAL
2023-07-28T14:31:14.828258+00:00
2023-07-28T14:31:14.828288+00:00
848
false
# Code\n```\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init) {\n let val = init;\n for (let i = 0; i < nums.length; i++) {\n val = fn(val, nums[i]);\n }\n return val;\n};\n```
2
0
['JavaScript']
0
array-reduce-transformation
DAY 6 of JS challenge!⏳Easy solution with explanation!🚀Beginner friendly!📈
day-6-of-js-challengeeasy-solution-with-1edoy
\n# Approach\n1. To implement the reduce function, we can iterate over each element of the array using a for loop\n2. apply the reducer function to the current
deleted_user
NORMAL
2023-05-27T13:08:13.418673+00:00
2023-06-02T09:09:37.969207+00:00
390
false
\n# Approach\n1. To implement the `reduce` function, we can iterate over each element of the array using a `for loop`\n2. apply the reducer function to the current value and the current element and store it as `val`. \n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init) {\n let val=init; //set current value\n for(let i=0;i<nums.length;i++){ //iterate over each ele in array\n val = fn(val, nums[i]);//store the val as function of the current val with the element\n }\n return val;//output\n};\n```\nKindly upvote if you found this helpful!Happy learning!
2
0
['JavaScript']
0
array-reduce-transformation
😎 Super duper easy Reduce Method | Javascript | Typescript | Brownie Tip
super-duper-easy-reduce-method-javascrip-rym2
Intuition\n Describe your first thoughts on how to solve this problem. \nThe objective of this problem is to write a function that performs a reduction transfor
Yatin-kathuria
NORMAL
2023-05-10T18:54:07.936032+00:00
2023-05-10T18:54:07.936073+00:00
958
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe objective of this problem is to write a function that performs a reduction transformation based on the output of a callback function with arguments `accumulator` and `current value`. The value obtained by calling fn must be taken `accumulator` for next function call.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThis probelm is require to create our `Custom Reduce` function but not in `Array.prototype`.\n\nTo achieve this, we can create a variable named `accumulator` which will assign with initial value and start looping over each element in the `nums` array. For each element, we call the fn function with `accumulator` and value as arguments, and reassign accumulator with returned value. At last return the accumulator.\n\nBy using this approach, we can reduce out the input array efficiently and elegantly.\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n``` javascript []\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init) {\n let accumulator = init;\n nums.forEach(num => {\n accumulator = fn(accumulator, num)\n })\n\n return accumulator\n};\n```\n``` typescript []\ntype Fn = (accum: number, curr: number) => number\n\nfunction reduce(nums: number[], fn: Fn, init: number): number {\n let accumulator = init;\n nums.forEach(num => {\n accumulator = fn(accumulator, num)\n })\n\n return accumulator\n};\n```\n\n# Brownie Learning :\nIf you understand the above function then to make it run similar to JS reduce HOC method. We just need to change 3 things.\n1. remove the first `nums` argument from function defination.\n2. create a variable name `nums` and assign it with keyword `this`. Why ? because keyword `this` will hold the array on which our custom reduce method called.\n3. assign reduce method to `Array.prototype[CUSTOME_REDUCE_METHOD_NAME] = reduce`\n\nHurray! We have our own custom reduce method similar to JS reduce method.\n\n``` javascript\nArray.prototype.myReduce = function(fn, init) {\n let nums = this\n let accumulator = init;\n nums.forEach(num => {\n accumulator = fn(accumulator, num)\n })\n\n return accumulator\n};\n```
2
0
['Array', 'TypeScript', 'JavaScript']
0
array-reduce-transformation
JavaScript || Day 6 of 30 Days Challange ✅✅
javascript-day-6-of-30-days-challange-by-3tg0
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
Shubhamjain287
NORMAL
2023-05-10T18:12:30.361425+00:00
2023-05-10T18:12:30.361463+00:00
609
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/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init) {\n\n for(let i=0; i<nums.length; i++){\n init = fn(init, nums[i]);\n }\n\n return init;\n};\n```
2
0
['JavaScript']
0
array-reduce-transformation
Easy to understand || JS
easy-to-understand-js-by-yashwardhan24_s-auax
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
yashwardhan24_sharma
NORMAL
2023-05-10T15:30:21.878283+00:00
2023-05-10T15:30:21.878329+00:00
947
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/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init) {\n if(!nums.length){\n return init;\n } \n let sum=init;\n for(let value of nums){\n sum = fn(sum, value);\n }\n return sum; \n};\n```
2
0
['JavaScript']
0
array-reduce-transformation
Easy and simple approach!!
easy-and-simple-approach-by-mrigank_2003-6vs4
\n\n# Code\n\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init)
mrigank_2003
NORMAL
2023-05-10T11:17:24.256147+00:00
2023-05-10T11:17:24.256189+00:00
995
false
\n\n# Code\n```\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init) {\n var ans=init;\n for(var i=0; i<nums.length; i++){\n ans=fn(ans, nums[i]);\n }\n return ans;\n};\n```
2
0
['JavaScript']
0
array-reduce-transformation
3 Different Method || Beginner Friendly || Day 6 || Explained
3-different-method-beginner-friendly-day-t2bn
Using Built in reduce\nIn this method we use built in reduce() which is provided by javascript.\n\n# Code\n\nvar reduce = function (nums, fn, init) {\n return
mdadil9
NORMAL
2023-05-10T06:51:00.900086+00:00
2023-05-10T06:51:00.900138+00:00
124
false
# Using Built in reduce\nIn this method we use built in ```reduce()``` which is provided by javascript.\n\n# Code\n```\nvar reduce = function (nums, fn, init) {\n return nums.reduce(fn,init);\n};\n```\n\n# Using For Loop\nIn this solution we use conventional for loop to iterate each element of array. Firstly we take ans variable ans and assign it to inital value then we itreate over array using for loop and pass ans and element of array to function ```ans = fn(ans,nums[i])``` .\n\n# Code\n```\nvar reduce = function (nums, fn, init) {\n let ans = init;\n for (let i = 0; i < nums.length; i++) {\n ans = fn(ans, nums[i]);\n }\n return ans;\n};\n```\n\n# Using forEach \n\nIn this we use builtin ```forEach()``` which is provided by javascript.\n# Code\n```\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init) {\n let ans = init;\n\n nums.forEach((n) => {\n ans = fn(ans,n);\n });\n\n return ans;\n};\n```\n![478xve.jpg](https://assets.leetcode.com/users/images/996b2059-933d-42cd-bf7e-820cc4ba5e91_1683701398.1942718.jpeg)\n
2
0
['JavaScript']
0
array-reduce-transformation
Very easy and simple solution in JavaScript. Wow. (0_o)
very-easy-and-simple-solution-in-javascr-e4a4
Code\n\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init) {\n
AzamatAbduvohidov
NORMAL
2023-05-10T05:06:23.541344+00:00
2023-05-10T05:06:23.541392+00:00
641
false
# Code\n```\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init) {\n for(let i = 0; i < nums.length; i++) {\n init = fn(init, nums[i])\n }\n return init\n};\n```
2
0
['JavaScript']
2
array-reduce-transformation
1 Line | 2 Line | Javascript | Typescript
1-line-2-line-javascript-typescript-by-i-zsod
Code\n1 Line\n\nJavascript\n\nvar reduce = function(nums, fn, init,i = 0) {\n return (i === nums.length ? init : reduce(nums,fn,fn(init,nums[i]),i+1));\n};\n
includerajat
NORMAL
2023-05-10T04:44:47.776564+00:00
2023-05-10T04:44:47.776607+00:00
310
false
# Code\n`1 Line`\n\n`Javascript`\n```\nvar reduce = function(nums, fn, init,i = 0) {\n return (i === nums.length ? init : reduce(nums,fn,fn(init,nums[i]),i+1));\n};\n```\n`Typescript`\n```\nfunction reduce(nums: number[], fn: Fn, init: number,i: number = 0): number {\n return i === nums.length ? init : reduce(nums,fn,fn(init,nums[i]),i + 1);\n};\n```\n\n`2 Line`\n\n`Javascript`\n```\nvar reduce = function(nums, fn, init) {\n for(let i=0;i<nums.length;i++) init = fn(init,nums[i]);\n return init;\n};\n```\n\n`Typescript`\n```\nfunction reduce(nums: number[], fn: Fn, init: number): number {\n for(let i=0;i<nums.length;i++) init = fn(init,nums[i]);\n return init;\n};\n```
2
0
['TypeScript', 'JavaScript']
0
array-reduce-transformation
Array Reduce
array-reduce-by-sourasb-iv3t
we are using an arrow function to define the reduce function itself, and another arrow function to define the function passed to the forEach loop. The forEach l
sourasb
NORMAL
2023-05-10T01:43:16.977833+00:00
2023-05-10T01:43:16.977884+00:00
456
false
we are using an arrow function to define the `reduce` function itself, and another arrow function to define the function passed to the `forEach` loop. The `forEach` loop iterates through each element of the `nums` array and applies the `reducer` function `fn` to it and the accumulated value. We update the accumulated value at each iteration, starting with the initial value `init`. Finally, we return the final accumulated value.\n\n# Code\n```\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nconst reduce = (nums, fn, init) => {\n let val = init;\n nums.forEach(num => {\n val = fn(val, num);\n });\n return val;\n}\n\n```
2
0
['JavaScript']
1
array-reduce-transformation
🔥🚀 4 Easy solution with Video Explanation in JS & TS 🔥 | Learn concepts first ✅
4-easy-solution-with-video-explanation-i-refp
\n# Video explanation \nVideo link\n\n___\n\n\n## Intution - steps to think (explained in video too)\n The problem is asking us to return a reduced array \n we
ady_codes
NORMAL
2023-05-10T00:25:34.310835+00:00
2023-05-10T00:53:28.132930+00:00
184
false
\n# Video explanation \n[Video link](https://youtu.be/10iEbeg30mE)\n\n___\n\n\n## Intution - steps to think (explained in video too)\n* The problem is asking us to return a reduced array \n* we will start by declaring the variable and return it\n* between declaration and return, we will loop over the array and try to apply the given function to it.\n\n\n---\n\n\n# Complexity\n\n### Time complexity:\nThe time complexity of the above solution is O(n), where n is the length of the input array arr.\n\n### Space complexity:\nThe space complexity of the solution is O(1) as well. This is because we are just using the variable to store the result, nothing else.\n\n# Code\n\n\n```javascript []\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init) {\n let res = init;\n for (let i = 0; i < nums.length; i++) {\n res = fn(res, nums[i])\n }\n return res\n};\n```\n```typescript []\nconst reduce = function(nums: number[], fn: (acc: number, curr: number) => number, init: number): number {\n let res: number = init;\n for (let i = 0; i < nums.length; i++) {\n res = fn(res, nums[i])\n }\n return res\n};\n```\n\n```javascript []\n\n\n/*Solution 2*/\n var reduce = function (nums, fn, init) {\n let res = init;\n nums.map(x => (res = fn(res, x)));\n\n return res;\n};\n\n/* Solution 3 */\n// var reduce = function (nums, fn, init) {\n// let res = init;\n// nums.forEach(x => (res = fn(res, x)));\n\n// return res;\n// };\n\n/*Solution 4*/\n// var reduce = function(nums, fn, init) {\n// let ans = init;\n// for (let i of nums)\n// ans = fn(ans, i);\n \n// return ans;\n// };\n\n\n```\n\n\nOther good resources:-\n* [My video explanation]()\n* [Loops in JS](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration)\n* [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)\n* [Filter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)\n* [Reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce)\n\n\n# Important links\n* [Join 100+ other JS lovers](https://discord.gg/2BxFN63EFc) \uD83D\uDE80\n* [Reach out to me on Linkedin.](https://www.linkedin.com/in/anshulontech/) \uD83D\uDE4F\uD83C\uDFFB\n\n\n\n![upvote me.jpeg](https://assets.leetcode.com/users/images/bc2afe3a-768d-42cb-aba8-39023ef69af2_1683593182.9982169.jpeg)\n
2
0
['JavaScript']
0
array-reduce-transformation
🔥🔥Easy Simple JavaScript Solution 🔥🔥
easy-simple-javascript-solution-by-motah-3na7
\n\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init) {\n let
Motaharozzaman1996
NORMAL
2023-04-19T02:27:32.850907+00:00
2023-04-19T02:27:32.850946+00:00
1,675
false
\n```\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init) {\n let ans=init;\n for(const i of nums){\n ans=fn(ans,i);\n\n }\n return ans;\n};\n```
2
0
['JavaScript']
1
array-reduce-transformation
Robust Code with explanation
robust-code-with-explanation-by-santosh-nuaap
Intuition\nThe reduce function is used to apply a given function to each element of an array and return a single accumulated value.\n\n# Approach\n- Check if th
santosh-setty
NORMAL
2023-04-15T12:31:23.861589+00:00
2023-04-15T12:31:23.861619+00:00
454
false
# Intuition\nThe **reduce** function is used to apply a given function to each element of an array and return a single accumulated value.\n\n# Approach\n- Check if the input array is empty. If it is, return the initial value.\n- If an initial value is provided, set the accumulator to the initial value. Otherwise, set it to the first element of the array.\n- Determine the starting index for the loop based on whether an initial value was provided. If an initial value was provided, start the loop at index 0. Otherwise, start at index 1.\n- Iterate over the input array using a simple for loop starting at the determined starting index.\n- Apply the given function to the accumulator and the current element of the array, and update the accumulator with the result.\n- Once all elements of the array have been processed, return the final accumulated value.\n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(1)\n\n# Code\n```\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init) {\n // Return init value if array is empty\n if (nums.length === 0) return init;\n\n // If init value is undefine then first item in the array is assigned\n let accumilate = init ?? nums[0];\n\n // If first item of the the array is assigned, then start count from 1 if not 0\n let start = (accumilate === init) ? 0 : 1;\n\n // Simple for loop\n for (let i = start; i < nums.length; i++) {\n accumilate = fn(accumilate, nums[i]);\n }\n\n return accumilate;\n};\n```
2
0
['Array', 'JavaScript']
1
array-reduce-transformation
🔥Easy 1 Line sol🔥
easy-1-line-sol-by-sahillather002-oepw
\n\n# Code\n\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init)
sahillather002
NORMAL
2023-04-12T03:24:24.601745+00:00
2023-04-12T03:24:24.601777+00:00
2,406
false
\n\n# Code\n```\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init) {\n return nums.reduce(fn,init)\n};\n```
2
0
['JavaScript']
5
array-reduce-transformation
Simple solution using Array.forEach() method.
simple-solution-using-arrayforeach-metho-6tw0
Code\n\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init) {\n
mhetreayush
NORMAL
2023-04-12T01:34:40.985812+00:00
2023-04-12T01:34:40.985857+00:00
977
false
# Code\n```\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init) {\n if(nums.length){nums.forEach(num=> init = fn(init, num))}\n return init\n};\n```
2
0
['JavaScript']
1
array-reduce-transformation
Step-by-Step Solution, Easy And Clean Code
step-by-step-solution-easy-and-clean-cod-5gj1
IntuitionThe provided function aims to replicate the behavior of the Array.prototype.reduce method. This function is used to apply a reducer function on each el
PrathmeshJejurkar
NORMAL
2025-04-12T08:00:55.857585+00:00
2025-04-12T08:00:55.857585+00:00
2
false
# Intuition The provided function aims to replicate the behavior of the Array.prototype.reduce method. This function is used to apply a reducer function on each element of an array, resulting in a single output value. The initial value is used as the starting point, and the reducer function is applied sequentially to each element of the array, updating the accumulated result. # Approach 1.⚙️ Initialization: Start with an initial value (init) which will act as the initial accumulator (accum). 2.🔄 Iteration: Use the forEach method to iterate through each element of the array. For each element, apply the provided function (fn) which takes two arguments: the current accumulator value and the current element. Update the accumulator with the result of the function. 3.🏁 Return: After the iteration completes, return the accumulated result. # Complexity 1.⏱️ Time Complexity: O(n) The function iterates through each element of the array exactly once, leading to a linear time complexity. 2.🗃️ Space Complexity: O(1) The function uses a fixed amount of space for the accumulator and does not require additional space that scales with the input size. # Code ```javascript [] /** * @param {number[]} nums * @param {Function} fn * @param {number} init * @return {number} */ var reduce = function(nums, fn, init) { let accum = init; nums.forEach(element => { accum = fn(accum, element) }); return accum }; ```
1
0
['JavaScript']
0
array-reduce-transformation
Simple JavaScript Solution
sime-javascript-solution-by-gokulram2221-fbav
Code
gokulram2221
NORMAL
2025-04-05T05:58:51.197840+00:00
2025-04-05T05:59:04.028915+00:00
81
false
# Code ```javascript [] var reduce = (nums, fn, init) => { nums.forEach(num => init = fn(init, num)); return init; }; ```
1
0
['JavaScript']
0
array-reduce-transformation
✅ 🌟 JAVASCRIPT SOLUTION ||🔥 BEATS 100% PROOF🔥|| 💡 CONCISE CODE ✅ || 🧑‍💻 BEGINNER FRIENDLY
javascript-solution-beats-100-proof-conc-spwb
Complexity Time complexity:O(n) Space complexity:O(1) Code
Shyam_jee_
NORMAL
2025-03-23T13:29:54.735247+00:00
2025-03-23T13:29:54.735247+00:00
150
false
# Complexity - Time complexity:$$O(n)$$ <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity:$$O(1)$$ <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```javascript [] /** * @param {number[]} nums * @param {Function} fn * @param {number} init * @return {number} */ var reduce = function(nums, fn, init) { var val=0; if(nums.length>0) val=fn(init, nums[0]); else return init; for(var i=1;i<nums.length;i++) { val=fn(val, nums[i]); } return val; }; ```
1
0
['JavaScript']
0
array-reduce-transformation
Array Reduce Transformation
array-reduce-transformation-by-yassinsis-5cke
IntuitionApproachComplexity Time complexity: Space complexity: Code
yassinsisino
NORMAL
2025-03-21T15:00:29.402931+00:00
2025-03-21T15:00:29.402931+00:00
99
false
![Capture d’écran 2025-03-21 à 15.59.32.png](https://assets.leetcode.com/users/images/c791c798-945c-460e-bf99-a44b6db348ac_1742569187.090847.png) # Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```typescript [] type Fn = (accum: number, curr: number) => number function reduce(nums: number[], fn: Fn, init: number): number { let value = init nums.forEach(num => value = fn(value, num)) return value }; ```
1
0
['TypeScript']
0
array-reduce-transformation
leetcodedaybyday - Beats 83.97% with JavaScript - 90.39% with TypeScript
leetcodedaybyday-beats-8397-with-javascr-42iz
IntuitionThe problem requires implementing a reduce function that iterates through an array, applies a given function to accumulate values, and returns the fina
tuanlong1106
NORMAL
2025-03-09T08:07:09.568386+00:00
2025-03-09T08:07:09.568386+00:00
132
false
# **Intuition** The problem requires implementing a `reduce` function that iterates through an array, applies a given function to accumulate values, and returns the final result. This is similar to the built-in `Array.prototype.reduce()` method in JavaScript. # **Approach** 1. **Initialize** `res` with `init` (the starting value). 2. **Iterate** through each element in `nums`: - Apply the function `fn(res, num)`, where `res` is the accumulated value and `num` is the current element. - Update `res` with the returned value. 3. **Return `res`** after processing all elements. # **Complexity** - **Time Complexity:** \(O(n)\) - We iterate through the entire array once. - **Space Complexity:** \(O(1)\) - We only use a single variable `res` for accumulation. --- # Code ```javascript [] /** * @param {number[]} nums * @param {Function} fn * @param {number} init * @return {number} */ var reduce = function(nums, fn, init) { let res = init; for (let i = 0; i < nums.length; i++){ res = fn(res, nums[i]) } return res; }; ``` ```typescript [] type Fn = (accum: number, curr: number) => number function reduce(nums: number[], fn: Fn, init: number): number { let res = init; for (let i = 0; i < nums.length; i++){ res = fn(res, nums[i]); } return res; }; ```
1
0
['TypeScript', 'JavaScript']
0
array-reduce-transformation
JavaScript
javascript-by-adchoudhary-pogj
Code
adchoudhary
NORMAL
2025-03-03T01:39:07.876187+00:00
2025-03-03T01:39:07.876187+00:00
171
false
# Code ```javascript [] /** * @param {number[]} nums * @param {Function} fn * @param {number} init * @return {number} */ var reduce = function(nums, fn, init) { let val = init; for (let i = 0; i < nums.length; i++) { val = fn(val, nums[i]); } return val; }; ```
1
0
['JavaScript']
0
array-reduce-transformation
🌟 Custom Reduce Function 🌟
custom-reduce-function-by-cx_pirate-rzgq
🧠 IntuitionThe provided function aims to replicate the behavior of the Array.prototype.reduce method. This function is used to apply a reducer function on each
cx_pirate
NORMAL
2025-02-12T02:24:52.494337+00:00
2025-02-12T02:24:52.494337+00:00
173
false
# 🧠 Intuition The provided function aims to replicate the behavior of the Array.prototype.reduce method. This function is used to apply a reducer function on each element of an array, resulting in a single output value. The initial value is used as the starting point, and the reducer function is applied sequentially to each element of the array, updating the accumulated result. # 🛠️ Approach 1. **⚙️ Initialization:** - Start with an initial value (init) which will act as the initial accumulator (accum). 2. **🔄 Iteration:** - Use the forEach method to iterate through each element of the array. - For each element, apply the provided function (fn) which takes two arguments: the current accumulator value and the current element. - Update the accumulator with the result of the function. 3. **🏁 Return:** - After the iteration completes, return the accumulated result. # 📊 Complexities 1. **⏱️ Time Complexity: O(n)** - The function iterates through each element of the array exactly once, leading to a linear time complexity. 2. **🗃️ Space Complexity: O(1)** - The function uses a fixed amount of space for the accumulator and does not require additional space that scales with the input size. # 📝 Code ```javascript [] /** * @param {number[]} nums * @param {Function} fn * @param {number} init * @return {number} */ var reduce = function(nums, fn, init) { let accum = init; nums.forEach(element => { accum = fn(accum, element) }); return accum }; ```
1
0
['JavaScript']
0
array-reduce-transformation
Array Reduce Transformation | JS Solution | Beats 95.37%🕐
array-reduce-transformation-js-solution-u8mca
Code
shenurarasheen
NORMAL
2025-02-02T14:07:50.709805+00:00
2025-02-02T14:14:37.956252+00:00
218
false
# Code ```javascript [] /** * @param {number[]} nums * @param {Function} fn * @param {number} init * @return {number} */ var reduce = function(nums, fn, init) { let accum = init; for(let num of nums){ accum = fn(accum, num); } return accum; }; ```
1
0
['JavaScript']
0
array-reduce-transformation
Using for loop
using-for-loop-by-eliasyahya100-z0h9
IntuitionFirst, I used an if statement to check if nums.length is greater than 0. If it's not, then return init. Then, I created a variable called val to store
eliasyahya100
NORMAL
2025-01-27T07:29:57.828637+00:00
2025-01-27T07:29:57.828637+00:00
112
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> First, I used an `if` statement to check if `nums.length` is greater than `0`. If it's not, then return `init`. Then, I created a variable called `val` to store the output of the reducer function `fn`. I assigned an initial value of `0` to the val variable. Next, I used a `for` loop to iterate over every element in the `nums` array. For each element, I let it equal `val` and then set `init` to be the same as the value of `val` because, in every subsequent computation, `init` needs to be equal to the previous result, which is `val`. Once the `for` loop finishes (when it becomes `=` to `nums.length`), I returned the latest value of `val` from the loop. I hope this clarifies things! Let me know if you need further explanations. 😊 # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> **Time Complexity: O(n)** The code iterates through the nums array once using a for loop. The number of operations inside the loop is directly proportional to the length of the array. Therefore, the time complexity is linear, denoted as O(n), where n is the length of the nums array. - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> **Space Complexity: O(1)** The code uses a fixed amount of extra space regardless of the input size. It declares a few variables (val, i) and uses some constant space for operations. This extra space doesn't scale with the size of the input array. Therefore, the space complexity is constant, denoted as O(1). # Code ```javascript [] /** * @param {number[]} nums * @param {Function} fn * @param {number} init * @return {number} */ var reduce = function (nums, fn, init) { if (nums.length > 0){ let val = 0 for (let i = 0; i < nums.length; ++i){ val = fn(init,nums[i]) init = val } return val } else { return init } }; ```
1
0
['JavaScript']
0
array-reduce-transformation
Using Array.Map()
using-arraymap-by-eliasyahya100-lz85
IntuitionFirst, I used an if statement to return the init value if the length of the nums array is 0 (an empty array). Then, I used the nums.map() method to ite
eliasyahya100
NORMAL
2025-01-27T06:49:09.375440+00:00
2025-01-27T07:32:58.115757+00:00
66
false
# Intuition First, I used an `if` statement to return the `init` value if the length of the nums array is `0` (an empty array). Then, I used the `nums.map()` method to iterate over every element inside the `nums` array. For each element, I applied the provided reducer function `fn` and stored the returned value in a variable called `val`. Since in the next computation the `init` should be equal to the last computation result, I set `init = val`. Then, I returned the result of the map under `val`. The `map()` method should return a new array `newArray` with all the computation results. Since the final result will be at the end of the array, I retrieved it by returning the last element of the array using `newArray[newArray.length - 1]`. Kindly, if you like my answer and explanation, please upvote me. 😊 # - Time complexity: **Combining these steps, the overall time complexity is O(n).** 1- Empty Check: The `if` statement to check if `nums.length` is `0` has a constant time complexity, O(1). 2- Map Method: The `nums.map()` method iterates over every element of the array, so its time complexity is O(n), where `n` is the length of the `nums` array. 3- Reducer Function: The function `fn` is applied to each element in the array. Assuming the function `fn` operates in constant time, O(1), the total time complexity is O(n). # - Space complexity: **Combining these steps, the overall space complexity is O(n).** 1- Empty Check: The space complexity of the `if` statement is O(1). 2- Map Method: The `nums.map()` method creates a new array, newArray, with the same length as the `nums` array. Therefore, the space complexity is O(n). 3- Intermediate Values: The variable `val` stores intermediate computation results, which takes O(1) space. # Code ```javascript [] /** * @param {number[]} nums * @param {Function} fn * @param {number} init * @return {number} */ var reduce = function (nums, fn, init) { if (nums.length === 0){ return init } newArray = nums.map( (num)=>{ val = fn(init,num); init = val return val } ) return newArray[newArray.length - 1] }; ```
1
0
['JavaScript']
0
array-reduce-transformation
Reduce in JavaScript and TypeScript
reduce-in-javascript-and-typescript-by-x-xxom
Complexity Time complexity: O(n) Space complexity: O(1) Code
x2e22PPnh5
NORMAL
2025-01-22T18:01:39.326722+00:00
2025-01-22T18:01:39.326722+00:00
104
false
# Complexity - Time complexity: O(n) - Space complexity: O(1) # Code ```javascript [] /** * @param {number[]} nums * @param {Function} fn * @param {number} init * @return {number} */ var reduce = function(nums, fn, init) { const length = nums.length; let i = 0 for (i; i < length; i++) { init = fn(init, nums[i]); }; return init; }; ``` ```typescript [] type Fn = (accum: number, curr: number) => number function reduce(nums: number[], fn: Fn, init: number): number { const length: number = nums.length; let i: number = 0; for (i; i < length; i++) { init = fn(init, nums[i]); }; return init; }; ```
1
0
['TypeScript', 'JavaScript']
0
array-reduce-transformation
👉🏻SHORT ||EASY TO UNDERSTAND SOLUTION || JS
short-easy-to-understand-solution-js-by-g82bs
IntuitionApproachComplexity Time complexity: Space complexity: Code
Siddarth9911
NORMAL
2025-01-18T17:29:36.434450+00:00
2025-01-18T17:29:36.434450+00:00
135
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```javascript [] /** * @param {number[]} nums * @param {Function} fn * @param {number} init * @return {number} */ var reduce = function(nums, fn, init) { if (nums.length === 0){return init;} let res = init; for (let i = 0; i < nums.length; i++) { res = fn(res, nums[i]); } return res; }; ```
1
0
['JavaScript']
0
array-reduce-transformation
Array Reduce Transformation: JS Clear Explanations with Code Examples
array-reduce-transformation-js-clear-exp-9f0g
DescriptionThis implementation of reduce replicates the functionality of the built-in Array.prototype.reduce method. It takes an array, a callback function, and
eduperezn
NORMAL
2025-01-16T03:03:16.212089+00:00
2025-01-16T03:03:16.212089+00:00
90
false
# Description This implementation of `reduce` replicates the functionality of the built-in `Array.prototype.reduce` method. It takes an array, a callback function, and an initial value, then iterates over the array to produce a single accumulated result. The function demonstrates key JavaScript concepts such as higher-order functions, iteration, and immutability. # Key Concepts: - **Higher-order functions:** Functions that accept other functions as arguments or return functions. - **Callback functions:** A function passed as an argument to another function, executed during the iteration. - **Iteration (for-of loop):** A clean and concise way to iterate over arrays in JavaScript. - **Immutability:** The initial value (init) is updated but does not mutate the original array. - **Return statement:** Used to return the final accumulated value. # Code ```javascript [] var reduce = (nums, fn, init) => { for (const num of nums) init = fn(init, num); return init; }; ``` # Code With Comments ```javascript [] /** * Custom reduce function implementation. * @param {number[]} nums - Array of numbers to iterate over. * @param {Function} fn - Callback function to process each element. * @param {number} init - Initial value for the accumulator. * @return {number} - Final accumulated value. */ var reduce = (nums, fn, init) => { // Iteration (for-of loop): Loops through each element in the array. for (const num of nums) { // Callback function: 'fn' processes the current accumulator and array element. init = fn(init, num); // Immutability: 'init' is updated without modifying the array. } // Return statement: Returns the final accumulated value. return init; }; /** * Example usage: */ const nums = [1, 2, 3, 4]; const sum = reduce(nums, (acc, curr) => acc + curr, 0); // Higher-order function: Passes a callback to 'reduce'. console.log(sum); // Output: 10 ```
1
0
['JavaScript']
0
array-reduce-transformation
Implementing Custom Array Reduction Without Using Built-in Methods 🛠️➡️📉
implementing-custom-array-reduction-with-h285
Problem UnderstandingIn this problem, we are tasked with reducing an array of integers, nums, using a provided reducer function, fn, and an initial value, init.
Muhammad-Mahad
NORMAL
2025-01-12T07:16:10.084743+00:00
2025-01-12T07:16:10.084743+00:00
71
false
# Problem Understanding In this problem, we are tasked with reducing an array of integers, nums, using a provided reducer function, fn, and an initial value, init. The goal is to sequentially apply fn to accumulate a single result, starting with init and processing each element in nums. Notably, we must achieve this without utilizing the built-in Array.prototype.reduce method. # Approach 1. ## Initialize the Accumulator: Begin by setting a variable, total, to the initial value, init. This variable will hold the cumulative result as we iterate through the array. 2. ## Iterate Through the Array: Use a for loop to traverse each element in nums. For each element, update total by applying the reducer function fn to the current total and the current array element. 3. ## Return the Final Result: After processing all elements, total contains the reduced value, which we then return. This method ensures that we manually perform the reduction operation without relying on the built-in reduce method, thereby meeting the problem's constraints. # Complexity - Time complexity: O(n) - Space complexity: O(1) # Example Usage: Suppose we have an array nums = [1️⃣, 2️⃣, 3️⃣, 4️⃣], a reducer function fn = (a, b) => a + b, and an initial value init = 0️⃣. Using our reduce function: ``` const result = reduce(nums, fn, init); console.log(result); // Output: 🔟 ``` Here, the function computes the sum of all elements in the array, starting from the initial value 0️⃣. This approach provides a clear and efficient way to perform array reduction without using the built-in reduce method, adhering to the problem's requirements. # Code ```javascript [] /** * @param {number[]} nums * @param {Function} fn * @param {number} init * @return {number} */ var reduce = function(nums, fn, init) { let total = init for(let i = 0; i < nums.length; i++){ total = fn(total, nums[i]) } return total }; ```
1
0
['JavaScript']
0
array-reduce-transformation
Array Reduce Transformation - Manually & BuiltIn fns
array-reduce-transformation-manually-bui-bryq
Intuition\nMy Intution in this question is so Simple, to use directly reducer function, but it is illegal in this, so i construct the Idea to make the same resu
Ujjwal_Saini007
NORMAL
2024-12-04T05:48:48.135461+00:00
2024-12-04T05:48:48.135486+00:00
45
false
# Intuition\nMy Intution in this question is so Simple, to use directly reducer function, but it is illegal in this, so i construct the Idea to make the same result as possible with not using as direct resulting function by manual method to solve it.\n\n# Approach\n***Approach for Code 1:*** This implementation uses the built-in Array.prototype.reduce function to directly compute the result by applying the provided fn iteratively over nums, starting with the init value.\n\n***Approach for Code 2:*** This manual implementation initializes the result with init and iterates through nums using a for loop, applying fn at each step to update the result.\n\n# Complexity\n- Time complexity: **O(n)**\n\n- Space complexity: **O(1)**\n\n# Illegal Try - Use Direct built-in fn:\n### Code\n```javascript []\nvar reduce = function(nums, fn, init) {\n return nums.reduce(fn,init);\n};\n```\n\n# Best Method:\n### Code\n```javascript []\nvar reduce = function(nums, fn, init) {\n let result = init;\n if(nums.length == 0) return result;\n for(let i=0; i<nums.length; i++){\n result = fn(result, nums[i]);\n }\n return result;\n};\n```
1
0
['JavaScript']
0
array-reduce-transformation
JavaScript | Easy | Simple
javascript-easy-simple-by-siyadhri-nbar
\n\n# Code\njavascript []\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(num
siyadhri
NORMAL
2024-10-15T14:19:15.613773+00:00
2024-10-15T14:19:15.613807+00:00
102
false
\n\n# Code\n```javascript []\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init) {\n return nums.reduce(fn,init);\n};\n```
1
0
['JavaScript']
1
array-reduce-transformation
Beginner-Friendly Solution Using JavaScript || Clear
beginner-friendly-solution-using-javascr-vhf3
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
truongtamthanh2004
NORMAL
2024-08-19T15:44:18.007241+00:00
2024-08-19T15:44:18.007277+00:00
841
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```javascript []\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init) {\n return nums.reduce(fn, init)\n};\n```
1
0
['JavaScript']
1
array-reduce-transformation
Array Reduce Transformation w/ TypeScript
array-reduce-transformation-with-typescr-1dtk
Code
skywalkerSam
NORMAL
2024-07-26T18:00:32.967027+00:00
2025-02-23T23:03:15.199485+00:00
3
false
# Code ``` type Fn = (accum: number, curr: number) => number function reduce(nums: number[], fn: Fn, init: number): number { let reducedVal: number = 0; let acc: number = init; if (nums.length === 0) { return init; } for (let i: number = 0; i < nums.length; i++) { reducedVal = fn(acc, nums[i]); acc = reducedVal; } return reducedVal; }; ```
1
0
['TypeScript']
0
array-reduce-transformation
Easy 1 line.
easy-1-line-by-pratik_pathak_05-99h7
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
Pratik_Pathak_05
NORMAL
2024-05-05T13:05:14.483738+00:00
2024-05-05T13:05:14.483774+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```\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init) {\n return nums.reduce(fn,init)\n};\n```
1
0
['JavaScript']
0
array-reduce-transformation
Array Reduce Transformation
array-reduce-transformation-by-mohammed_-bq63
Single line answer\n Describe your first thoughts on how to solve this problem. \n\nUse the fn as first parameter and and init as second parameter of reduce met
Mohammed_Thasleem_MK
NORMAL
2024-03-28T15:02:46.655033+00:00
2024-03-28T15:02:46.655069+00:00
1
false
Single line answer\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nUse the fn as first parameter and and init as second parameter of reduce method\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/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init) {\n return nums.reduce(fn,init)\n};\n```
1
0
['JavaScript']
0
array-reduce-transformation
Simple code :stom Array Reduction Function in JavaScript"
simple-code-stom-array-reduction-functio-0239
Intuition\nThe goal of this function is to reduce an array of numbers by applying a given reduction function to each element sequentially, starting with an init
nishantpriyadarshi60
NORMAL
2023-10-15T03:44:07.514465+00:00
2023-10-15T03:44:07.514485+00:00
288
false
# Intuition\nThe goal of this function is to reduce an array of numbers by applying a given reduction function to each element sequentially, starting with an initial value. This is essentially a custom implementation of a reduce operation similar to the built-in Array.reduce method in JavaScript.\n\n# Approach\n1 .First, the function checks if the input array nums is empty. If it is, it returns the initial value init because there are no elements to process.\n\n2 .If the array is not empty, it initializes an accumulator variable with the initial value init.\n\n3 .Then, it iterates through the array using a for loop, starting from the first element to the last.\n\n4 .During each iteration, it applies the provided reduction function fn to the current value of the accumulator and the current element of the array (nums[i]), storing the result back in the accumulator.\n\n5 .After processing all elements in the array, the final value of the accumulator represents the result of the reduction operation, and this value is returned.\n\n# Complexity\n- Time complexity:\n O(n)\n- Space complexity:\nO(1)\n# Code\n```\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init) {\n\n if(nums.length === 0){\n return init;\n }\n\n\n let accumulator = init\n for(let i = 0;i < nums.length;i++){\n accumulator = fn(accumulator, nums[i])\n }\n return accumulator;\n};\n```
1
0
['JavaScript']
2
array-reduce-transformation
2626:Array Reduce transformation|| Simple JavaScript Solution||Memory Beats 96.58%
2626array-reduce-transformation-simple-j-zrts
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
SAITEJA2474
NORMAL
2023-08-23T18:51:41.171543+00:00
2023-08-23T18:54:32.501274+00:00
203
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init) {\n val=init\n for (i=0;i<nums.length;i++){\n val=fn(val,nums[i])\n }\n \n return val\n};\n```
1
0
['JavaScript']
0
array-reduce-transformation
Easy || Simple || Fast with detailed explanation
easy-simple-fast-with-detailed-explanati-oc0p
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nCalling out the function for the whole array and returning the value init
VinayakNegi
NORMAL
2023-05-18T05:25:52.479004+00:00
2023-05-18T05:25:52.479054+00:00
512
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nCalling out the function for the whole array and returning the value init if the array is empty.\n\n# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(1)$$ \n\n# Code\n```\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init) {\n let out=init;\n if(nums.length === 0)\n return init;\n for(let i=0;i< nums.length;i++){\n out= fn(out,nums[i])\n }\n return out;\n};\n```
1
0
['JavaScript']
1
array-reduce-transformation
✌ Simple O(N) Solution ✌
simple-on-solution-by-silvermete0r-bw9q
Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\nJavaScript []\nvar reduce = function(nums, fn, init) {\n for(let i in nums) init
silvermete0r
NORMAL
2023-05-11T02:03:37.626656+00:00
2023-05-11T02:05:36.491240+00:00
5
false
# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n``` JavaScript []\nvar reduce = function(nums, fn, init) {\n for(let i in nums) init = fn(init, nums[i]);\n return init;\n};\n```
1
0
['JavaScript']
0
array-reduce-transformation
js solution day 6
js-solution-day-6-by-abhishekvallecha20-gmxm
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
abhishekvallecha20
NORMAL
2023-05-10T19:46:08.360051+00:00
2023-05-10T19:46:08.360093+00:00
30
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/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init) {\n let val = init;\n for(let i = 0;i < nums.length; i++) val = fn(val, nums[i]);\n return val;\n};\n```
1
0
['JavaScript']
0
array-reduce-transformation
✅✅Day - 6 JavaScript Challenge || Easy || O(n)
day-6-javascript-challenge-easy-on-by-va-0npj
\n# Code\n\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init) {\
vansh_00_7
NORMAL
2023-05-10T18:50:49.555863+00:00
2023-05-10T18:50:49.555895+00:00
2,231
false
\n# Code\n```\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init) {\n if(nums.length === 0) return init;\n let val = 0;\n for(let i = 0;i < nums.length;i++){\n if(i === 0) val = fn(init,nums[i]);\n else val = fn(val,nums[i]); \n }\n return val;\n};\n```
1
0
['JavaScript']
1