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
difference-between-maximum-and-minimum-price-sum
BFS Solution ( not optimal but INTERESTING 🤓)
bfs-solution-not-optimal-but-interesting-9z9s
Intuition\n Describe your first thoughts on how to solve this problem. \nMain intuton is any node except leaf node have multiple incoming nodes which has starti
Swarnarup
NORMAL
2024-07-12T10:47:50.328782+00:00
2024-07-12T10:47:50.328813+00:00
5
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMain intuton is any node except leaf node have multiple incoming nodes which has starting point from a leaf node. Do multisearch BFS starting from all leaf Node. and shrink gradually towards the center of the cluster.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nstarting from all the node whose degree is 1.\nat every node push 2 value to the center of cluster\n1. Maximum streak formed till this node\n2. Maximum streak formed till this node excluding the leaf node from which the streak started.\n\nalso at each node update the maximum answer...\n![photo_2024-07-12_16-17-15.jpg](https://assets.leetcode.com/users/images/fa80193a-a9e6-420b-93ae-89b235eb209c_1720781258.5062275.jpeg)\n\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\naround O(nlogn) for the priority queue approach.\nO(n) (2nd approach wiithout using the priority queue)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n).\n\n# Code\n```\n////////// BFS Approach1: using Priority Queue ///////////\n\nclass Solution {\npublic:\n\n long long maxOutput(int n, vector<vector<int>>& edges, vector<int>& price) {\n if(n==1) return 0;\n unordered_map<int, vector<int>> adj;\n vector<int> degree(n, 0);\n\n for(auto i = 0; i<n-1; i++){\n int a = edges[i][0];\n int b = edges[i][1];\n adj[a].push_back(b);\n adj[b].push_back(a);\n degree[a]++; degree[b]++;\n }\n\n unordered_map<int, priority_queue<pair<int, int>>> woFirstNode;\n unordered_map<int, priority_queue<pair<int, int>>> wFirstNode;\n\n queue<int> q;\n\n for(int i = 0; i<n; i++){\n if(degree[i] == 1){\n degree[i]--;\n q.push(i);\n woFirstNode[i].push({-price[i], -1});\n wFirstNode[i].push({0, -1});\n }\n }\n\n int ans = INT_MIN;\n while(!q.empty()){\n int node = q.front(); q.pop();\n int wFN = wFirstNode[node].top().first;\n int woFN = woFirstNode[node].top().first;\n \n if(wFirstNode[node].top().second == woFirstNode[node].top().second){\n if(wFirstNode[node].size()>1){\n int w1 = wFirstNode[node].top().first, wo2 = woFirstNode[node].top().first;\n wFirstNode[node].pop();\n woFirstNode[node].pop();\n int w2 = wFirstNode[node].top().first, wo1 = woFirstNode[node].top().first;\n \n ans = max(ans, max(w1+wo1+price[node], w2+wo2+price[node]));\n }\n else{\n ans = max(ans, wFN + price[node] - min(price[node], wFN-woFN));\n }\n }\n else{\n ans = max(ans, wFN + woFN + price[node]);\n }\n\n // cout<<node<<" "<<wFN<<" "<<woFN<<" "<<ans<<endl;\n\n wFN += price[node];\n woFN += price[node];\n woFirstNode.erase(node);\n wFirstNode.erase(node);\n for(int next:adj[node]){\n wFirstNode[next].push({wFN, node});\n woFirstNode[next].push({woFN, node});\n degree[next]--;\n if(degree[next] == 1){\n q.push(next);\n }\n }\n }\n\n return ans; \n }\n};\n\n\n\n\n//////////// Approach 2: without using Priority_Queue ////////////////////\n\n\n\nclass Solution {\npublic:\n\n long long maxOutput(int n, vector<vector<int>>& edges, vector<int>& price) {\n if(n==1) return 0;\n unordered_map<int, vector<int>> adj;\n vector<int> degree(n, 0);\n\n for(auto i = 0; i<n-1; i++){\n int a = edges[i][0];\n int b = edges[i][1];\n adj[a].push_back(b);\n adj[b].push_back(a);\n degree[a]++; degree[b]++;\n }\n\n unordered_map<int, vector<pair<int, int>>> woFirstNode;\n unordered_map<int, vector<pair<int, int>>> wFirstNode;\n\n queue<int> q;\n\n for(int i = 0; i<n; i++){\n if(degree[i] == 1){\n degree[i]--;\n q.push(i);\n woFirstNode[i].push_back({-price[i], -1});\n wFirstNode[i].push_back({0, -1});\n }\n }\n\n int ans = INT_MIN;\n while(!q.empty()){\n int node = q.front(); q.pop();\n int wFN = wFirstNode[node][0].first;\n int woFN = woFirstNode[node][0].first;\n \n if(wFirstNode[node][0].second == woFirstNode[node][0].second){\n // cout<<"1"<<endl;\n if(wFirstNode[node].size()>1){\n // cout<<"2"<<endl;\n int w1 = wFirstNode[node][0].first, wo2 = woFirstNode[node][0].first;\n // wFirstNode[node].pop();\n // woFirstNode[node].pop();\n int w2 = wFirstNode[node][1].first, wo1 = woFirstNode[node][1].first;\n // cout<<w1<<" "<<wo1<<" "<<w2<<" "<<wo2<<endl;\n ans = max(ans, max(w1+wo1+price[node], w2+wo2+price[node]));\n }\n else{\n // cout<<"3"<<endl;\n ans = max(ans, wFN + price[node] - min(price[node], wFN-woFN));\n }\n }\n else{\n // cout<<"4"<<endl;\n ans = max(ans, wFN + woFN + price[node]);\n }\n \n // cout<<node<<" "<<wFN<<" "<<woFN<<" "<<ans<<endl;\n\n wFN += price[node];\n woFN += price[node];\n // woFirstNode.erase(node);\n // wFirstNode.erase(node);\n for(int next:adj[node]){\n if(wFirstNode[next].size() < 2){\n // cout<<"1"<<endl;\n wFirstNode[next].push_back({wFN, node});\n woFirstNode[next].push_back({woFN, node});\n sort(wFirstNode[next].begin(), wFirstNode[next].end());\n sort(woFirstNode[next].begin(), woFirstNode[next].end());\n reverse(wFirstNode[next].begin(), wFirstNode[next].end());\n reverse(woFirstNode[next].begin(), woFirstNode[next].end());\n }\n else{\n // cout<<"2"<<endl;\n if(wFN > wFirstNode[next][0].first){\n wFirstNode[next][1] = wFirstNode[next][0];\n wFirstNode[next][0] = {wFN, node};\n }\n else if(wFN > wFirstNode[next][1].first) wFirstNode[next][1] = {wFN, node};\n if(woFN > woFirstNode[next][0].first){\n woFirstNode[next][1] = woFirstNode[next][0];\n woFirstNode[next][0] = {woFN, node};\n }\n else if(woFN > woFirstNode[next][1].first) woFirstNode[next][1] = {woFN, node};\n }\n // cout<<" "<<next<<endl;\n // for(auto x:woFirstNode[next])cout<<"wo: "<<x.first<<" "<<x.second<<endl;\n // for(auto x:wFirstNode[next])cout<<"w: "<<x.first<<" "<<x.second<<endl;\n // cout<<endl;\n degree[next]--;\n if(degree[next] == 1){\n q.push(next);\n }\n }\n }\n\n return ans; \n }\n};\n\n\n\n```
0
0
['C++']
0
difference-between-maximum-and-minimum-price-sum
Simple C++ Solution | DP on Trees
simple-c-solution-dp-on-trees-by-rj_9999-o6zz
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
rj_9999
NORMAL
2024-06-29T11:44:58.423533+00:00
2024-06-29T11:44:58.423566+00:00
31
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:\nvoid dfs(int node,int p,vector<int>sides[],vector<pair<int,int>>&dp,vector<int>& price){\n int flag=0;\n for(int i=0;i<sides[node].size();i++){\n int n=sides[node][i];\n if(n!=p){\n dfs(n,node,sides,dp,price);\n int prev1=dp[node].first;\n int prev2=dp[node].second;\n int new_prev1=price[node]+dp[n].first;\n if(new_prev1>prev1){\n dp[node].first=new_prev1;\n dp[node].second=prev1;\n }\n else{\n dp[node].second=max(dp[node].second,new_prev1);\n }\n flag=1;\n }\n }\n if(flag==0)dp[node].first=price[node];\n}\nvoid dfs2(int node,int p,vector<int>sides[],vector<pair<int,int>>&dp,vector<int>&price,vector<int>&out){\n for(int i=0;i<sides[node].size();i++){\n int newn=sides[node][i];\n if(newn!=p){\n\n int fir=dp[node].first;\n int sec=dp[node].second;\n int outer=out[node];\n int p=price[node];\n if(p+dp[newn].first==fir){\n int poss1=0;\n if(sec!=0)poss1=price[newn]+sec;\n else poss1=price[newn]+sec+price[i];\n int poss2=price[newn]+out[node];\n out[newn]=max(poss1,poss2);\n }\n else{\n int poss1=price[newn]+fir;\n int poss2=price[newn]+out[node];\n out[newn]=max(poss1,poss2);\n }\n dfs2(newn,node,sides,dp,price,out);\n }\n }\n}\n long long maxOutput(int n, vector<vector<int>>& edges, vector<int>& price) {\n vector<int>sides[n];\n for(int i=0;i<edges.size();i++){\n int n1=edges[i][0];\n int n2=edges[i][1];\n sides[n1].push_back(n2);\n sides[n2].push_back(n1);\n }\n vector<pair<int,int>>dp(n,{0,0});\n vector<int>out(n,0);\n int root=0;\n int ans=-1e9;\n dfs(root,-1,sides,dp,price);\n vector<int>visited(n,0);\n visited[root]=-1;\n out[root]=0;\n dfs2(root,-1,sides,dp,price,out);\n for(int i=0;i<n;i++){\n int a1=dp[i].first-price[i];\n int a2=out[i]-price[i];\n ans=max(ans,a1);\n ans=max(ans,a2);\n }\n return ans;\n }\n};\n```
0
0
['Array', 'Dynamic Programming', 'Tree', 'Depth-First Search', 'C++']
0
difference-between-maximum-and-minimum-price-sum
Rerooting| No multi set or TreeMap
rerooting-no-multi-set-or-treemap-by-its-nbtp
Intuition\n Describe your first thoughts on how to solve this problem. \nRerooting\n\n# Approach\n Describe your approach to solving the problem. \nGet the max
itsmejatin_s
NORMAL
2024-05-30T16:22:42.028323+00:00
2024-05-30T16:22:42.028360+00:00
5
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nRerooting\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nGet the max path value for single node in one pass using dfsDown (start from `root` = 0). At this point, the `dfsDown[root]` contains the maximum price length. Remaining values in this array are incorrect because they are calculated based only on the subtree starting at that node.\n\nNow we need to calculate up values. Up values are the maximum price you can get when instead of going down from that node, you go up from the node, ie, from the parent.\nInitialy up value of the root will be zero because you cannot go up from the root, ie, max sum of price of nodes encountered in the path when you go up from the root of the tree is zero. For other nodes it will not be zero. We need to calculate up values for every node in the tree. Then for every node, we do the following to get the ans ```\t\nfor (int i = 0; i < n; i++) {\n\t\t\tans = Math.max(ans, Math.max(down[i], up[i] + price[i]) - price[i]);\n\t\t}```\nWhy?\nMin price sum for a node will always be the price of that node as the prices are alaways positive.\nMaximum price su for a node will be either the down value for that node or price of that node + the up value of that node. \nWhy do we add price of node to the up value?\nBecause up value for a node stores the max price sum that you can get when you go up from the root. Here you don\'t count the price[root] while filling this array, ie, the price is considered from the parent of this root.\n\nNow go through the code. In `dfsUp()`, you will find a loop which causes TLE. THis is because the tree can have very large number of children. To avoid this, we need to calculate the [max down value of the parent of the node under exploration (max down value should not be the one which is of the current child)] in constant time. FOr this we use the logic below.\n\nAt every node, maintain the topmost 2 down values. While calculating up values, the up value of current node is max of (all downs of parent(except current child), up of parent) + price[parent]. You directly know up[parent]. Your objective is to find the max down of the parent, ie, max down value of the children of the parent, but this child should not be the node under exploration.\n\nIf you directly do down[parent] - price[parent], it gives you the max down of all its children (including the child under exploration). So we cannot use this formula directly.\n\nSo for every node, during dfs down, you maintain top 2 highest down values along with its child id. If the current child belongs to the highest down value, then take the second highest one, other wise take the highest one.\n\nThen take max of this highest and the parent value of the parent.\n\nNow you have max of all downs of the parent (except the current child) and up of the parent. You add price[parent] to get the up of the current node.\n\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(V + E)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(V)$$\n\n# Code\n```\npackage current.temp;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.PriorityQueue;\n\nclass Solution {\n\tMap<Integer, List<long[]>> map;\n\tpublic long maxOutput(int n, int[][] edges, int[] price) {\n\t\tList<List<Integer>> adj = getAdj(n, edges, false);\n\t\tmap = new HashMap<>();\n\n\t\tint parent[] = new int[n];\n\t\tparent[0] = -1;\n\t\tlong down[] = new long[n];\n\t\tdfsDown(0, adj, down, -1, price, parent);\n\t\tArrays.stream(down).forEach(System.out::println);\n\n\t\tlong up[] = new long[n];\n\t\t// up[0] = price[0];\n\t\tdfsUp(0, adj, up, down, -1, price, parent);\n\n\t\tlong ans = 0;\n\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tans = Math.max(ans, Math.max(down[i], up[i] + price[i]) - price[i]);\n\t\t}\n\t\tArrays.stream(up).forEach(System.out::println);\n\t\treturn ans;\n\t}\n\n\tprivate void dfsUp(int root, List<List<Integer>> adj, long up[], long down[], int parent, int price[],\n\t\t\tint parentArray[]) {\n\t\tlong ans = 0;\n\t\tif (parent != -1) {\n//\t\t\tfor (int v : adj.get(parent)) { // THIS LOOP CAUSES TLE\n//\t\t\t\tif (v == root || v == parentArray[parent])\n//\t\t\t\t\tcontinue;\n//\t\t\t\tans = Math.max(down[v], ans);\n//\t\t\t}\n\t\t\tList<long[]> list = map.get(parent);\n\t\t\tint n = list.size();\n\t\t\tif(list.get(n - 1)[1] == root) {\n\t\t\t\tif(n == 1) // i am the only child and the down value goes through me\n\t\t\t\t\tans = 0;\n\t\t\t\telse\n\t\t\t\t\tans = list.get(0)[0];\n\t\t\t}else {\n\t\t\t\tans = list.get(n - 1)[0];\n\t\t\t}\n\t\t\tans = Math.max(ans, up[parent]);\n\t\t\tup[root] = ans + price[parent];\n\t\t}\n\t\t\n\t\tfor (int v : adj.get(root)) {\n\t\t\tif (v != parent)\n\t\t\t\tdfsUp(v, adj, up, down, root, price, parentArray);\n\t\t}\n\t}\n\n\tprivate long dfsDown(int root, List<List<Integer>> adj, long down[], int parent, int price[], int parentArray[]) {\n\t\tPriorityQueue<long[]> pq = new PriorityQueue<>((a, b) -> Long.compare(a[0], b[0]));\n\t\tlong ans = 0;\n\t\tfor (int v : adj.get(root)) {\n\t\t\tif (v == parent)\n\t\t\t\tcontinue;\n\t\t\tlong result = dfsDown(v, adj, down, root, price, parentArray);\n\t\t\tif (pq.size() < 2)\n\t\t\t\tpq.offer(new long[] { result, v });\n\t\t\telse if (pq.peek()[0] < result) {\n\t\t\t\tpq.poll();\n\t\t\t\tpq.offer(new long[] { result, v });\n\t\t\t}\n\n\t\t\tans = Math.max(ans, result);\n\t\t}\n\t\tList<long[]> list = new ArrayList<>();\n\t\twhile(!pq.isEmpty())\n\t\t\tlist.add(pq.poll());\n\t\tmap.put(root, list);\n\t\tparentArray[root] = parent;\n\t\treturn down[root] = price[root] + ans;\n\t}\n\n\tprivate List<List<Integer>> getAdj(int n, int edges[][], boolean directed) {\n\t\tList<List<Integer>> adj = new ArrayList<>();\n\t\tfor (int i = 0; i < n; i++)\n\t\t\tadj.add(new ArrayList<>());\n\n\t\tfor (int edge[] : edges) {\n\t\t\tint u = edge[0], v = edge[1];\n\t\t\tadj.get(u).add(v);\n\t\t\tif (!directed)\n\t\t\t\tadj.get(v).add(u);\n\t\t}\n\t\treturn adj;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tint edges[][] = { { 0, 1 }, { 1, 2 }, { 1, 3 }, { 3, 4 }, { 3, 5 } };\n\t\tSystem.out.println(new Solution().maxOutput(6, edges, new int[] { 9, 8, 7, 6, 10, 5 }));\n\t}\n}\n```
0
0
['Java']
0
difference-between-maximum-and-minimum-price-sum
Diameter endpoints are farthest
diameter-endpoints-are-farthest-by-theab-zll7
\nfrom collections import *\n\nclass Solution:\n def BFS(self, graph, i):\n q = deque([(i, self.price[i])])\n dist = {}\n dist[i] = self
theabbie
NORMAL
2024-04-10T07:47:38.762631+00:00
2024-04-10T07:47:38.762662+00:00
5
false
```\nfrom collections import *\n\nclass Solution:\n def BFS(self, graph, i):\n q = deque([(i, self.price[i])])\n dist = {}\n dist[i] = self.price[i]\n while len(q) > 0:\n curr, d = q.pop()\n for j in graph[curr]:\n if dist.get(j, float(\'inf\')) > d + self.price[j]:\n dist[j] = d + self.price[j]\n q.appendleft((j, d + self.price[j]))\n res = max(dist.keys(), key = lambda i: dist[i])\n return (res, dist)\n \n def maxOutput(self, n: int, edges: List[List[int]], price: List[int]) -> int:\n self.price = price\n graph = defaultdict(set)\n for a, b in edges:\n graph[a].add(b)\n graph[b].add(a)\n x, dx = self.BFS(graph, 0)\n y, dy = self.BFS(graph, x)\n z, dz = self.BFS(graph, y)\n res = 0\n for i in range(n):\n cost = max(dy[i], dz[i])\n res = max(res, cost - price[i])\n return res\n```
0
0
['Python']
0
difference-between-maximum-and-minimum-price-sum
in-out dfs
in-out-dfs-by-yv0403-g30p
Intuition\n Describe your first thoughts on how to solve this problem. \nin-out dfs technique\n\n# Approach\n Describe your approach to solving the problem. \nt
yv0403
NORMAL
2024-04-03T16:57:33.768594+00:00
2024-04-03T16:57:33.768626+00:00
9
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nin-out dfs technique\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nthis is a technique through which we can find maximum path for all nodes in O(n)\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n \n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nusing ll=long long;\nclass Solution {\npublic:\n ll dfs1(int i, int par, vector<vector<int>>& adj,map<ll,multiset<ll,greater<ll>>> &in,vector<int>&price ){\n ll maxi=0;\n for(auto itr:adj[i]){\n if(itr==par) continue;\n ll temp=dfs1(itr,i,adj,in,price);\n in[i].insert(temp);\n maxi=max(maxi,temp);\n }\n return maxi+price[i];\n }\n void dfs2(int i, int par, vector<vector<int>> &adj, map<ll,multiset<ll,greater<ll>>> &in, map<ll,ll> &out,vector<int>& price){\n ll maxi=0;\n if(par!=-1){\n in[par].erase(in[par].find((in[i].size()!=0?*(in[i].begin()):0)+price[i]));\n maxi=max(maxi,*(in[par].begin())+price[par]);\n maxi=max(maxi,out[par]+price[par]);\n in[par].insert((in[i].size()!=0?*(in[i].begin()):0)+price[i]);\n }\n out[i]=maxi;\n for(auto itr:adj[i]){\n if(itr==par) continue;\n dfs2(itr,i,adj,in,out,price);\n }\n }\n ll maxOutput(int n, vector<vector<int>>& edges, vector<int>& price) {\n vector<vector<int>> adj(n);\n for(auto itr:edges){\n adj[itr[0]].push_back(itr[1]);\n adj[itr[1]].push_back(itr[0]);\n }\n map<ll,multiset<ll,greater<ll>>> in;\n map<ll,ll> out;\n dfs1(0,-1,adj,in,price);\n dfs2(0,-1,adj,in,out,price);\n ll maxi=-1;\n for(int i=0;i<n;i++){\n maxi=max(maxi, max(*(in[i].begin()),out[i]));\n }\n return maxi;\n\n \n }\n};\n```
0
0
['C++']
0
difference-between-maximum-and-minimum-price-sum
Tree rerooting O(3*n)
tree-rerooting-o3n-by-penguinzzz-a3dj
Intuition\nWe need to solve it for all roots, hence tree rerooting\n\n# Approach\n1. first build max length for each subtree\n2. Now build maxlength for outside
penguinzzz
NORMAL
2024-03-18T09:44:21.962490+00:00
2024-03-18T09:44:21.962524+00:00
20
false
# Intuition\nWe need to solve it for all roots, hence tree rerooting\n\n# Approach\n1. first build max length for each subtree\n2. Now build maxlength for outside the subtree and compare both\n\n# Complexity\n- Time complexity:\n`O(n)`\n\n- Space complexity:\n`O(n)`\n\n# Code\n```\n\nclass Solution {\npublic:\n long long maxOutput(int n, vector<vector<int>>& edges, vector<int>& a) {\n ios_base::sync_with_stdio(false);\n cin.tie(NULL);\n vector<vector<int>> l(n + 2);\n for(auto c : edges){\n int u = c[0]+1;\n int v = c[1]+1;\n l[u].push_back(v);\n l[v].push_back(u);\n }\n vector<int> sub(n+1);\n function<void(int,int)> dfs1 = [&](int i, int p){\n sub[i]=a[i-1];\n for(auto child : l[i]){\n if(child == p) continue;\n dfs1(child, i);\n sub[i]=max(sub[i],sub[child]+a[i-1]);\n }\n };\n int ans=0;\n vector<int> out(n+1);\n function<void(int,int)> dfs2=[&](int i,int p){\n int mx1=a[i-1];\n int mx2=a[i-1];\n for(auto child:l[i]){\n if(child==p) continue;\n if(sub[child]+a[i-1]>mx1) mx2=mx1,mx1=sub[child]+a[i-1];\n else if(sub[child]+a[i-1]>mx2) mx2=sub[child]+a[i-1];\n }\n for(auto child:l[i]){\n if(child==p) continue;\n int l=0;\n if(mx1==sub[child]+a[i-1]) l=mx2;\n else l=mx1;\n out[child]=max(out[i],l)+a[child-1];\n dfs2(child,i);\n }\n };\n dfs1(1,-1);\n dfs2(1,-1);\n for(int i=1;i<=n;i++){\n ans=max(ans,max(sub[i],out[i])-a[i-1]);\n }\n return ans;\n }\n};\n\n```
0
0
['C++']
0
difference-between-maximum-and-minimum-price-sum
C++ DP DFS O(n) Detailed approach + comments
c-dp-dfs-on-detailed-approach-comments-b-mqab
Approach\nFor questions like this, it is best to approach with the mindset "if the path passes through the current node, what is the answer?" - in this case, th
tangd6
NORMAL
2024-03-18T04:58:56.179564+00:00
2024-03-18T04:58:56.179599+00:00
22
false
# Approach\nFor questions like this, it is best to approach with the mindset "if the path passes through the current node, what is the answer?" - in this case, the answer is the maximum path cost sum.\n\nThe key here is to realise that when you are on the node u, you are calculating all the nodes that start from some leaf of u, and end at another leaf of u. You do NOT have to worry about a node going from the leaf of u to u\'s parent etc since that case is covered by u\'s parent! So focus on only u\'s subtree.\n\nNow that we are focusing on the subtree, how do we do it? What information do we need? The most important observation is that: despite calculating for u\'s subtree -> we don\'t want to root the tree at u. This is because of the nature of the question - if we don\'t go from leaf to leaf we are $$shortening$$ our path. But if we go from leaf to leaf, it is optimal to root the tree at a leaf (or we will make our minimum-path-sum bigger). Please note: there is no case where rooting at u is optimal - if we take the singular longest path starting from u, we are bounded by that path sum. If we try to take 2 paths to 2 leafs, then we can automatically get that path sum and more.\n\nThe key here is to use a DP where you store the longest path from the root to a leaf, and the longest path from the root to a NON-leaf (we are excluding leaves). So now, from different subtrees - we can take the longest path to a leaf + longest path to a non-leaf (note: from different children of u!!!) - This treats the non-leaf path\'s leaf as the root so we exclude it. That\'s pretty much the answer. Just be careful, for every child, you need to do both the \'ends here\' and \'not ends here\' calculation.\n\n# Code\n```\nclass Solution {\npublic:\n const static int MX = (int)1e5 + 1;\n vector<int> adj[MX];\n array<long long,2> stats[MX]; // {largest path, largest path without leaf}\n vector<int> cost;\n long long ans = 0;\n void dfs(int u, int p) {\n // base case: a leaf will only have cost on [0], and empty on [1] since excludes itself\n stats[u] = { static_cast<long long>(cost[u]), 0 };\n for (auto v : adj[u]) {\n if (v == p) continue;\n dfs(v, u);\n // compare current child longest path with longest UNLEAFED\n // child calculated BEFORE. Then do it the opposite.\n // These paths are guaranteed in different subtrees! Never the\n // same, because the actual setting is done underneath.\n ans = max(ans, stats[v][0] + stats[u][1]);\n ans = max(ans, stats[v][1] + stats[u][0]);\n // If this runs, not a leaf, so add your costs.\n stats[u][0] = max(stats[u][0], stats[v][0] + cost[u]);\n stats[u][1] = max(stats[u][1], stats[v][1] + cost[u]);\n }\n }\n\n long long maxOutput(int n, vector<vector<int>>& edges, vector<int>& price) {\n cost = price;\n for (auto &e : edges) {\n adj[e[0]].push_back(e[1]);\n adj[e[1]].push_back(e[0]);\n }\n dfs(0, -1);\n return ans;\n }\n};\n```
0
0
['C++']
0
difference-between-maximum-and-minimum-price-sum
Most efficient solution using javascript
most-efficient-solution-using-javascript-bns9
\n# Code\n\n/**\n * @param {number} n\n * @param {number[][]} edges\n * @param {number[]} price\n * @return {number}\n */\nvar maxOutput = function(n, edges, pr
inovra
NORMAL
2024-03-01T07:37:12.690055+00:00
2024-03-01T07:37:12.690088+00:00
13
false
\n# Code\n```\n/**\n * @param {number} n\n * @param {number[][]} edges\n * @param {number[]} price\n * @return {number}\n */\nvar maxOutput = function(n, edges, price) {\n if (n === 1) return 0\n const graph = new Array(n).fill(null).map(_=> []);\n const visited = new Array(n).fill(false)\n\n for(const edge of edges){\n // initialize graph and path values with 0\n graph[edge[0]].push(edge[1]);\n graph[edge[1]].push(edge[0]);\n }\n // console.log("graph: ", graph)\n\n let result = 0;\n visited[0] = true\n dfs(0);\n\n return result\n \n function dfs(node) {\n if (graph[node].length == 1 && node != 0) {\n\t\t\treturn [price[node], 0];\n\t\t}\n\t\tlet i0 = -1, i1 = -1; // child id of the longest path and path without leaf\n\t\tlet l0 = 0, l1 = 0; // the longest path with leaf and path without leaf\n\t\tlet s0 = 0, s1 = 0; // the 2nd longest\n\n\t\tfor (const child of graph[node]) {\n\t\t\tif (visited[child]) continue;\n\t\t\tvisited[child] = true;\n\t\t\tconst sub = dfs(child);\n\n\t\t\tif (sub[0] >= l0) {\n\t\t\t\ts0 = l0;\n\t\t\t\tl0 = sub[0];\n\t\t\t\ti0 = child;\n\t\t\t} else if (sub[0] > s0) {\n\t\t\t\ts0 = sub[0];\n\t\t\t}\n\n\t\t\tif (sub[1] >= l1) {\n\t\t\t\ts1 = l1;\n\t\t\t\tl1 = sub[1];\n\t\t\t\ti1 = child;\n\t\t\t} else if (sub[1] > s1) {\n\t\t\t\ts1 = sub[1];\n\t\t\t}\n\t\t}\n\n\t\tif (s0 == 0) {\n\t\t\t// only one child. case: example 2\n\t\t\tresult = Math.max(result, Math.max(l0, l1 + price[node]));\n\t\t} else {\n\t\t\tconst path = i0 !== i1 ? price[node] + l0 + l1 \n\t\t\t\t: price[node] + Math.max(l0 + s1, s0 + l1);\n result = Math.max(result, path);\n\t\t}\n\n\t\treturn [l0 + price[node], l1 + price[node]];\n } \n};\n```
0
0
['JavaScript']
0
difference-between-maximum-and-minimum-price-sum
Java O(n) solution, DFS , detailed explanation
java-on-solution-dfs-detailed-explanatio-q1ey
Definition\n+ edge node or leaf node: a node has only one edge connecting to the tree. \n+ internal node: a node has more than one edge\n# Intuition\nSuppose
jasonzhang2002
NORMAL
2024-02-04T10:19:29.125953+00:00
2024-02-04T19:26:16.858525+00:00
9
false
# Definition\n+ edge node or leaf node: a node has only one edge connecting to the tree. \n+ internal node: a node has more than one edge\n# Intuition\nSuppose a path from x to y has maximal cost.\n+ The maximal pricing is the sum of prices for all nodes in the path. \n+ The minimal pricing is the smaller price among x and y.\n+ Let us suppose y has smaller price than x. So the cost is sum of [x, ..., y). Note here we want to **exclude the price of one leaf node**. \n+ The x and y have to be edge nodes. If not, we can extend the path and have a greater cost sum of [z, x, ..., y), or [x, ..., y, z)\n\nSince this is a tree struture, there is only one path between every two edge nodes.\n\n# Approach\n\nThe general idea is finding all possible candidate paths during DFS, and calculating the maximal cost at the same time. All possible candidate paths are path from every leaf node to the other leaf nodes. For each path x ->..-> y, we pick up the smaller cost between [x, y) and (x, y].\n\n## How can we finding all candidate paths?\n\nLet us suppose a tree has many substrees. There is a candidate path **through root** for a leaf node at one substree with every leaf node at another subtrees.\n\nFor nodes withtin a subtree, the candidate path are already processed. Those paths do not include the edge from root node to the subtree root node.\n\nBy pairing every node in one subtree with every node in all other subtrees, we have all the candidate paths. We want to find the maximal cost of all these candidate paths. \n\nLet us define two term\n\n**dist**: the path sum from the root to a leaf node. \n**distMinus**: the path sum from the root the a leaf node, minus the leaf node pricing. We want to keep this value since we want to calcualte the cost which excludes the price of one leaf node.\n\n## Let us look at two substrees : ith and jth\n\nFor ith substree, we have \nith-dist= [ith-dist1, ith-dist2, ..., ], one for each leaf node\nith-distMinus= [ith-distMinus1, ith-distMinus2, ...]\n\nFor jth substree, we have \njth-dist = [jth-dist1, jth-dist2, ... ]\njth-distMinus = [jth-distMinus1, jth-distMinus2, ...]\n\nWe pair every node at ith subtree with every node at jth substree, \n+ Excluding the jth edge node: the cost is ith-distX + jth-distMinusY. The maximal cost among all these pairs will be max(ith-dist) + max(jth-distMinus)\n+ Excluding the ith edge node. The maximal cost will be max(ith-distMinus) + max(jth-dist)\n\nBase on this analysis, we just maintain two values for each subtree: max(dist) and max(distMinus), not the dist and distMinus for every leaf node.\n\n\n## From two subtrees to many subtrees\n\nFor first substree, the maximal cost comes from\n+ ~max(1th-dist) + max(1th-distMinus)~\n+ max(1th-dist) + max(2th-distMinus), \n+ ...,\n+ max(1th-dist) + max(ith-distMinus), \n+ ...,\n+ max(1th-dist) + max(nth-distMinus). \n\nwhich is max(1th-dist) + max( max(2th-distMinus), ..., max( nth-distMinus) )\n\nExpand this to all subtrees, the maxial cost comes from\n\nmax( the maximal dist from all subtree) + max (the maximal distMinus from all subtree) where these two max values are not from the same subtree\n\n\n# Complexity\n- Time complexity:\nO(n) since we only do basic DFS\n\n- Space complexity:\nO(E): Maintain a tree. \n\n# Code\n```\nclass Solution {\n int n;\n ArrayList<List<Integer>> tree;\n int[] price;\n\n public long maxOutput(int n, int[][] edges, int[] price) {\n if (n==1){\n return 0;\n }\n if (n==2){\n return Math.max(price[0], price[1]);\n }\n\n // n>2 here to make sure we have internal node.\n this.n = n;\n this.price = price; \n // build a tree first\n tree = new ArrayList<>();\n for (int i=0; i<n; i++){\n tree.add(new ArrayList<>());\n }\n\n for (int[] edge: edges){\n tree.get(edge[0]).add(edge[1]);\n tree.get(edge[1]).add(edge[0]);\n }\n\n // select one node which is not leaf node, then DFS\n for (int u=0; u<n; u++){\n if (tree.get(u).size()>1){\n dfs(u, -1);\n break;\n }\n }\n return max;\n }\n\n long max = 0;\n\n \n // Maintain two maximal values\n public static class TwoMaximalValue {\n \n long v1;\n // root node of the subtree.\n int tree1 = -1;\n long v2;\n // root node of the subtree.\n int tree2 = -1;\n\n public void push(long v, int treeNum){\n\n if (v>=v1){\n v2 = v1;\n tree2 = tree1;\n\n v1 = v;\n tree1 = treeNum;\n\n } else if (v > v2){\n v2 = v;\n tree2 = treeNum;\n }\n }\n }\n long max = 0;\n\n \n // u: the sub tree rooted at u\n // p: the parent node of u. We need this node so each edge is only used once.\n // Suppose the sub tree have k LEAF nodes: L1, L2, ...Lk.\n // We have two arrays:\n // The path sum from u to leaf nodes: [u -> L1], [u -> L2], ...[u -> LK]. \n//This is the dist in the explanation.\n // The path sum from u to leaf nodes, but not including the leaf\'s price, : [u ->L1), [u->L2), ..., [u->Lk). \n//This is the distMinus in the explanation.\n // We return two values : \n // The maximal value of the first array, \n // and the maximal value of the second array. \n public long[] dfs(int u, int p) {\n // leaf node.\n if (tree.get(u).size()==1 && tree.get(u).get(0) ==p){\n return new long[]{price[u], 0};\n }\n\n TwoMaximalValue maxDist = new TwoMaximalValue();\n TwoMaximalValue maxDistMinus = new TwoMaximalValue();\n\n long dist =0;\n long distMinus = 0;\n for (int v: tree.get(u)){\n if (v==p){\n continue;\n }\n long[] child = dfs(v, u);\n maxDist.push(child[0], v);\n maxDistMinus.push(child[1], v);\n\n dist = Math.max(dist, price[u] + child[0]);\n distMinus = Math.max(distMinus, price[u] + child[1]);\n }\n\n if (maxDist.tree2!=-1) { // we have at least two sub tree.\n \n if (maxDist.tree1 !=maxDistMinus.tree1){\n max = Math.max(max, maxDist.v1 + maxDistMinus.v1 + price[u]);\n } else {\n max = Math.max(max, maxDist.v1 + maxDistMinus.v2 + price[u]);\n max = Math.max(max, maxDist.v2 + maxDistMinus.v1 + price[u]);\n }\n }\n\n return new long[]{dist, distMinus};\n }\n\n}\n \n```
0
0
['Java']
0
difference-between-maximum-and-minimum-price-sum
2538. Difference Between Maximum and Minimum Price Sum (Python)
2538-difference-between-maximum-and-mini-pz6l
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nBefore new test cases w
Koushik_leetcode
NORMAL
2024-01-30T06:50:29.439306+00:00
2024-01-30T06:50:29.439337+00:00
2
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nBefore new test cases were added, the following code solves the issue:\nclass Solution(object):\n\n\xA0 \xA0 def maxOutput(self, n, edges, price):\n\n\xA0 \xA0 \xA0 \xA0 """\n\n\xA0 \xA0 \xA0 \xA0 :type n: int\n\n\xA0 \xA0 \xA0 \xA0 :type edges: List[List[int]]\n\n\xA0 \xA0 \xA0 \xA0 :type price: List[int]\n\n\xA0 \xA0 \xA0 \xA0 :rtype: int\n\n\xA0 \xA0 \xA0 \xA0 """\n\n\xA0 \xA0 \xA0 \xA0 graph = [[] for _ in range(n)]\n\n\xA0 \xA0 \xA0 \xA0 for edge in edges:\n\n\xA0 \xA0 \xA0 \xA0 \xA0 \xA0 u, v = edge\n\n\xA0 \xA0 \xA0 \xA0 \xA0 \xA0 graph[u].append(v)\n\n\xA0 \xA0 \xA0 \xA0 \xA0 \xA0 graph[v].append(u)\n\n\n\n\xA0 \xA0 \xA0 \xA0 memo = {}\n\n\n\n\xA0 \xA0 \xA0 \xA0 def dfs(node, parent):\n\n\xA0 \xA0 \xA0 \xA0 \xA0 \xA0 if (node, parent) in memo:\n\n\xA0 \xA0 \xA0 \xA0 \xA0 \xA0 \xA0 \xA0 return memo[(node, parent)]\n\n\n\n\xA0 \xA0 \xA0 \xA0 \xA0 \xA0 max_price_sum = price[node]\n\n\xA0 \xA0 \xA0 \xA0 \xA0 \xA0 min_price_sum = price[node]\n\n\xA0 \xA0 \xA0 \xA0 \xA0 \xA0 for neighbor in graph[node]:\n\n\xA0 \xA0 \xA0 \xA0 \xA0 \xA0 \xA0 \xA0 if neighbor != parent:\n\n\xA0 \xA0 \xA0 \xA0 \xA0 \xA0 \xA0 \xA0 \xA0 \xA0 child_max, child_min = dfs(neighbor, node)\n\n\xA0 \xA0 \xA0 \xA0 \xA0 \xA0 \xA0 \xA0 \xA0 \xA0 max_price_sum = max(max_price_sum, child_max + price[node])\n\n\xA0 \xA0 \xA0 \xA0 \xA0 \xA0 \xA0 \xA0 \xA0 \xA0 min_price_sum = min(min_price_sum, child_min + price[node])\n\n\xA0 \xA0 \xA0 \xA0 \xA0 \xA0 memo[(node, parent)] = (max_price_sum, min_price_sum)\n\n\xA0 \xA0 \xA0 \xA0 \xA0 \xA0 return max_price_sum, min_price_sum\n\n\n\n\xA0 \xA0 \xA0 \xA0 max_diff = float(\'-inf\')\n\n\xA0 \xA0 \xA0 \xA0 for root in range(n):\n\n\xA0 \xA0 \xA0 \xA0 \xA0 \xA0 root_max, root_min = dfs(root, -1)\n\n\xA0 \xA0 \xA0 \xA0 \xA0 \xA0 max_diff = max(max_diff, root_max - root_min)\n\n\xA0 \xA0 \xA0 \xA0 return max_diff\n\nAFTER New test cases were addded, this old code passed on 54/58 test cases.\nBut, new code passes all test cases\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe old code used O(n^2) complexity, this one uses O(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution(object):\n def maxOutput(self, n, edges, price):\n if n == 1:\n return 0\n \n self.price = price\n self.tree = [[] for _ in range(n)]\n \n for e in edges:\n self.tree[e[0]].append(e[1])\n self.tree[e[1]].append(e[0])\n \n self.visited = [False] * n\n self.visited[0] = True\n self.res = 0\n \n self.dfs(0)\n \n return self.res\n \n def dfs(self, node):\n if len(self.tree[node]) == 1 and node != 0:\n return [self.price[node], 0]\n \n temp = self.res\n i0, i1 = -1, -1\n l0, l1 = 0, 0\n s0, s1 = 0, 0\n \n for child in self.tree[node]:\n if self.visited[child]:\n continue\n self.visited[child] = True\n sub = self.dfs(child)\n \n if sub[0] >= l0:\n s0 = l0\n l0 = sub[0]\n i0 = child\n elif sub[0] > s0:\n s0 = sub[0]\n \n if sub[1] >= l1:\n s1 = l1\n l1 = sub[1]\n i1 = child\n elif sub[1] > s1:\n s1 = sub[1]\n \n if s0 == 0:\n self.res = max(self.res, max(l0, l1 + self.price[node]))\n else:\n path = self.price[node] + l0 + l1 if i0 != i1 else self.price[node] + max(l0 + s1, s0 + l1)\n self.res = max(self.res, path)\n \n return [l0 + self.price[node], l1 + self.price[node]]\n\n```
0
0
['Python']
0
difference-between-maximum-and-minimum-price-sum
REROOTING using IN-OUT VECTOR
rerooting-using-in-out-vector-by-dvsingh-cbn1
Intuition\nIn vector contains the max subtree sum of a node whereas out vector contains the answer of the max path outside of the subtree passing through its pa
DVSINGH
NORMAL
2024-01-06T13:38:49.666199+00:00
2024-01-06T13:38:49.666250+00:00
11
false
# Intuition\nIn vector contains the max subtree sum of a node whereas out vector contains the answer of the max path outside of the subtree passing through its parent.\n\n\n# Code\n```\nclass Solution {\npublic:\nvector<long long> in,out;\nvector<vector<int>> adj;\nlong long dfs(int src,int par,vector<int> &price){\n in[src]=price[src];\n long long a=0;\n for(auto ne:adj[src]){\n if(ne==par)continue;\n a=max(a,dfs(ne,src,price));\n }\n in[src]+=a;\n return in[src];\n}\nvoid dfs2(int src,int par,vector<int> &price){\n long long mx1=0,mx2=0;\n for(auto ne:adj[src]){\n if(ne==par)continue;\n if(in[ne]>=mx1){\n mx2=mx1;\n mx1=in[ne];\n }\n else if(mx2<in[ne]){\n mx2=in[ne];\n }\n }\n for(auto ne:adj[src]){\n if(ne==par)continue;\n long long longest=mx1;\n if(in[ne]==longest)longest=mx2;\n out[ne]=max(longest+price[src],out[src]+price[src]);\n dfs2(ne,src,price);\n }\n\n \n}\n long long maxOutput(int n, vector<vector<int>>& edges, vector<int>& price) {\n adj.resize(n);\n in.resize(n,0);\n out.resize(n,0);\n for(auto e:edges){\n adj[e[0]].push_back(e[1]);\n adj[e[1]].push_back(e[0]);\n }\n dfs(0,-1,price);\n dfs2(0,-1,price);\n long long ans=INT_MIN;\n for(auto i:in)cout<<i<<" ";\n cout<<endl;\n for(auto j:out)cout<<j<<" ";\n cout<<endl;\n for(int i=0;i<n;i++){\n ans=max(ans,max(in[i]-price[i],out[i]));\n }\n return ans;\n }\n};\n```
0
0
['Depth-First Search', 'C++']
0
difference-between-maximum-and-minimum-price-sum
One Pass O(n) Beats 100%
one-pass-on-beats-100-by-sarthakbhandari-fieh
\n\n## Intuition\nPrice of each node is positive, therefore max path cost is always leaf to leaf\nBut we will need to remove the smaller leaf, if this constrain
sarthakBhandari
NORMAL
2023-12-21T22:31:06.654208+00:00
2023-12-21T22:51:41.753074+00:00
5
false
![Screenshot from 2023-12-21 22-33-09.png](https://assets.leetcode.com/users/images/b5a1ebd8-0b53-4867-8be5-57347977bc18_1703197997.3650398.png)\n\n## Intuition\nPrice of each node is positive, therefore max path cost is always leaf to leaf\nBut we will need to remove the smaller leaf, if this constraint wasnt present the answer is basically diameter of tree (counting node val, not edges)\n\nI did come up with a two pass diameter solution which is also posted below\n\n## Explanation\nLets keep track of two values for each node as we traverse the graph (we havent discussed traversal yet)\n`path_i = [with_leaf, without_leaf]`\n`with_leaf` is the cost of max path from some leaf to `node i`\n`without_leaf` is cost of the same max path, but without leaf val\n\nIf there is an edge: `[node i, node j]`\nWhen `[node i, node j` meet during the traversal what do we do?\n```\nTwo things can be done:\n\nCombine the two into a leaf to leaf path, leaving out the smaller node\nbecause max(path_i[0] + path_j[1], path_i[1] + path_j[0])\nmight be a possible answer\n\nnode i, keeps its own path if its bigger, otherwise joins node j\npath_i[0] = max(path_i[0], path_j[0] + price[node])\npath_i[1] = max(path_i[1], path_j[1] + price[node]) \n```\nWe can come up the two traversals to implement the above solution. \nDFS from any node\nBFS from outer leafs to center\n**DFS Solution**\n```\ndef maxOutput(self, n, edges, price):\n graph = defaultdict(list)\n for a,b in edges:\n graph[a].append(b)\n graph[b].append(a)\n\n ans = 0\n\n def dfs(node, parent):\n nonlocal ans\n path_sum_i = [price[node], 0] #[with_node, without_node]\n \n for child in graph[node]:\n if child != parent:\n path_sum_j = dfs(child, node)\n ans = max(ans, path_sum_i[0] + path_sum_j[1], path_sum_i[1] + path_sum_j[0])\n path_sum_i[0] = max(path_sum_i[0], path_sum_j[0] + price[node])\n path_sum_i[1] = max(path_sum_i[1], path_sum_j[1] + price[node])\n \n return path_sum_i #[with_leaf, without_leaf]\n \n dfs(0, 0)\n\n return ans\n```\n\n**Two pass diameter solution**\nThe code looks quite similar to above, but thought process is quite different,\nKeep track of largest path from some node to `node i`\nThen try combining that with the largest path from the children of `node i`\n\nThis could have been done in one pass, but posting the two pass solution for better understanding\n```\ndef maxOutput(self, n, edges, price):\n graph = defaultdict(list)\n for a,b in edges:\n graph[a].append(b)\n graph[b].append(a)\n \n ans = 0\n\n def dfs(node, parent, iterator):\n nonlocal ans\n c_val = price[node]\n\n if parent != None:\n chain[node] = max(chain[node], c_val + chain[parent])\n ans = max(ans, chain[parent])\n\n deepest_child = 0\n for child in iterator(graph[node]):\n if child == parent: continue\n deepest_child = max(deepest_child, dfs(child, node, iterator))\n chain[node] = max(chain[node], deepest_child + c_val)\n \n ans = max(ans, deepest_child)\n return deepest_child + c_val\n \n chain = price[:]; dfs(0, None, lambda nums: nums)\n chain = price[:]; dfs(0, None, lambda nums: reversed(nums))\n \n return ans\n```
0
0
['Array', 'Dynamic Programming', 'Depth-First Search', 'Python']
0
difference-between-maximum-and-minimum-price-sum
Dp in trees
dp-in-trees-by-camilopalacios772-kg41
Intuition\nthe minimum path sum is not relevant more than the node itself so think about getting the maximum path for every node, the naive solution is start fo
camilopalacios772
NORMAL
2023-12-15T16:46:16.711541+00:00
2023-12-15T16:46:16.711570+00:00
25
false
# Intuition\nthe minimum path sum is not relevant more than the node itself so think about getting the maximum path for every node, the naive solution is start for every node a dfs but this takes O(n^2) time complexity, so you should think for every node how can I get the maximum path? well you can do it with a dp, no matter where you root the tree you can calculate the maximum path seeing the tree from top to down, its very easy ```dp_down[u] = max(dp_down[v]) + price [u]```, but what happen with the nodes that are above to the current node ? this is something more complex, think about the node itself how options do you have? well you have two options, let say that p is the parent of node u, so the option 1 is take the ```dp_up[u] = dp_up[p] + price[u] ``` that is your maximum branch above of your parent, but what if your maximum branch is not above of your parent, what if the maximum branch is connected with other branch of your parent, you can use the info from dp_down to know that, you don\'t have to calculate the maximum branch down from your parent again, so your option 2 is ```dp_up[u] = max(dp_down[p]) + price[u] ``` the means that maybe your maximum path up from u is connected to some maximum path of your parent, its seems thats all but this is not true at all, think about what if u is the maximum branch of p, this path cant be take it, you should take the second maximum, so the second option become more like ``` dp_up[p] = max(max_branch_1, max_branch_2) + price[p] + price[u] ```, so the final dp_up is more like ```dp_up[u] = max(dp_out[p], max(max_branch_1, max_branch_2) + price[p] + price[u]) ```\n\nNow you have all the info to know the answer and it is not more than traverse every node and calculate ```maximum_path - price[u] = max(dp_down[u], dp_up[u]) - price[u]```\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 + m)\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```\nconst int N = 2e5 + 5;\nclass Solution {\npublic:\n \n vector<int> prices;\n int in[N], out[N];\n vector<int> g[N];\n\n void dfs(int u, int p) {\n in[u] = prices[u];\n for(auto v : g[u]) {\n if(v == p) continue;\n dfs(v, u);\n in[u] = max(in[u], in[v] + prices[u]);\n }\n }\n\n void dfs2(int u, int p) {\n out[u] += prices[u];\n int mx1 = 0, mx2 = 0;\n for(auto v : g[u]) {\n if(v == p) continue;\n if(mx1 < in[v]) {\n mx2 = mx1;\n mx1 = in[v];\n } \n else if(mx2 < in[v]) {\n mx2 = in[v];\n }\n }\n for(auto v : g[u]) {\n if(v == p) continue;\n out[v] = max(out[u], (mx1 == in[v] ? mx2 : mx1) + prices[u]);\n dfs2(v, u);\n }\n }\n\n long long maxOutput(int n, vector<vector<int>>& edges, vector<int>& price) {\n for(auto e : edges) {\n int u = e[0], v = e[1];\n g[u].emplace_back(v);\n g[v].emplace_back(u);\n }\n prices = price;\n dfs(0, 0);\n dfs2(0, 0);\n int ans = 0;\n for(int i = 0; i < n; i++) {\n ans = max(ans, max(in[i], out[i]) - price[i]);\n }\n return ans;\n }\n};\n```
0
0
['Dynamic Programming', 'Depth-First Search', 'C++']
0
difference-between-maximum-and-minimum-price-sum
Reroute DP Soulution
reroute-dp-soulution-by-samhit102-30km
Code\n\nclass Solution {\npublic:\n long long ans;\n pair<long long, long long> dp[100001];\n long long dfs(auto& graph, int cur, int parent, vector<in
samhit102
NORMAL
2023-11-19T06:23:26.934923+00:00
2023-11-19T06:23:26.934940+00:00
10
false
# Code\n```\nclass Solution {\npublic:\n long long ans;\n pair<long long, long long> dp[100001];\n long long dfs(auto& graph, int cur, int parent, vector<int>& price) {\n long long max1 = 0, max2 = 0;\n for(int child : graph[cur]) {\n if(child != parent) {\n int temp;\n temp = dfs(graph, child, cur, price);\n if(temp >= max1) {\n max2 = max1;\n max1 = temp;\n }\n else if(temp > max2) {\n max2 = temp;\n }\n }\n }\n dp[cur] = {max1, max2};\n return (long long)price[cur]+max1;\n }\n void dfs1(auto& graph, int cur, int parent, vector<int>& price) {\n if(parent == -1) {\n ans = dp[cur].first;\n }\n else {\n if(dp[parent].first == dp[cur].first+(long long)price[cur]) {\n int temp = dp[parent].second+(long long)price[parent];\n if(temp >= dp[cur].first) {\n dp[cur].second = dp[cur].first;\n dp[cur].first = temp;\n }\n else if(temp > dp[cur].second) {\n dp[cur].second = temp;\n }\n }\n else {\n int temp = dp[parent].first+(long long)price[parent];\n if(temp >= dp[cur].first) {\n dp[cur].second = dp[cur].first;\n dp[cur].first = temp;\n }\n else if(temp > dp[cur].second) {\n dp[cur].second = temp;\n }\n }\n ans = max(ans, dp[cur].first);\n }\n for(int child : graph[cur]) {\n if(child != parent) {\n dfs1(graph, child, cur, price);\n }\n }\n }\n long long maxOutput(int n, vector<vector<int>>& edges, vector<int>& price) {\n vector<vector<int>> graph(n);\n for(int i = 0; i < edges.size(); i++) {\n graph[edges[i][0]].push_back(edges[i][1]);\n graph[edges[i][1]].push_back(edges[i][0]);\n }\n dfs(graph, 0, -1, price);\n dfs1(graph, 0, -1, price);\n return ans;\n }\n};\n```
0
0
['C++']
0
difference-between-maximum-and-minimum-price-sum
✅Re rooting✅ | O(N) | Explained
re-rooting-on-explained-by-jayesh_06-qjhk
AUTHOR: JAYESH BADGUJAR\n\n\n# Code\n\nclass Solution {\npublic:\n //Using DP O(N) Solution\u2705\n long long dfs(int src,map<int,vector<int>>& mp,vector<
Jayesh_06
NORMAL
2023-09-27T15:19:45.093460+00:00
2023-09-27T15:19:45.093487+00:00
18
false
# AUTHOR: JAYESH BADGUJAR\n\n\n# Code\n```\nclass Solution {\npublic:\n //Using DP O(N) Solution\u2705\n long long dfs(int src,map<int,vector<int>>& mp,vector<int>& price,vector<long long>& dp,int par){\n long long maxi=price[src];\n for(auto it:mp[src]){\n if(it==par){\n continue;\n }\n maxi=max(maxi,price[src]+dfs(it,mp,price,dp,src));\n }\n \n return dp[src]=maxi;\n }\n void find(int src,map<int,vector<int>>& mp,vector<int>& price,vector<long long>& dp,vector<long long>& ans,int par,long long pre_sum){\n long long maxi=0;\n vector<long long> v;\n bool child=false;\n for(auto it:mp[src]){\n if(it==par) continue;\n child=true;\n maxi=max(maxi,dp[it]);\n v.push_back(dp[it]);\n }\n ans[src]=max(ans[src],maxi);\n int n=v.size();\n vector<long long> pre(n,0),suff(n,0);\n for(int i=0;i<n;i++){\n if(i==0){\n pre[i]=v[i];\n }else{\n pre[i]=max(v[i],pre[i-1]);\n }\n }\n for(int i=n-1;i>=0;i--){\n if(i==n-1){\n suff[i]=v[i];\n }else{\n suff[i]=max(v[i],suff[i+1]);\n }\n }\n int i=0;\n for(auto it:mp[src]){\n if(it!=par){\n long long child_mx=0;\n if(i!=0){\n child_mx=max(child_mx,pre[i-1]);\n }\n if(i!=n-1){\n child_mx=max(child_mx,suff[i+1]);\n }\n child_mx=max(child_mx,pre_sum);\n ans[it]=max(ans[it],price[src]+child_mx);\n find(it,mp,price,dp,ans,src,price[src]+child_mx);\n i++;\n }\n }\n \n }\n long long maxOutput(int n, vector<vector<int>>& edges, vector<int>& price) {\n vector<long long> dp(n,0),ans(n,0);\n map<int,vector<int>> mp;\n for(int i=0;i<edges.size();i++){\n mp[edges[i][0]].push_back(edges[i][1]);\n mp[edges[i][1]].push_back(edges[i][0]);\n }\n dfs(0,mp,price,dp,-1); \n find(0,mp,price,dp,ans,-1,0);\n long long maxi=0;\n for(int i=0;i<n;i++){\n maxi=max(maxi,ans[i]);\n }\n return maxi;\n }\n};\n```
0
0
['C++']
0
difference-between-maximum-and-minimum-price-sum
Tree không có root
tree-khong-co-root-by-dongts-vlhw
Intuition\n Describe your first thoughts on how to solve this problem. \ndfs: t\u1EA1i m\u1ED7i node, l\u01B0u {\u0111\u01B0\u1EDDng max nh\u1EA5t t\u1EEB node
dongts
NORMAL
2023-08-31T09:09:27.617377+00:00
2023-08-31T09:09:27.617428+00:00
4
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\ndfs: t\u1EA1i m\u1ED7i node, l\u01B0u {\u0111\u01B0\u1EDDng max nh\u1EA5t t\u1EEB node xu\u1ED1ng l\xE1, \u0111\u01B0\u1EDDng max nh\u1EA5t t\u1EEB root xu\u1ED1ng l\xE1 - node cu\u1ED1i}\nL\xE2y k\u1EBFt qu\u1EA3: T\u1EA1i 1 node, for c\xE1c nh\xE1nh con v\xE0 c\u1EADp nh\u1EADt res trong qu\xE1 tr\xECnh for, ch\u1ECDn trong c\xE1c tr\u01B0\u1EDDng h\u1EE3p F \u0111\xE3 duy\u1EC7t + S ti\u1EBFp theo ho\u1EB7c S \u0111\xE3 duy\u1EC7t + F ti\u1EBFp theo\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n#define pii pair<int, int>\n#define F first\n#define S second\n\nclass Solution {\npublic:\n long long maxOutput(int n, vector<vector<int>>& edges, vector<int>& price) {\n vector<vector<int>> adj(n);\n for(auto&x:edges) {\n adj[x[0]].push_back(x[1]);\n adj[x[1]].push_back(x[0]);\n }\n long long res = 0;\n function<pii(int,int)> dfs=[&](int node, int pre_node) {\n pii res_i = {price[node], 0};\n for(auto n_node:adj[node]) {\n if(n_node == pre_node) continue;\n pii n_res = dfs(n_node,node);\n res = max(res, 1ll*res_i.F + n_res.S);\n res = max(res, 1ll*res_i.S + n_res.F);\n res_i.F = max(res_i.F, price[node] + n_res.F);\n res_i.S = max(res_i.S, price[node] + n_res.S);\n }\n return res_i;\n };\n dfs(0,-1);\n return res;\n }\n};\n```
0
0
['C++']
0
difference-between-maximum-and-minimum-price-sum
[CLEAN] IN-OUT DP | O(N) time & space
clean-in-out-dp-on-time-space-by-crimson-muge
\nclass Solution {\n int n;\n vector<vector<int>> adj;\n vector<int> p;\n vector<multiset<int>> in;\n vector<int> out;\n int res;\n void df
crimsonX
NORMAL
2023-08-29T05:50:04.373618+00:00
2023-08-29T05:50:04.373641+00:00
8
false
```\nclass Solution {\n int n;\n vector<vector<int>> adj;\n vector<int> p;\n vector<multiset<int>> in;\n vector<int> out;\n int res;\n void dfs1(int node, int par){\n in[node].insert(p[node]);\n in[node].insert(0);\n for(auto &a:adj[node]){\n if(a==par)\n continue;\n dfs1(a,node);\n in[node].insert(*in[a].rbegin()+p[node]);\n while(in[node].size()>2)\n in[node].erase(in[node].begin());\n }\n }\n void dfs2(int node, int par){\n out[node]=max(p[node],out[node]);\n for(auto &a:adj[node]){\n if(a==par)\n continue;\n out[a]=max(out[node]+p[a],out[a]);\n if(*in[node].rbegin()-p[node]==*in[a].rbegin())\n out[a]=max(*in[node].begin()+p[a],out[a]);\n else\n out[a]=max(*in[node].rbegin()+p[a],out[a]);\n dfs2(a,node);\n }\n res=max({*in[node].rbegin()-p[node],out[node]-p[node],res});\n }\npublic:\n long long maxOutput(int nn, vector<vector<int>>& edges, vector<int>& price) {\n n=nn;\n p=price;\n adj.assign(n,{});\n in.assign(n,{0,0});\n out.assign(n,0);\n res=-1;\n for(auto &e:edges){\n adj[e[0]].push_back(e[1]);\n adj[e[1]].push_back(e[0]);\n }\n dfs1(0,-1);\n dfs2(0,-1);\n return res;\n }\n};\n```
0
0
['Dynamic Programming', 'C']
0
difference-between-maximum-and-minimum-price-sum
Code is lengthy , problem is based on tree Diameter
code-is-lengthy-problem-is-based-on-tree-3ezx
Intuition\n Describe your first thoughts on how to solve this problem. \nTree Diameter was my approach \n\n# Approach\n Describe your approach to solving the pr
007kinshuk
NORMAL
2023-08-25T13:40:24.711871+00:00
2023-08-25T13:40:24.711888+00:00
11
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTree Diameter was my approach \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nBFS \n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> graph;\n vector<int> cost;\n int n;\n pair<int,int> bfs(int node){\n vector<int> dist(n,INT_MIN);\n vector<int> visited(n,0);\n dist[node]=0;\n visited[node]=cost[node];\n int maxi = 0,resnode=node;\n queue<int> q;\n q.push(node);\n while(!q.empty()){\n int vertex = q.front();q.pop();\n visited[vertex]=1;\n for(int child:graph[vertex]){\n if(visited[child]==0 && dist[child]<dist[vertex]+cost[child]){\n q.push(child);\n visited[child]=1;\n dist[child]=dist[vertex]+cost[child];\n if(maxi<dist[child]){\n maxi = dist[child];\n resnode = child;\n }\n }\n }\n }\n return {resnode,maxi};\n }\n vector<int> bfs1(int node){\n vector<int> dist(n,INT_MIN);\n vector<int> visited(n,0);\n dist[node]=cost[node];\n visited[node]=1;\n int maxi = 0,resnode=node;\n queue<int> q;\n q.push(node);\n while(!q.empty()){\n int vertex = q.front();q.pop();\n visited[vertex]=1;\n for(int child:graph[vertex]){\n if(visited[child]==0 && dist[child]<dist[vertex]+cost[child]){\n q.push(child);\n visited[child]=1;\n dist[child]=dist[vertex]+cost[child];\n if(maxi<dist[child]){\n maxi = dist[child];\n resnode = child;\n }\n }\n }\n }\n return dist;\n }\n long long maxOutput(int N, vector<vector<int>>& edges, vector<int>& price) {\n n = N;\n graph.resize(n);\n for(int i:price) cost.push_back(i);\n for(auto it:edges){\n graph[it[0]].push_back(it[1]);\n graph[it[1]].push_back(it[0]);\n }\n pair<int,int> p;\n p = bfs(0);\n int node1 = p.first;\n p = bfs(node1);\n int node2 = p.first, maxi = p.second;\n vector<int> dist1 = bfs1(node1);\n vector<int> dist2 = bfs1(node2);\n vector<int> ans(n,INT_MIN);\n for(int i=0;i<n;i++){\n ans[i]=max(ans[i],max(dist1[i],dist2[i]))-cost[i];\n }\n return *max_element(ans.begin(),ans.end());\n }\n};\n```
0
0
['C++']
0
difference-between-maximum-and-minimum-price-sum
Intuitive || DFS || O(n) working solution
intuitive-dfs-on-working-solution-by-izu-bsi2
The code is a bit long but I have tried to explain wherever felt necessary\n\n# Code\n\nclass Solution {\n ArrayList<ArrayList<Integer>> list;\n long ans
Izuku5
NORMAL
2023-08-21T17:26:10.617706+00:00
2023-08-23T06:52:58.108666+00:00
36
false
The code is a bit long but I have tried to explain wherever felt necessary\n\n# Code\n```\nclass Solution {\n ArrayList<ArrayList<Integer>> list;\n long ans = 0;\n public long maxOutput(int n, int[][] edges, int[] price) {\n list = new ArrayList();\n for(int i=0;i<n;++i){\n list.add(new ArrayList<Integer>());\n }\n for(int[] e : edges){ // adj list\n list.get(e[0]).add(e[1]);\n list.get(e[1]).add(e[0]);\n }\n // precomputing the maximum cost of a path when we use dfs for each node\n long[] pre = new long[n];\n ans = solve1(pre, price, 0, -1); // max cost path using dfs\n\n // But dfs gives us the max cost from one side\n // what if we can add the max cost from the other side\n // as well --> then we would get the maximum cost path \n // passing through that node\n\n boolean[] vis = new boolean[n];\n solve2(pre, price, 0, vis);\n\n // finally if youre confused that why are we not subtracting minimum cost, \n // then note that minimum cost will be the node price itself and \n // we have not added it when calculating the max for that node\n return ans;\n }\n\n // after using this function the pre array will have the\n // maximum cost path pre[i] rooted at i\n // assuming 0 as the root node (you could take any other)\n long solve1(long[] pre, int[] price, int ind, int par) {\n long res = 0l;\n for (int i: list.get(ind)) {\n if (i == par) continue;\n res = Math.max(res, price[i] + solve1(pre, price, i, ind));\n }\n return pre[ind] = res;\n }\n void solve2(long[] pre, int[] price, int ind, boolean[] vis){\n long temp = pre[ind];\n vis[ind] = true;\n\n // this is the tricky part\n // we already have the presum (max cost path of a subtree)\n // so now we will do the same thing which we did in solve1\n // just in the opposite manner (first calculate max for that node, then dfs)\n // but if you think about it what if the node where we will be \n // going next is the subtree which has given us the maximum cost path\n // the calculation would become wrong\n // we will take the maximum costpath from all other subtrees\n // except from the one where we will be going next\n\n long max1 = 0, max2 = 0;\n for(int i : list.get(ind)){\n if(max1 <= price[i] + pre[i]){\n max2 = max1;\n max1 = price[i] + pre[i];\n }\n else if(max2 < price[i] + pre[i]){\n max2 = price[i] + pre[i];\n }\n }\n for(int i : list.get(ind)){\n if(vis[i]) continue;\n long child = 0;\n if(pre[i] + price[i] == max1){\n child = max2;\n }\n else{\n child = max1;\n }\n pre[ind] = child; // it would be used in calculation, when we \n // go in the subtree and check its neighbours\n\n long temp1 = pre[i]; \n pre[i] = Math.max(price[ind] + child, pre[i]);\n ans = Math.max(ans, pre[i]);\n vis[i] = true;\n solve2(pre, price, i, vis);\n pre[i] = temp1;\n } \n pre[ind] = temp;\n }\n}\n```
0
0
['Dynamic Programming', 'Depth-First Search', 'Java']
0
difference-between-maximum-and-minimum-price-sum
Re - Rooting Tree DP solution
re-rooting-tree-dp-solution-by-anantbans-vzt1
Intuition\n Describe your first thoughts on how to solve this problem. \nThough code is readable I recommend watching Kartik Arora DP on trees playlist for prop
AnantBansal
NORMAL
2023-08-19T13:32:44.792973+00:00
2023-08-19T13:32:44.792998+00:00
35
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThough code is readable I recommend watching Kartik Arora DP on trees playlist for proper understanding and how to approach to these kind of problems!\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> tree[100000];\n long long subTreeAns[100000];\n long long ans[100000];\n\n void pre(int node, int par, vector<long long>& price){\n long long curr = 0;\n for(auto child : tree[node]){\n if(child != par){\n pre(child,node,price);\n curr = max(curr, subTreeAns[child]);\n }\n }\n subTreeAns[node] = curr + price[node];\n }\n void solve(int node, int par, long long par_ans, vector<long long> &price){\n vector<long long> prefix, suffix;\n for(auto child : tree[node]){\n if(child != par){\n prefix.push_back(subTreeAns[child]);\n suffix.push_back(subTreeAns[child]);\n }\n }\n int n = prefix.size();\n for(int i=1;i<n;i++){\n prefix[i] = max(prefix[i], prefix[i-1]);\n }\n for(int i=n-2;i>=0;i--){\n suffix[i] = max(suffix[i], suffix[i+1]);\n }\n int i = 0;\n for(auto child : tree[node]){\n if(child != par){\n long long left = i > 0 ? prefix[i-1] : 0;\n long long right = i < n - 1 ? suffix[i+1] : 0;\n solve(child, node, price[node] + max({left,right,par_ans}), price);\n i++;\n }\n }\n ans[node] = max(par_ans, n == 0 ? 0 : prefix[n-1]);\n }\n long long maxOutput(int n, vector<vector<int>>& edges, vector<int>& price) {\n for(auto it : edges){\n tree[it[0]].push_back(it[1]);\n tree[it[1]].push_back(it[0]);\n }\n vector<long long> temp(n);\n for(int i=0;i<n;i++){\n temp[i] = (long long)price[i];\n }\n pre(0,-1,temp);\n solve(0,-1,0,temp);\n long long output = 0;\n for(int i=0;i<n;i++){\n output = max(output, ans[i]);\n }\n return output;\n }\n};\n```
0
0
['C++']
0
difference-between-maximum-and-minimum-price-sum
C++ DFS solution, O(N)
c-dfs-solution-on-by-guccigang-izt8
Run-time is O(N), space is O(N).\n\nSome caveats: \n\n1. We only need to worry about each node\'s children, and we can pick the starting node arbitrarily. This
guccigang
NORMAL
2023-07-21T21:09:11.271432+00:00
2023-07-21T21:09:11.271460+00:00
21
false
Run-time is $$O(N)$$, space is $$O(N)$$.\n\nSome caveats: \n\n1. We only need to worry about each node\'s children, and we can pick the starting node arbitrarily. This is because the path must consists of either path from any current child to some leaf node, or from root. We can leave the root calculation once we backtrack, so we only need to check child node paths\n2. Since we cannot pick the "same" path, we need to keep top 2 `max_min` and `max_no_min` values. This is in case `max_min` and `max_no_min` comes from the same child. In this case we need to compute by paring with second biggest `max_min` and `max_no_min`. \n\n\n# Code\n```\n\n// max_min means maximum (path sum minus leaf value)\n// max_no_min means maximum (path sum including leaf value)\ntypedef struct data_s {\n data_s(int _max_min, int _max_no_min): max_min(_max_min), max_no_min(_max_no_min) {}\n int max_min;\n int max_no_min;\n} data_t;\n\nclass Solution {\n int global_max = 0;\npublic:\n long long maxOutput(int n, vector<vector<int>>& edges, vector<int>& price) {\n std::vector<std::vector<int>> adj(n);\n\n for (auto e: edges) {\n adj[e[0]].emplace_back(e[1]);\n adj[e[1]].emplace_back(e[0]);\n }\n\n dfs(adj, price, 0, -1);\n return global_max;\n }\n\n data_t dfs(std::vector<std::vector<int>>& adj, std::vector<int>& price, int node, int prev) {\n\n std::pair<int,int> min1(-1,-1), min2(-1,-1), no_min1(-1,-1), no_min2(-1,-1);\n for (auto n: adj[node]) {\n if (n == prev) continue;\n auto [cur_min, cur_no_min] = dfs(adj, price, n, node);\n if (cur_min > min1.first) {\n min2 = min1;\n min1 = {cur_min, n};\n } else if (cur_min > min2.first) {\n min2 = {cur_min, n};\n }\n\n if (cur_no_min > no_min1.first) {\n no_min2 = no_min1;\n no_min1 = {cur_no_min, n};\n } else if (cur_no_min > no_min2.first) {\n no_min2 = {cur_no_min, n};\n }\n }\n \n if (min1.first == -1) {\n return {0, price[node]};\n }\n\n int local_max = 0;\n\n /* only 1 child, use self as other option */\n if (min2.first == -1) {\n min2 = {0, node};\n no_min2 = {price[node], node};\n } else {\n local_max = price[node];\n }\n \n if (min1.second != no_min1.second) {\n local_max += min1.first + no_min1.first;\n } else {\n if (min1.first + no_min2.first > min2.first + no_min1.first) {\n local_max += min1.first + no_min2.first;\n } else {\n local_max += min2.first + no_min1.first;\n } \n }\n\n global_max = std::max(local_max, global_max);\n return {min1.first+price[node], no_min1.first+price[node]};\n\n }\n};\n```
0
0
['C++']
0
difference-between-maximum-and-minimum-price-sum
C++ | DP | DFS
c-dp-dfs-by-krunal_078-w456
\nclass Solution {\npublic:\n #define ll long long\n void inDfs(vector<int> adj[],int n,int node,int prev,vector<int> &price,vector<ll> &in){\n in[
krunal_078
NORMAL
2023-06-21T09:28:26.806028+00:00
2023-06-21T09:28:26.806047+00:00
34
false
```\nclass Solution {\npublic:\n #define ll long long\n void inDfs(vector<int> adj[],int n,int node,int prev,vector<int> &price,vector<ll> &in){\n in[node] = price[node];\n ll mx = 0;\n for(auto &ele:adj[node]){\n if(ele!=prev){\n inDfs(adj,n,ele,node,price,in);\n mx = max(mx,in[ele]);\n }\n }\n in[node] += mx;\n }\n void outDfs(vector<int> adj[],int n,int node,int prev,vector<int> &price,vector<ll> &in,vector<ll> &out){\n ll mx1 = 0,mx2 = 0;\n // find longest path;\n for(auto &ele:adj[node]){\n if(ele!=prev){\n if(in[ele]>mx1){\n mx2 = mx1;\n mx1 = in[ele];\n }\n else if(in[ele]>mx2){\n mx2 = in[ele];\n }\n }\n }\n for(auto &ele:adj[node]){\n if(ele!=prev){\n ll longest = mx1;\n if(longest==in[ele])\n longest = mx2;\n out[ele] = price[ele] + max(out[node],price[node]+longest);\n outDfs(adj,n,ele,node,price,in,out);\n }\n }\n }\n ll maxOutput(int n, vector<vector<int>>& edges, vector<int>& price){\n vector<int> adj[n];\n for(auto &ele:edges){\n int u = ele[0],v = ele[1];\n adj[u].push_back(v),adj[v].push_back(u);\n }\n // ans = max(in[node],out[node]) for all nodes;\n // minimum will be node\'s value it self , for maximum we can calculate like height;\n // for storing maximum sum;\n vector<ll> in(n,0),out(n,0);\n // in[node] = max(in[node],val[node]+in[child]);\n // out[node] = val[node] + max(out[parent],val[parent]+maximum from all the branches of parent excluding the current node);\n inDfs(adj,n,0,-1,price,in);\n outDfs(adj,n,0,-1,price,in,out);\n // minimum sum will be value on that node;\n ll ans = 0;\n for(int i=0;i<n;i++){\n // cout<<i<<"-->";\n // cout<<in[i]<<" "<<out[i]<<endl;\n ll mx = max(in[i],out[i]),mn = price[i];\n ans = max(ans,mx-mn);\n }\n return ans;\n }\n};\n```
0
0
['Dynamic Programming', 'Tree', 'Depth-First Search', 'C']
0
difference-between-maximum-and-minimum-price-sum
[C++] Easy to Understand O(N) Solution | Beats 96.9%
c-easy-to-understand-on-solution-beats-9-b4at
\n#define ll long long\nclass Solution {\nprivate:\n vector<vector<int>> graph;\n vector<pair<ll,ll>> mxSubtree; // {mx1, mx2} branch-wise\n ll getMaxS
_an1rudh
NORMAL
2023-06-21T08:51:52.292700+00:00
2023-06-21T08:51:52.292718+00:00
77
false
```\n#define ll long long\nclass Solution {\nprivate:\n vector<vector<int>> graph;\n vector<pair<ll,ll>> mxSubtree; // {mx1, mx2} branch-wise\n ll getMaxSubtree(int node, int par, vector<int> &price) { //dfs to get mx1,mx2 sum from all branches\n ll mx1 = 0, mx2 = 0;\n for(int &child: graph[node]) {\n if(child == par) continue;\n ll res = getMaxSubtree(child,node,price);\n res += price[child];\n if(mx1 <= res) {\n mx2 = max(mx2,mx1);\n mx1 = res;\n } else if(mx2 < res) mx2 = res;\n }\n mxSubtree[node] = {mx1,mx2};\n return mx1;\n }\n ll getMaxOutput(int node, int par, ll mxPar, vector<int> &price) { // O(N)\n ll ret = max(mxSubtree[node].first, mxPar);\n mxPar += price[node];\n for(int &child: graph[node]) {\n if(child == par) continue;\n ll mx = ((mxSubtree[child].first + price[child]) == mxSubtree[node].first) ?\n (mxSubtree[node].second + price[node]) : (mxSubtree[node].first + price[node]);\n if(mxPar > mx) mx = mxPar;\n ll res = getMaxOutput(child,node,mx,price);\n ret = max(ret, res);\n }\n return ret;\n }\npublic: \n Solution() {\n ios::sync_with_stdio(false);\n cin.tie(NULL);\n }\n ll maxOutput(int n, vector<vector<int>>& edges, vector<int>& price) {\n graph = vector<vector<int>> (n);\n for(auto &i: edges) {\n graph[i[0]].push_back(i[1]);\n graph[i[1]].push_back(i[0]);\n }\n mxSubtree = vector<pair<ll,ll>>(n);\n getMaxSubtree(0,-1,price); // O(N)\n return getMaxOutput(0,-1,0,price);\n }\n};\n```
0
0
['Tree', 'Depth-First Search', 'C++']
0
difference-between-maximum-and-minimum-price-sum
beats 80% cpp solution
beats-80-cpp-solution-by-ahethesham8-mziw
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
ahethesham8
NORMAL
2023-06-15T09:56:47.431083+00:00
2023-06-15T09:56:47.431102+00:00
34
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:\nvector<vector<long long>> e;\nvector<long long> fin;\nvector<int> price;\nvoid help(int node,int parent){\n fin[node]=price[node];\n for(int i=0;i<e[node].size();i++){\n if(e[node][i]!=parent){\n help(e[node][i],node);\n fin[node]=max(fin[node],fin[e[node][i]]+price[node]);\n }\n }\n return;\n}\nvoid help2(int node,int parent,long long t){\n fin[node]=max(fin[node],t+price[node]);\n long long ma1=price[node],ma2=price[node];\n for(int i=0;i<e[node].size();i++){\n if(e[node][i]!=parent){\n if(fin[e[node][i]]+price[node]>ma1){ma2=ma1;ma1=fin[e[node][i]]+price[node];}\n else\n ma2=max(ma2,fin[e[node][i]]+price[node]);\n }\n }\n t+=price[node];\n for(int i=0;i<e[node].size();i++){\n if(e[node][i]!=parent){\n if(fin[e[node][i]]+price[node]!=ma1)\n help2(e[node][i],node,max(t,ma1));\n else\n help2(e[node][i],node,max(t,ma2));\n }\n }\n}\n long long maxOutput(int n, vector<vector<int>>& edges, vector<int>& p) {\n e=vector<vector<long long>> (n,vector<long long>(0,0));\n price=p;\n fin=vector<long long>(n,0);\n for(int i=0;i<edges.size();i++){\n e[edges[i][0]].push_back(edges[i][1]);\n e[edges[i][1]].push_back(edges[i][0]);\n }\n help(0,-1);\n help2(0,-1,0);\n long long ans=0;\n for(int i=0;i<fin.size();i++){\n ans=max(ans,abs(price[i]-fin[i]));\n }\nreturn ans;\n }\n};\n```
0
0
['C++']
0
difference-between-maximum-and-minimum-price-sum
reverse wavefronts| bottom up tree traversal
reverse-wavefronts-bottom-up-tree-traver-g8c1
start from all the leaves and travel inwards according to number of unvisited neighbors == 1, keeping the queue and track of visited nodes just like you would d
redsmolder
NORMAL
2023-04-25T06:11:08.422811+00:00
2023-04-25T06:11:08.422857+00:00
12
false
start from all the leaves and travel inwards according to number of unvisited neighbors == 1, keeping the queue and track of visited nodes just like you would do in BFS(naming it BFS in any way apart from use of queue would be wrong). **This is bottom up tree traversal i.e. no node is visited until all its children are visited.** \nI have done it in breadth first manner using queue. You can all see it as a wavefront starting from all the leaves. You can also do it depth first manner using stacks + queue(for efficiency of keeping track of unvisited neighbors == 1).\n```\nclass Solution {\npublic:\n long long maxOutput(int n, vector<vector<int>>& edges, vector<int>& price) {\n if(n == 1) return 0;\n if(n == 2) return max(price[0], price[1]);\n vector<vector<int> > adj(n, vector<int>());\n for(vector<int> x: edges){\n adj[x[0]].push_back(x[1]);\n adj[x[1]].push_back(x[0]);\n }\n vector<pair<long long, long long> > endCost(n, {-1, -1});\n queue<int> q;\n for(int i = 0; i < n; i++){\n if(adj[i].size() == 1) {\n q.push(i);\n endCost[i] = {price[i], 0};\n }\n else endCost[i].second = adj[i].size();\n }\n int x;\n int gi, si, gl, sl;\n long long ans = 0;\n while(!q.empty()){\n x = q.front();\n q.pop();\n if(adj[x].size() == 1){\n for(int y: adj[x]){\n endCost[y].second--;\n if(endCost[y].second == 1){\n endCost[y].first = 0;\n q.push(y);\n }\n }\n }\n else{\n gi = -1;\n si = -1;\n gl = -1;\n sl = -1;\n for(int i = 0; i < adj[x].size(); i++){\n if(endCost[adj[x][i]].first == - 1){\n endCost[adj[x][i]].second--;\n if(endCost[adj[x][i]].second == 1){\n endCost[adj[x][i]].first = 0;\n q.push(adj[x][i]);\n }\n }\n else if(endCost[adj[x][i]].first > 0){\n if(gi == -1 || endCost[adj[x][i]].first > endCost[adj[x][gi]].first){\n si = gi;\n gi = i;\n }\n else if(si == -1 || endCost[adj[x][i]].first > endCost[adj[x][si]].first){\n si = i;\n }\n if(gl == -1 || endCost[adj[x][i]].second > endCost[adj[x][gl]].second){\n sl = gl;\n gl = i;\n }\n else if(sl == -1 || endCost[adj[x][i]].second > endCost[adj[x][sl]].second){\n sl = i;\n }\n if(si != -1){\n if(gi == gl){\n ans = max(ans, endCost[adj[x][gi]].first + endCost[adj[x][sl]].second + price[x]);\n ans = ans = max(ans, endCost[adj[x][si]].first + endCost[adj[x][gl]].second + price[x]);\n }\n else{\n ans = max(ans, endCost[adj[x][gi]].first + endCost[adj[x][gl]].second + price[x]);\n }\n }\n } \n }\n endCost[x].first = endCost[adj[x][gi]].first + price[x];\n endCost[x].second = endCost[adj[x][gl]].second + price[x];\n }\n }\n return ans;\n }\n};\n```
0
0
[]
0
difference-between-maximum-and-minimum-price-sum
Both O(n) and O(nlog(n)) Solutions C++
both-on-and-onlogn-solutions-c-by-kumar_-yr9v
Complexity\n- Time complexity:\nO(nlog(n))\n\n- Space complexity:\n- O(n)\n\n# Code\n\nclass Solution {\npublic:\n vector<vector<int>>adjList ;\n long lon
Kumar_11
NORMAL
2023-03-31T04:35:47.675038+00:00
2023-03-31T04:35:47.675083+00:00
72
false
# Complexity\n- Time complexity:\nO(nlog(n))\n\n- Space complexity:\n- O(n)\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>>adjList ;\n long long result ;\n void ans(int source , int parent , vector<int>&price , vector<long long>&sum ){\n result = max(result , sum[source] - price[source]);\n cout<<source<<" "<<sum[source]<<endl;\n map<long long , long long>another ;\n for(auto it : adjList[source]){\n another[sum[it]]++ ;\n }\n for(auto it : adjList[source]){\n if(it != parent){\n another[sum[it]]-- ;\n if(another[sum[it]] == 0)\n another.erase(sum[it]);\n long long ne = sum[it];\n long long first = sum[source];\n if(another.size() == 0){\n sum[source] = price[source];\n if(sum[it] < price[source] + price[it]){\n sum[it] = price[source] + price[it];\n }\n ans(it , source , price , sum);\n sum[source] = first ;\n sum[it] = ne ;\n }\n else{\n long long k = another.rbegin()->first;\n k += price[source];\n sum[source] = k ;\n if(sum[it] < k + (long long)price[it]){\n sum[it] = k + price[it] ;\n }\n ans(it , source , price , sum);\n sum[source] = first ;\n sum[it] = ne;\n }\n another[sum[it]]++;\n }\n }\n // sum[source] = curr ;\n }\n void dfs(int source , int parent , vector<int>&price , vector<long long>&sum){\n sum[source] = price[source];\n long long curr = 0 ;\n for(auto it : adjList[source]){\n if(it != parent){\n dfs(it , source , price , sum);\n curr = max(curr , sum[it]);\n }\n }\n sum[source] += curr ;\n }\n long long maxOutput(int n, vector<vector<int>>& edges, vector<int>& price) {\n vector<long long>sum(n);\n adjList.resize(n);\n for(auto it : edges){\n adjList[it[0]].push_back(it[1]);\n adjList[it[1]].push_back(it[0]);\n }\n dfs(0 , -1 , price , sum);\n result = 0 ;\n ans(0 , -1 , price , sum);\n return result ;\n }\n};\n};\n```\n\n\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\n- O(n)\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>>adjList ;\n vector<vector<long long>>mx ;\n vector<long long>price_sum ;\n long long result ;\n void dfs1(int source , int parent , vector<int>&price){\n price_sum[source] = price[source];\n long long curr = 0 ;\n for(auto it : adjList[source]){\n if(it != parent){\n dfs1(it , source , price);\n curr = max(curr , price_sum[it]);\n }\n }\n price_sum[source] += curr ;\n }\n\n void dfs2(int source , int parent , vector<int>&price){\n result = max(result , price_sum[source] - price[source]);\n // cout<<source<<" "<<price_sum[source]<<endl;\n for(auto it : adjList[source]){\n if(it != parent){\n long long ne = price_sum[it];\n long long first = price_sum[source];\n if(mx[source][1] == -1){\n price_sum[source] = price[source];\n long long g = price_sum[source];\n long long a = mx[it][0] , b = mx[it][1];\n if(g >= mx[it][0]){\n mx[it][1] = mx[it][0];\n mx[it][0] = g;\n }\n else if(g >= mx[it][1]){\n mx[it][1] = g ;\n }\n price_sum[it] = max(price_sum[it] , price_sum[source] + price[it]);\n dfs2(it , source , price);\n mx[it][0] = a , mx[it][1] = b ;\n price_sum[source] = first ;\n price_sum[it] = ne ;\n }\n else{\n if(price_sum[it] == mx[source][0]){\n price_sum[source] = price[source] + mx[source][1];\n }\n else{\n price_sum[source] = price[source] + mx[source][0];\n }\n long long g = price_sum[source];\n long long a = mx[it][0] , b = mx[it][1];\n if(g >= mx[it][0]){\n mx[it][1] = mx[it][0];\n mx[it][0] = g;\n }\n else if(g >= mx[it][1]){\n mx[it][1] = g ;\n }\n price_sum[it] = max(price_sum[it] , price_sum[source] + price[it]);\n dfs2(it , source , price);\n mx[it][0] = a , mx[it][1] = b ;\n price_sum[source] = first ;\n price_sum[it] = ne ;\n\n }\n }\n }\n }\n vector<int>par ;\n void dfs(int source , int parent ){\n par[source] = parent ;\n for(auto it : adjList[source]){\n if(it != parent){\n dfs(it , source);\n }\n }\n }\n long long maxOutput(int n, vector<vector<int>>& edges, vector<int>& price) {\n if(n == 1)return 0 ;\n result = 0 ;\n adjList.resize(n);\n price_sum.resize(n);\n for(auto it : edges){\n adjList[it[0]].push_back(it[1]);\n adjList[it[1]].push_back(it[0]);\n }\n par.resize(n);\n dfs(0 , -1);\n\n dfs1(0 , -1 , price);\n for(int i = 0 ; i < n ; i++){\n long long first = -1 , second = -1 ;\n for(auto it : adjList[i]){\n if(it == par[i])\n continue;\n if(price_sum[it] > first){\n second = first ;\n first = price_sum[it] ;\n }\n else if(price_sum[it] > second){\n second = price_sum[it];\n }\n }\n vector<long long>a;\n a.push_back(first) , a.push_back(second);\n mx.push_back(a);\n }\n dfs2(0 , -1 , price);\n\n return result ;\n // return 0 ;\n }\n};\n```
0
0
['C++']
0
difference-between-maximum-and-minimum-price-sum
Graph traversal, C#
graph-traversal-c-by-user4435yf-lpk4
\n\n# Complexity\n- Time complexity:\nO(n) \nEvery node gets visited exactly once during recursive solution.\n\n- Space complexity:\nO(n) for graph connectivity
user4435YF
NORMAL
2023-03-29T20:30:04.122889+00:00
2023-03-29T20:30:04.122921+00:00
24
false
\n\n# Complexity\n- Time complexity:\n$$O(n)$$ \nEvery node gets visited exactly once during recursive solution.\n\n- Space complexity:\n$$O(n)$$ for graph connectivity and also $$O(n)$$ worst-case stack requirement\n\n# Code\n```\npublic class Solution {\n public long MaxOutput(int n, int[][] edges, int[] price) {\n var conn = new List<int>[n];\n for(int i = 0; i < n; i++)\n conn[i] = new List<int>();\n foreach(var v in edges)\n {\n conn[v[0]].Add(v[1]);\n conn[v[1]].Add(v[0]);\n }\n\n int best = 0;\n bool[] visited = new bool[n];\n\n //We are looking for the max sum of a path without counting one element at one end of the path\n //Approach: \n //for every subtree of node, find its max sum and its max sum without last element\n //From these values, calculate maximum sum of path crossing this node\n //iteratively visit every node\n (int node, int sum, int sumWithoutLast) traverse(int node)\n { \n visited[node] = true;\n var subtrees = new List<(int node, int sum, int sumWithoutLast)>();\n foreach(int c in conn[node])\n { \n if(!visited[c])\n subtrees.Add(traverse(c));\n }\n //leaf node\n if(subtrees.Count == 0)\n return (node, price[node], 0);\n\n //only one node, path starts or ends here\n if(subtrees.Count == 1)\n {\n best = Math.Max(best, subtrees[0].sumWithoutLast + price[node]);\n best = Math.Max(best, subtrees[0].sum);\n return (node, subtrees[0].sum + price[node], subtrees[0].sumWithoutLast + price[node]);\n }\n\n //>=2 child nodes, max sum path must be crossing this node\n subtrees.Sort((x, y) => y.sum.CompareTo(x.sum));\n var bySum1 = subtrees[0];\n var bySum2 = subtrees[1];\n subtrees.Sort((x, y) => y.sumWithoutLast.CompareTo(x.sumWithoutLast));\n var bySumWO1 = subtrees[0];\n var bySumWO2 = subtrees[1];\n if(bySum1.node != bySumWO1.node)\n {\n //best sum node and best sum without last node are different, therefore we may use the best node of both\n best = Math.Max(best, bySum1.sum + bySumWO1.sumWithoutLast + price[node]);\n }\n else\n {\n //best sum node and best sum without last node are equal\n //therefore we may use only one of them and must use the second best for the other one\n best = Math.Max(best, bySum1.sum + bySumWO2.sumWithoutLast + price[node]);\n best = Math.Max(best, bySum2.sum + bySumWO1.sumWithoutLast + price[node]);\n }\n return (node, bySum1.sum + price[node], bySumWO1.sumWithoutLast + price[node]);\n }\n\n traverse(0);\n return best;\n }\n}\n```
0
0
['Tree', 'C#']
0
difference-between-maximum-and-minimum-price-sum
Tree Dp and Re-rooting Technique| O(N) Code (C++)
tree-dp-and-re-rooting-technique-on-code-rvq7
Intuition\nFixing the root then using re-rooting technique to find the solution for all the other roots.\n# Time Complexity\nO(n)\n# Code\n\n#define ll long lon
rahulhind
NORMAL
2023-03-21T16:28:20.165341+00:00
2023-03-21T16:28:20.165372+00:00
140
false
# Intuition\nFixing the root then using re-rooting technique to find the solution for all the other roots.\n# Time Complexity\n$$O(n)$$\n# Code\n```\n#define ll long long\nclass Solution {\npublic:\n const static int M=1e5+100;\n ll dp[M];\n void dfs(int s,int p,vector<vector<int>>&graph,vector<int>&cost){\n \n ll mx=0;\n dp[s]=cost[s];\n for(auto i:graph[s]){\n if(i!=p){\n dfs(i,s,graph,cost);\n mx=max(mx,dp[i]);\n }\n }\n dp[s]+=mx;\n }\n \n \n ll ans=0;\n void reroot(int s,int p,vector<vector<int>>&graph,vector<int>&cost){\n ans=max(dp[s],ans);\n \n vector<ll>suf,pref;\n for(auto i:graph[s]){\n if(i!=p){\n pref.push_back(dp[i]);\n suf.push_back(dp[i]);\n }\n }\n//Prefix and Suffix Max array for eliminating the current Child and getting max fromt all the other child path except the i\'th child.\n\n for(int i=1;i<(int)pref.size();i++){\n pref[i]=max(pref[i],pref[i-1]);\n }\n for(int i=(int)suf.size()-2;i>=0;i--){\n suf[i]=max(suf[i+1],suf[i]);\n }\n \n ll t1=dp[s];\n int it=0;\n for(auto i:graph[s]){\n if(i!=p){\n ll l=0,r=0;\n if(it-1>=0)\n l=pref[it-1];\n if(it+1<(int)suf.size())\n r=suf[it+1];\n \n ll t2=dp[i];\n dp[s]=max(l,r);\n \n if(p!=-1)\n dp[s]=max(dp[s],dp[p]);\n\n dp[s]+=cost[s];\n dp[i]-=cost[i];\n dp[i]=max(dp[i],dp[s]);\n \n reroot(i,s,graph,cost);\n\n dp[s]=t1;\n dp[i]=t2;\n it++;\n \n }\n }\n \n }\n \n long long maxOutput(int n, vector<vector<int>>& edges, vector<int>& price) {\n vector<vector<int>>graph(n);\n for(auto it:edges){\n graph[it[0]].push_back(it[1]);\n graph[it[1]].push_back(it[0]);\n }\n dfs(0,-1,graph,price);\n dp[0]-=price[0];\n// Considering root 0 as intital and calulating for all the other roots by re-rooting.\n reroot(0,-1,graph,price);\n \n \n return ans ;\n }\n};\n```
0
0
['Dynamic Programming', 'Tree', 'Memoization', 'C++']
0
difference-between-maximum-and-minimum-price-sum
Reroot so only 2 dfs is needed instead of n dfs.
reroot-so-only-2-dfs-is-needed-instead-o-w426
Intuition\nWe can treat every node as root, and run DFS n times. But we can use re-root trick to do two DFS.\n\n# Code\n\nstruct GraphNode {\n GraphNode(int
huangdachuan
NORMAL
2023-03-13T03:42:43.940480+00:00
2023-03-13T03:42:43.940523+00:00
53
false
# Intuition\nWe can treat every node as root, and run DFS n times. But we can use re-root trick to do two DFS.\n\n# Code\n```\nstruct GraphNode {\n GraphNode(int id, int cost):\n id(id),\n cost(cost),\n neighbors(),\n maxDepth(cost),\n maxNodeId(-1),\n max2Depth(cost)\n {}\n\n void updateFromChild(int childNodeId, long long childMaxDepth) {\n if (maxDepth < childMaxDepth + cost) {\n max2Depth = maxDepth;\n maxNodeId = childNodeId;\n maxDepth = childMaxDepth + cost;\n } else if (max2Depth < childMaxDepth + cost) {\n max2Depth = childMaxDepth + cost;\n }\n }\n\n void updateFromParent(int parentNodeId, long long parentMaxDepth, int parentMaxNodeId, long long parentMax2Depth) {\n if (parentMaxNodeId == -1 || parentMaxNodeId != id) {\n updateFromChild(parentNodeId, parentMaxDepth);\n } else {\n updateFromChild(parentNodeId, parentMax2Depth);\n }\n }\n\n int id;\n int cost;\n vector<int> neighbors;\n long long maxDepth;\n int maxNodeId;\n long long max2Depth;\n};\n\nclass Solution {\npublic:\n long long maxOutput(int n, vector<vector<int>>& edges, vector<int>& price) {\n vector<GraphNode> graph = SetupGraph(n, edges, price);\n dfs(graph, 0, -1);\n dfs2(graph, 0, -1);\n long long ans = 0;\n for (int i = 0; i < n; ++i) {\n ans = max(ans, graph[i].maxDepth - graph[i].cost);\n }\n return ans;\n }\n\nprivate:\n vector<GraphNode> SetupGraph(int n, vector<vector<int>>& edges, vector<int>& price) {\n vector<GraphNode> graph;\n for (int i = 0; i < n; ++i) {\n graph.emplace_back(i, price[i]);\n }\n for (vector<int>& edge : edges) {\n int u = edge[0], v = edge[1];\n graph[u].neighbors.emplace_back(v);\n graph[v].neighbors.emplace_back(u);\n }\n return graph;\n }\n\n void dfs(vector<GraphNode>& graph, int i, int p) {\n for (int neighborId : graph[i].neighbors) {\n if (neighborId != p) {\n dfs(graph, neighborId, i);\n graph[i].updateFromChild(neighborId, graph[neighborId].maxDepth);\n }\n }\n }\n\n void dfs2(vector<GraphNode>& graph, int i, int p) {\n for (int neighborId : graph[i].neighbors) {\n if (neighborId != p) {\n graph[neighborId].updateFromParent(i, graph[i].maxDepth, graph[i].maxNodeId, graph[i].max2Depth);\n dfs2(graph, neighborId, i);\n }\n }\n }\n};\n\n```
0
0
['C++']
0
difference-between-maximum-and-minimum-price-sum
100% working || DFS || Re-rooting Technique
100-working-dfs-re-rooting-technique-by-tknvl
Intuition\nUsing the re-rooting technique\n\nTo understand this technique visit the on this you-tube link : \n\nhttps://www.youtube.com/watch?v=N7e4CTfimkU\n\n#
gauravgoyal_13
NORMAL
2023-03-07T07:42:03.091129+00:00
2023-03-07T07:42:03.091171+00:00
84
false
# Intuition\nUsing the re-rooting technique\n\nTo understand this technique visit the on this you-tube link : \n\nhttps://www.youtube.com/watch?v=N7e4CTfimkU\n\n# Complexity\n- Time complexity: O(N)\n\n- Space complexity: O(N)\n\n** **\n**Please upvote me if it helpful for you... happy coding**\n# Code\n```\n#include<unordered_map>\n#include<map>\n#include<math.h>\n#include<vector>\n#include<string>\n#define endl \'\\n\'\n#define ll long long\n#define pb push_back\n#define pf push_front\n#define ff first \n#define ss second\n#define sz(x) (int)(x).size()\n#define pi 3.141592653589793238\n#define MOD 1000000007\n#define pinf INT_MAX\n#define minf INT_MIN\n#define py cout << "YES\\n"\n#define pn cout << "NO\\n"\n#define vi vector<ll>\n#define vb vector<bool>\nusing namespace std;\n#define all(x) (x).begin(),(x).end()\n\nll depth[2000001];\nll ans[2000001];\nll p[2000001];\n \nvoid eval_depth(vector<vector<ll>>& adj, ll src, ll par) {\n bool leaf = 1;\n ll maxi = 0;\n for(auto u : adj[src]) {\n if(u != par) {\n leaf = 0;\n eval_depth(adj, u, src);\n maxi = max(maxi, depth[u]);\n }\n }\n if(leaf) depth[src] = p[src];\n else depth[src] = maxi + p[src];\n}\n \nvoid dfs(vector<vector<ll>>& adj, ll src, ll par, ll partial) {\n vi prefix, suffix;\n for(auto child : adj[src]) {\n if(child != par) {\n prefix.pb(depth[child]);\n suffix.pb(depth[child]);\n }\n }\n ll n = prefix.size();\n for(int i = 1; i < n; i++) {\n prefix[i] = max(prefix[i], prefix[i - 1]);\n }\n for(int i = n - 2; i >= 0; i--) {\n suffix[i] = max(suffix[i], suffix[i + 1]);\n }\n \n ll c_no = 0;\n for(ll child : adj[src]) {\n if(child != par) {\n ll op1 = c_no == 0? 0 : prefix[c_no - 1];\n ll op2 = c_no == suffix.size() - 1? 0 : suffix[c_no + 1];\n ll par_ans = p[src] + max(partial, max(op1, op2));\n dfs(adj, child, src, par_ans);\n c_no++;\n }\n }\n ans[src] = max((prefix.empty()? 0 : prefix.back()), partial);\n}\n\nclass Solution {\npublic:\n long long maxOutput(int n, vector<vector<int>>& edges, vector<int>& price) {\n for(int i = 0; i < n; i++) {\n p[i] = price[i];\n }\n vector<vector<ll>> adj(n);\n for(int i = 0; i < n - 1; i++) {\n int a = edges[i][0];\n int b = edges[i][1];\n adj[a].pb(b);\n adj[b].pb(a);\n }\n eval_depth(adj, 0, -1);\n dfs(adj, 0, -1, 0);\n ll res = 0;\n for(int i = 0; i < n; i++) {\n res = max(res, ans[i]);\n cout << ans[i] << " ";\n }\n return res;\n }\n};\n```
0
0
['C++']
0
difference-between-maximum-and-minimum-price-sum
Deatiled description C++ easy to understand code
deatiled-description-c-easy-to-understan-gimv
\nclass Solution {\npublic:\n long long result = 0;\n // Function to compute the max sum for a given subtree across all the nodes\n long long maxSum(in
vishalrathi02
NORMAL
2023-02-15T03:15:44.342108+00:00
2023-02-15T03:15:44.342145+00:00
31
false
```\nclass Solution {\npublic:\n long long result = 0;\n // Function to compute the max sum for a given subtree across all the nodes\n long long maxSum(int from, int cur, vector<vector<int>> &adj, vector<int> &price, vector<long long> &dp) {\n long long res = 0;\n for (auto &to : adj[cur]) {\n if (from == to) continue;\n res = max(res,maxSum(cur,to,adj,price,dp));\n }\n dp[cur] = price[cur] + res;\n return dp[cur];\n }\n // DFS each node from same start from where maxSum was calucualted\n // for a given node, there are n sums, 1 sum from parent chain, rest all from its chidlrens.\n // if current node is removed then max Cost will be max of its parent Sum path and all rest of siblings.\n void dfs(int from, int cur, vector<vector<int>> &adj, vector<int> &price, vector<long long> &dp, long long parentSum) {\n int maxChild = -1;\n long long firstMax = 0; long long secondMax = 0;\n for (auto &to : adj[cur]) {\n if (to == from) continue;\n if (dp[to] > firstMax) {\n secondMax = firstMax;\n firstMax = dp[to];\n maxChild = to;\n } else if (dp[to] > secondMax) {\n secondMax = dp[to];\n }\n }\n // result captured if current node is cut off it is max of parent Sum or one of neighbors children sum\n long long curMax = max(parentSum,firstMax);\n result = max(result,curMax);\n int curPrice = price[cur];\n for (auto &to : adj[cur]) {\n if (to == from) continue;\n if (to == maxChild) {\n // if child is part of the maxResult chain of current node\n // take max of 2nd max neighbor which doesn\'t include the current node\n // or parent Sum, Add the current node and pass on the chain to parentSum for \n // next chile\n dfs(cur,to,adj,price,dp,curPrice+max(parentSum,secondMax));\n } else {\n // if max path from current parent doesn\'t include this node\n dfs(cur,to,adj,price,dp,curPrice+curMax);\n }\n }\n }\n \n long long maxOutput(int n, vector<vector<int>>& edges, vector<int>& price) {\n vector<vector<int>> adj(n);\n for (auto &e: edges) {\n adj[e[0]].push_back(e[1]);\n adj[e[1]].push_back(e[0]);\n }\n vector<long long> dp(n,0);\n maxSum(-1,0,adj,price,dp);\n dfs(-1,0,adj,price,dp,0);\n return result;\n }\n};\n```
0
0
[]
0
difference-between-maximum-and-minimum-price-sum
C++ || DFS( Two DFS traversal)
c-dfs-two-dfs-traversal-by-hrithik8083-1ne6
0.\n\n# Code\n\nclass Solution {\npublic:\n void dfs2(vector<vector<int>>& adj,vector<long long>&sum,vector<int>&vis,int u,vector<int>&price,vector<long long
hrithik8083
NORMAL
2023-02-07T18:38:20.564136+00:00
2023-02-07T18:38:20.564178+00:00
122
false
0.\n\n# Code\n```\nclass Solution {\npublic:\n void dfs2(vector<vector<int>>& adj,vector<long long>&sum,vector<int>&vis,int u,vector<int>&price,vector<long long>& dist)\n {\n vis[u]=1;\n long long max1=0;\n long long max2=0;\n for(auto x:adj[u])\n {\n if(vis[x]==0)\n {\n if(sum[x]>=max1)\n {\n max2=max1;\n max1=sum[x];\n }\n else if(sum[x]>max2)\n max2=sum[x];\n }\n }\n \n long long calc=0;\n for(auto x:adj[u])\n { \n if(vis[x]==0)\n {\n \n if(max1==sum[x])\n {\n dist[x]=price[x]+max(max2+price[u],dist[u]);\n }\n else \n {\n dist[x]=price[x]+max(max1+price[u],dist[u]);\n }\n \n dfs2(adj,sum,vis,x,price,dist);\n } \n }\n }\n long long dfs1(vector<vector<int>>& adj,vector<long long>&sum,vector<int>&vis,int u,vector<int>&price)\n {\n vis[u]=1;\n long long val=0;\n long long ans=0;\n for(auto x:adj[u])\n { \n if(vis[x]==0)\n {\n val=dfs1(adj,sum,vis,x,price); \n ans=max(ans,val);\n }\n }\n \n sum[u]=ans+price[u];\n return sum[u];\n }\n long long maxOutput(int n, vector<vector<int>>& edges, vector<int>& price) {\n \n vector<long long>sum(n,0);\n vector<vector<int>>adj(n,vector<int>());\n for(int i=0;i<edges.size();i++)\n {\n adj[edges[i][0]].push_back(edges[i][1]);\n adj[edges[i][1]].push_back(edges[i][0]);\n }\n vector<int>vis(n,0);\n dfs1(adj,sum,vis,0,price);\n vector<int>vis2(n,0);\n vector<long long>dist(n,0);\n dfs2(adj,sum,vis2,0,price,dist);\n long long calc=0;\n for(int i=0;i<n;i++)\n {\n \n calc=max(calc,(max(sum[i],dist[i])-price[i]));\n }\n return calc;\n }\n};\n\n\n\n\n```
0
0
['Depth-First Search', 'Binary Tree', 'C++']
0
difference-between-maximum-and-minimum-price-sum
O(n) Re-rooting w/ Two-Pass Bidirectional DFS • 🎨 Diagram 💬 Comments 📛 Semantic Variables
on-re-rooting-w-two-pass-bidirectional-d-0i08
Approach\nThe brute-force approach would be to calculate the max path using a DFS from each node but this results in a TLE due to the O(n * n) time complexity.
jeffcamera
NORMAL
2023-02-01T18:53:06.736393+00:00
2023-02-01T18:53:06.736428+00:00
66
false
# Approach\nThe brute-force approach would be to calculate the max path using a DFS from each node but this results in a TLE due to the O(n * n) time complexity. Instead we do two DFS passes and store two solutions for each node. This allows us to figure out the max path for each node on the second pass.\n\nIn the first pass we do a normal DFS traversal to find the max path from each node to its children but after this traversal our results are incomplete since we never considered the opposite path from child to parent (if we used a different root) which could result in a larger max path. This is why we do a second traversal in the opposite direction. The trick is that when we go in reverse from parent to child we have to be careful that we don\'t create a cycle.\n\nIn the diagram below you can see that in the second pass node #1 points to the 2nd top neighbor of node #0 since the 1st top neighbor points back to node #1 which would create a cycle. This is why we need to store not only the max path for each node but also the 2nd top path as well.\n\nYou can also see that we could return our max result (20) directly from the 2nd traversal but I broke it out into another loop to make the code clearer.\n\n![2023-01-15-notes.jpg](https://assets.leetcode.com/users/images/945c054a-2d19-4777-9992-d56cbf822d35_1675276627.1758919.jpeg)\n\n# Complexity\n- Time complexity: O(n) - Two linear traversals of the tree.\n- Space complexity: O(n) - Dynamic programming cache stores constant data for each node.\n\n# Code\n```\n// A simple data structure to hold the root of a subtree and the sum of its\n// maximum path.\npublic record PathSum(int Root, long Sum);\n\n// A sort of specialized collection class that only holds the top two PathSums\n// with the largest sums.\npublic class TopNeighborPaths\n{\t\n private PathSum? _first;\n private PathSum? _second;\n \n private long _firstSum => _first?.Sum ?? 0;\n private long _secondSum => _second?.Sum ?? 0;\n\n // Adds the provided PathSum only if it is greater than either of the\n // existing PathSums.\n public void Add(PathSum pathSum)\n {\n if (pathSum.Sum > _firstSum)\n {\n _second = _first;\n _first = pathSum;\n }\n else if (pathSum.Sum > _secondSum)\n {\n _second = pathSum;\n }\n }\n \n // Returns the max sum, optionally excluding a specific neighbor.\n public long GetMaxSum(int? neighborToExclude = null)\n {\n if (\n _first is not null &&\n (neighborToExclude is null || _first.Root != neighborToExclude)\n )\n {\n return _first.Sum;\n }\n return _secondSum;\n }\n}\n\n// Run a depth-first search on the tree, measuring the top paths for each node\'s\n// children.\npublic void MeasureChildrenMaxPaths(\n Dictionary<int, HashSet<int>> adjList,\n int[] prices,\n int node,\n int parent,\n TopNeighborPaths[] topNeighborPathsCache\n)\n{\n var topNeighborPaths = new TopNeighborPaths();\n foreach (var child in adjList[node])\n {\n if (child == parent)\n {\n continue;\n }\n \n // First measure the max paths for the child node.\n MeasureChildrenMaxPaths(\n adjList,\n prices,\n child,\n node,\n topNeighborPathsCache\n );\n \n // Then add the path sum for this node to the child by adding the price\n // of the child plus its max path.\n topNeighborPaths.Add(\n new PathSum(\n Root: child,\n Sum: prices[child] + topNeighborPathsCache[child].GetMaxSum()\n )\n );\n }\n topNeighborPathsCache[node] = topNeighborPaths;\n}\n\n// Run a depth-first search on the tree, measuring the top path for each node\'s\n// parent.\npublic void MeasureParentMaxPaths(\n Dictionary<int, HashSet<int>> adjList,\n int[] prices,\n int node,\n int parent,\n TopNeighborPaths[] topNeighborPathsCache\n)\n{\n if (parent != -1)\n {\n // When we add the path sum for this node to the parent we perform the\n // same steps as we do for the children, only we need to exclude the\n // first path if it leads back to this node.\n topNeighborPathsCache[node].Add(\n new PathSum(\n Root: parent,\n Sum: prices[parent] +\n topNeighborPathsCache[parent].GetMaxSum(\n neighborToExclude: node\n )\n )\n );\n }\n foreach (var child in adjList[node])\n {\n if (child == parent)\n {\n continue;\n }\n MeasureParentMaxPaths(\n adjList,\n prices,\n child,\n node,\n topNeighborPathsCache\n );\n }\n}\n\npublic long MaxOutput(int n, int[][] edges, int[] prices)\n{\n // Handle the edge case of a single node here so that we don\'t have to keep\n // checking for a node without edges later on.\n if (n == 1)\n {\n return 0;\n }\n \n // Build the adjacency list to efficiently traverse the tree.\n var adjList = new Dictionary<int, HashSet<int>>();\n foreach (var edge in edges)\n {\n int\n a = edge[0],\n b = edge[1];\n if (!adjList.ContainsKey(a))\n {\n adjList.Add(a, new());\n }\n if (!adjList.ContainsKey(b))\n {\n adjList.Add(b, new());\n }\n adjList[a].Add(b);\n adjList[b].Add(a);\n }\n \n // Set up our dynamic programming cache to store our work.\n var topNeighborPathsCache = new TopNeighborPaths[n];\n \n // First measure the max paths of the children for each node.\n MeasureChildrenMaxPaths(adjList, prices, 0, -1, topNeighborPathsCache);\n \n // Then measure the max path of the parent for reach node.\n MeasureParentMaxPaths(adjList, prices, 0, -1, topNeighborPathsCache);\n \n // Check the max cost for each node to find our result.\n long maxCost = 0;\n foreach (var kvp in adjList)\n {\n // The root with the highest cost will be a leaf node so we can skip any\n // non-leaf nodes.\n if (kvp.Value.Count > 1)\n {\n continue;\n }\n \n // Since the cost for any root is the max price sum minus the min price\n // sum and the min price sum is always the price of the root the max sum\n // of the neighbor paths will be the cost.\n maxCost = Math.Max(maxCost, topNeighborPathsCache[kvp.Key].GetMaxSum());\n }\n return maxCost;\n}\n```
0
0
['Dynamic Programming', 'Depth-First Search', 'C#']
0
difference-between-maximum-and-minimum-price-sum
C++ up-to-down and down-to-up DFS
c-up-to-down-and-down-to-up-dfs-by-vvhac-brjt
Sorry my English here might not be the best.\nFirst of all, the min price path is just the node by itself.\nWe pick any root at random, let\'s say 0.\nFirst we
vvhack
NORMAL
2023-01-28T21:29:27.949090+00:00
2023-01-28T21:33:25.353445+00:00
43
false
Sorry my English here might not be the best.\nFirst of all, the min price path is just the node by itself.\nWe pick any root at random, let\'s say 0.\nFirst we get information from children and pass it up to the root (what is the maximum price path going downwards from the root) then we do another pass in which we pass information from the root down to the children (what is the maximum cost path if I pass through the parent). That way every node will know its own cost if it were the root.\n```\nclass Solution {\npublic:\n struct Node {\n long long price;\n Node(long long price) : price(price) {}\n vector<int> neighbors;\n map<long long, int> costToNeighbor;\n \n // Get the maximum cost for the path starting from nbIdx\n // and passing through this node.\n long long getMaxCost(int nbIdx = -1) {\n if (costToNeighbor.empty()) {\n return price;\n } else {\n auto it = --costToNeighbor.end();\n if (it->second == nbIdx) {\n if (it == costToNeighbor.begin()) {\n return price;\n } else {\n --it;\n return price + it->first;\n }\n } else {\n return price + it->first;\n }\n }\n }\n \n long long getCost() {\n // The node\'s own price will always be the minimum cost.\n return getMaxCost() - price;\n }\n };\n \n vector<Node> graph;\n \n long long maxOutput(int n, vector<vector<int>>& edges, vector<int>& price) {\n for (int i = 0; i < n; ++i) {\n graph.push_back(Node(price[i]));\n }\n for (auto& edge : edges) {\n graph[edge[0]].neighbors.push_back(edge[1]);\n graph[edge[1]].neighbors.push_back(edge[0]);\n }\n downToUp(0, -1);\n upToDown(0, -1, -1);\n long long maxCost = 0;\n for (int i = 0; i < n; ++i) {\n maxCost = max(maxCost, graph[i].getCost());\n }\n return maxCost;\n }\n \n void upToDown(int nodeIdx, int parentIdx, int parentMaxCost) {\n auto& node = graph[nodeIdx];\n if (parentIdx != -1) {\n if (parentMaxCost != -1) {\n node.costToNeighbor[parentMaxCost] = parentIdx; \n // The map just needs to hold the highest and the\n // second highest cost.\n if (node.costToNeighbor.size() > 2) {\n node.costToNeighbor.erase(node.costToNeighbor.begin()->first);\n }\n }\n }\n for (int nbIdx : node.neighbors) {\n if (nbIdx == parentIdx) continue;\n int maxCost = -1;\n upToDown(nbIdx, nodeIdx, node.getMaxCost(nbIdx));\n }\n }\n \n void downToUp(int nodeIdx, int parentIdx) {\n auto& node = graph[nodeIdx];\n for (int nbIdx : node.neighbors) {\n if (nbIdx == parentIdx) continue;\n auto& nb = graph[nbIdx];\n downToUp(nbIdx, nodeIdx);\n node.costToNeighbor[nb.getMaxCost()] = nbIdx;\n // The map just needs to hold the highest and the\n // second highest cost.\n if (node.costToNeighbor.size() > 2) {\n node.costToNeighbor.erase(node.costToNeighbor.begin()->first);\n }\n }\n }\n};\n\n```
0
0
[]
0
check-if-the-number-is-fascinating
3 lines || C++ || Easy
3-lines-c-easy-by-shrikanta8-80k2
CodeHappy Coding!Radhe Radhe😊
Shrikanta8
NORMAL
2023-06-10T16:02:00.611319+00:00
2025-02-20T19:00:10.545472+00:00
1,872
false
# Code ``` class Solution { public: bool isFascinating(int n) { string str= to_string(n)+to_string(2*n)+to_string(3*n); sort(str.begin(),str.end()); return str == "123456789"; } }; ``` **Happy Coding!** Radhe Radhe😊
22
1
['C++']
2
check-if-the-number-is-fascinating
Using set || Very simple and easy to understand solution
using-set-very-simple-and-easy-to-unders-koft
Up vote if you like the solution\n# Approach\nTake a set to check total number of uniqe char in the final string.\nIn the set check :\n- if the total unique cha
kreakEmp
NORMAL
2023-06-10T16:16:11.502409+00:00
2023-06-10T18:45:21.934249+00:00
2,682
false
<b>Up vote if you like the solution</b>\n# Approach\nTake a set to check total number of uniqe char in the final string.\nIn the set check :\n- if the total unique char count is 9\n- if the total size of the string s is 9\n- if there is no \'0\' in the string\n\n# Code\n```\nbool isFascinating(int n) {\n string s = to_string(n) + to_string(n*2) + to_string(n*3);\n unordered_set<char> st(s.begin(), s.end());\n return (st.size() == 9 && s.size() == 9 && st.find(\'0\') == st.end() );\n}\n```\n<b>Here is an article of my recent interview experience at Amazon, you may like :\nhttps://leetcode.com/discuss/interview-experience/3171859/Journey-to-a-FAANG-Company-Amazon-or-SDE2-(L5)-or-Bangalore-or-Oct-2022-Accepted
19
2
['C++']
4
check-if-the-number-is-fascinating
easy python code Beats 100% in Memory
easy-python-code-beats-100-in-memory-by-cjux8
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
hakkiot
NORMAL
2023-06-11T02:29:59.961417+00:00
2023-06-11T02:29:59.961441+00:00
717
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def isFascinating(self, n: int) -> bool:\n def pan(num):\n if sorted(list(num))==["1","2","3","4","5","6","7","8","9"]:\n return(True)\n else:\n return False\n n=str(n)+str(n*2)+str(n*3)\n return pan(n)\n```
17
0
['Python3']
1
check-if-the-number-is-fascinating
✅ Bits (O(1) Space)
bits-o1-space-by-xxvvpp-3shx
We just traverse all digits in all 3 numbers & use bit manipulation to check if every digit is between [1, 9].\n# C++\n bool isFascinating(int n) {\n
xxvvpp
NORMAL
2023-06-10T16:15:58.224804+00:00
2023-06-10T16:38:14.329433+00:00
1,835
false
We just traverse all digits in all `3` numbers & use `bit manipulation` to check if every digit is between `[1, 9]`.\n# C++\n bool isFascinating(int n) {\n int freq = 0;\n function<bool(int)> repd = [&](int n) {\n while(n) {\n int d = n % 10;\n if(d == 0 || (freq >> d & 1)) return false;\n freq |= (1 << d);\n n /= 10;\n }\n return true;\n };\n return repd(n) and repd(2 * n) and repd(3 * n);\n }\n
16
0
['Bit Manipulation', 'C']
5
check-if-the-number-is-fascinating
Python 3 || 2 versions || T/S: 94% / 79%
python-3-2-versions-ts-94-79-by-spauldin-u3hi
Version 1: string manipulation\n\nclass Solution:\n def isFascinating(self, n: int) -> bool: \n\n return \'\'.join(sorted(str(n) + str(2*n) + str(3*n)
Spaulding_
NORMAL
2023-06-10T17:43:13.282459+00:00
2024-06-18T17:37:29.380146+00:00
378
false
Version 1: string manipulation\n```\nclass Solution:\n def isFascinating(self, n: int) -> bool: \n\n return \'\'.join(sorted(str(n) + str(2*n) + str(3*n))) == \'123456789\'\n```\nVersion 2: Mathematics. It\'s an interesting number theory exercise to show that*:\n- a number`n`is *fascinating* only if `123 <= n <= 329`, and\n- `n`must be cyclic permutations of the digits of 192 or 273. \n\n```\nclass Solution:\n def isFascinating(self, n: int) -> bool:\n \n return n in {192, 219, 273, 327}\n```\n\n[https://leetcode.com/problems/check-if-the-number-is-fascinating/submissions/1292688362/](https://leetcode.com/problems/check-if-the-number-is-fascinating/submissions/1292688362/)\n\nI could be wrong, but I think that for each version, time complexity is *O*(1) and space complexity is *O*(1).\n\n*(Edit 6/14/23) By request, here is are the steps to how this assertion can be justified. We will need to use that:\na) n, 2n and 3n are each three distinct digits (which gives us the inequality`123 <= n <= 329`); and \nb) digit sums mod 9 are invariant under artihmetic operations (you may want to wiki "Casting Out Nines.")\n\nStep 1: The three digits of *n* must be one each of 0, 1, and 2 mod 3\nStep 2: The most significant digit of *n* is 1,2, or 3.\nStep 3: The three digits of *n* must be two odd and one even.\nStep 4: The 0 mod 3 digit of *n* must be either 3 or 9.\nStep 5: The largest digit of *n* must be either 7 or 9, but 7 and 9 cannot be the two odd digits.\nStep 6: The three digits of *n* must contain 1 or 7, but 1 and 7 cannot be the two odd digits.\nStep 7: The even digit of *n* must be 2.\nStep 8: Conclude that only two sets of digits for *n* are 1,2,9 and 2,3,7, of which only 192, 219, 273, and 327 satisfy the necessary conditions.\n\n
12
0
['Python3']
2
check-if-the-number-is-fascinating
2729. Check if The Number is Fascinating, Time complexity: O(N), Space complexity: O(N)
2729-check-if-the-number-is-fascinating-o7m37
IntuitionApproachComplexity Time complexity: O(N) Space complexity: O(N) Code
richardmantikwang
NORMAL
2024-12-23T10:36:33.919274+00:00
2024-12-23T10:36:33.919274+00:00
207
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: O(N) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(N) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] from collections import defaultdict class Solution: def isFascinating(self, num): two_times_num = 2 * num three_times_num = 3 * num nums_concatenation = str(num) + str(two_times_num) + str(three_times_num) digit_to_freq_map = defaultdict(int) for d in nums_concatenation: digit_to_freq_map[d] += 1 if (digit_to_freq_map[d] > 1): return False return len(set(range(1, 9 + 1)).difference(set([int(d) for d in list(nums_concatenation)]))) == 0 ```
10
0
['Python3']
0
check-if-the-number-is-fascinating
C++ || 2 different approaches || O(1) TC
c-2-different-approaches-o1-tc-by-heder-66ry
Approach 1: do the work at compile time\nThe property of being fascinating doesn\'t change, hence we can pre compute them at compile time. ::isFascinating is in
heder
NORMAL
2023-06-11T09:55:48.283317+00:00
2023-07-14T20:54:06.881704+00:00
982
false
# Approach 1: do the work at compile time\nThe property of being _fascinating_ doesn\'t change, hence we can pre compute them at compile time. ```::isFascinating``` is inspired by [this post](https://leetcode.com/problems/check-if-the-number-is-fascinating/discuss/3622454/Bits-(O(1)-Space)).\n\n```cpp\nnamespace {\nconstexpr bool isFascinating(int n) {\n int seen = 0;\n auto check = [&](int n) -> bool {\n while (n) {\n const int d = n % 10;\n n /= 10;\n const int mask = 1 << d;\n if (d == 0 || seen & mask) return false;\n seen |= mask;\n }\n return true;\n };\n return check(n) && check(2 * n) && check(3 * n);\n}\n\nconstexpr array<bool, 1000> gen_isF() {\n array<bool, 1000> ans = {};\n for (int i = 100; i < 1000; ++i) \n ans[i] = isFascinating(i);\n return ans;\n}\n \nconstexpr array<bool, 1000> isF = gen_isF();\n} // namespace\n\nclass Solution {\npublic:\n static bool isFascinating(int n) {\n return isF[n];\n }\n};\n```\n\n**Complexity Analysis**\n* Time complexity is $$O(1)$$ and\n\n* Space comlexity is $$O(1)$$, even if we need to keep an array of 1000 booleans around.\n\n# Approach 2: hard code it\nIt turns out there are only 4 _fascinating_ numbers: 192, 219, 273, and 327. We can just hard code that. Maybe that\'s consider cheating. :)\n\n```cpp\n bool isFascinating(int n) {\n return n == 192 || n == 219 || n == 273 || n == 327;\n }\n```\n\nIt\'s interesting how the compiler generates something that looks like binary search for this: https://godbolt.org/z/P9cr7fnE9\n\n**Complexity Analysis**\n* Time complexity is $$O(1)$$ and\n\n* Space comlexity is $$O(1)$$.\n\n_As always: Feedback, questions, and comments are welcome. Leaving an up-vote sparks joy! :)_\n\n**p.s. Join us on the [LeetCode The Hard Way Discord Server](https://discord.gg/hFUyVyWy2E)!**
10
0
['C']
2
check-if-the-number-is-fascinating
Most efficient O(1)
most-efficient-o1-by-java_programmer_ket-myud
There are just 4 numbers which satisfy this condition. TC->O(1)\n\nclass Solution {\n public boolean isFascinating(int n) {\n return n == 192 || n ==
Java_Programmer_Ketan
NORMAL
2023-06-10T17:28:36.254977+00:00
2023-06-10T17:28:36.255024+00:00
1,377
false
There are just 4 numbers which satisfy this condition. TC->O(1)\n```\nclass Solution {\n public boolean isFascinating(int n) {\n return n == 192 || n == 219 || n==273 || n==327;\n }\n}\n```
9
1
['Java']
4
check-if-the-number-is-fascinating
One Liner💯 (Easiest)
one-liner-easiest-by-shehza-d-3x6s
\n # Intuition \n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nI sort the input
shehza-d
NORMAL
2023-06-10T16:13:28.651617+00:00
2023-06-10T16:27:45.130847+00:00
644
false
\n<!-- # Intuition -->\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nI sort the input number in string and then matched with the desired outcome. \n\n# Code\n```js\nconst isFascinating = (n) => "123456789" === `${n}${n * 2}${n * 3}`.split("").sort().join("")\n```
7
0
['TypeScript', 'JavaScript']
0
check-if-the-number-is-fascinating
Easy and clean Solution [ Beginner Freindly] python3
easy-and-clean-solution-beginner-freindl-nitb
```\nclass Solution:\n def isFascinating(self, n: int) -> bool:\n s = str(n)\n \n s = s + str(2n) + str(3n)\n \n ans = set(s)\
KmrVikas
NORMAL
2023-06-10T16:07:10.746140+00:00
2023-06-10T16:07:10.746183+00:00
1,642
false
```\nclass Solution:\n def isFascinating(self, n: int) -> bool:\n s = str(n)\n \n s = s + str(2*n) + str(3*n)\n \n ans = set(s)\n\n return len(ans) == 9 == len(s) and \'0\' not in ans\n \n
6
1
[]
1
check-if-the-number-is-fascinating
3 lines easy c++ solution ✅✅
3-lines-easy-c-solution-by-te-ke_alone-ho72
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
te-ke_alone
NORMAL
2023-06-10T19:12:26.793349+00:00
2023-06-10T20:46:23.639322+00:00
385
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:\nO(NlogN)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\n bool isFascinating(int n) {\n \n string s = to_string(n) + to_string(n * 2) + to_string(n * 3);\n sort(s.begin(), s.end());\n\n if(s == "123456789") return true;\n return false;\n }\n};\n```
5
1
['String', 'Sorting', 'C++']
3
check-if-the-number-is-fascinating
100%,98% BEATS || C++
10098-beats-c-by-ganeshkumawat8740-tcfq
Code\n\nclass Solution {\npublic:\n bool isFascinating(int n) {\n string str = "";\n int a = n*2,b=n*3;\n str = to_string(n)+to_string(a
ganeshkumawat8740
NORMAL
2023-06-10T16:18:22.994619+00:00
2023-06-10T16:18:22.994666+00:00
1,875
false
# Code\n```\nclass Solution {\npublic:\n bool isFascinating(int n) {\n string str = "";\n int a = n*2,b=n*3;\n str = to_string(n)+to_string(a)+to_string(b);\n vector<int> v(10,0);\n for(auto &i: str){\n v[i-\'0\']++;\n }\n for(int i = 0; i < 10; i++){\n if(i==0){\n if(v[i])return false;\n }else{\n if(v[i]!=1)return false;\n }\n }\n return true;\n }\n};\n```
5
1
['C++']
0
check-if-the-number-is-fascinating
✅ Explained - Simple and Clear Python3 Code✅
explained-simple-and-clear-python3-code-rqyz3
Intuition\nThe problem asks us to determine whether a given three-digit number is fascinating or not. To be fascinating, the number must meet certain conditions
moazmar
NORMAL
2023-06-10T16:04:19.298336+00:00
2023-06-10T16:04:19.298400+00:00
1,426
false
# Intuition\nThe problem asks us to determine whether a given three-digit number is fascinating or not. To be fascinating, the number must meet certain conditions after concatenating it with 2 * n and 3 * n. The conditions are that the resulting concatenated number should contain all digits from 1 to 9 exactly once and should not contain any zeros.\n\n\n# Approach\nTo solve the problem, we first concatenate the given number n with 2 * n and 3 * n. We convert these numbers to strings and concatenate them together. This gives us the concatenated string.\n\nNext, we check if the concatenated string contains any zeros. If it does, we immediately return false, as zeros are not allowed in the fascinating number.\n\nThen, we check if the length of the concatenated string is greater than 9. If it is, that means the concatenated string contains duplicate digits or additional digits beyond 1 to 9. In such a case, we return false.\n\nFinally, we iterate through the digits from 1 to 9 and check if each digit is present in the concatenated string. If any digit is missing, we return false. Otherwise, we return true, indicating that the number is fascinating.\n\n\n# Complexity\n- Time complexity:\nTime complexity: The time complexity of this approach is O(1) because the number of iterations and operations performed is constant, regardless of the input size. We are iterating through a fixed range (1 to 9) and performing a constant number of operations for each iteration.\n\n\n- Space complexity:\nSpace complexity: The space complexity is also O(1) because we are not using any additional data structures that grow with the input size. The space required is only for storing the concatenated string, which is of constant size since we are concatenating three fixed-size numbers.\n\n\n# Code\n```\nclass Solution:\n def isFascinating(self, n: int) -> bool:\n concatenated = str(n) + str(2 * n) + str(3 * n)\n\n if \'0\' in concatenated:\n return False\n if len(concatenated)>9:\n return False\n for i in range(1,10):\n if str(i) not in concatenated :\n return False\n return True\n```
5
1
['Python3']
3
check-if-the-number-is-fascinating
easy C++ solution
easy-c-solution-by-prashant_71200-oorj
Intuition\nThe problem requires checking whether a number is fascinating or not. A fascinating number is one that, when multiplied by 2 and 3, results in a conc
prashant_71200
NORMAL
2024-01-25T10:19:29.669533+00:00
2024-01-25T10:19:29.669564+00:00
93
false
# Intuition\nThe problem requires checking whether a number is fascinating or not. A fascinating number is one that, when multiplied by 2 and 3, results in a concatenated string of the original number, double the original number, and triple the original number containing all digits from 1 to 9 exactly once.\n\n# Approach\n\n1> convert the original number n, n * 2, and n * 3 to strings (s, s1, s2).\n\n2> Concatenate the three strings into a single string s3.\n\n3> Sort the characters in s3 in ascending order.\n\n4> If the length of s3 is less than 9, return false (as it cannot contain all digits from 1 to 9).\n\n5> Iterate through each character in the sorted string s3.\nCheck if the character at position i is equal to the expected character based on the loop variable i.\n\nIf any character is not equal, return false; otherwise, return true.\n\n# Complexity\n- Time complexity:\nO(n * log(n))\n\n- Space complexity:\no(n)\n\n# Code\n```\n#include <iostream>\n#include <string>\n#include <algorithm>\n\nclass Solution {\npublic:\n bool isFascinating(int n) {\n string s = to_string(n);\n string s1 = to_string(n * 2);\n string s2 = to_string(n * 3);\n\n string s3 = s + s1 + s2;\n\n sort(s3.begin(), s3.end());\n\n if (s3.length() < 9) {\n return false;\n }\n\n for (int i = 0; i < s3.length(); i++) {\n if (s3[i] != \'1\' + i) {\n return false;\n }\n }\n return true;\n }\n};\n\n```
3
0
['C++']
0
check-if-the-number-is-fascinating
[JAVA] 100% faster solution
java-100-faster-solution-by-jugantar2020-ckrw
\n\n# Complexity\n- Time complexity: O(log 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
Jugantar2020
NORMAL
2023-07-19T08:04:49.348697+00:00
2023-07-19T08:04:49.348719+00:00
341
false
\n\n# Complexity\n- Time complexity: O(log n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public boolean isFascinating(int n) {\n boolean[] fascinating = new boolean[10];\n int n2 = 2 * n;\n int n3 = 3 * n;\n while(n > 0) {\n fascinating[n % 10] = true;\n fascinating[n2 % 10] = true;\n fascinating[n3 % 10] = true;\n n /= 10;\n n2 /= 10;\n n3 /= 10;\n }\n for(int i = 1; i < 10; i ++)\n if(! fascinating[i]) return false;\n return true;\n }\n}\n```\n# PLEASE UPVOTE IF IT WAS HELPFULL
3
0
['Array', 'Hash Table', 'Math', 'Java']
2
check-if-the-number-is-fascinating
Java Solution || Using For Loop
java-solution-using-for-loop-by-ankur_ch-9qc1
Intuition\n Describe your first thoughts on how to solve this problem. \nWe are given a number n, we need to check whether every digit from 1 to 9 is present in
Ankur_Chhillar
NORMAL
2023-07-12T14:41:18.036875+00:00
2023-07-12T14:46:42.708062+00:00
186
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe are given a number n, we need to check whether every digit from 1 to 9 is present in the number which is formed connecting n + 2 * n + 3 * n.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nIn the code we have made a string s, in which we have stored the number n, 2 * n and 3 * n in string format. We then have created a array of size 9 containing all elements equal to 1. We then ran a for loop till the length of string and checking the value of element at the index (s.charAt(i) - \'0\') - 1 if it is equal to 1 then changing it to zero and if already equal to 0 then returning false which means a number is repeated in the string. And also checking that (s.charAt(i) - \'0\') - 1 should be greater than 0 because if less than 0 will give a error as there is no index -1 or less in the array.\n\n# Code\n```\nclass Solution {\n public boolean isFascinating(int n) {\n\n String s = String.valueOf(n) + String.valueOf(2*n) + String.valueOf(3*n);\n\n int[] arr = new int[9];\n Arrays.fill(arr,1);\n\n for(int i=0;i<s.length();i++){\n int j = s.charAt(i) - \'0\';\n if(j-1<0){\n return false;\n }\n if(arr[j-1] == 0){\n return false;\n }else{\n arr[j-1] = 0;\n }\n }\n\n for(int i=0;i<arr.length;i++){\n if(arr[i]!=0){\n return false;\n }\n }\n\n return true;\n\n }\n}\n```\n\n![oie_CksRiTNvbciG.jpg](https://assets.leetcode.com/users/images/96683108-fa6b-4899-825c-6216059f5ff0_1689172819.995048.jpeg)
3
0
['Java']
1
check-if-the-number-is-fascinating
Simple and Easy to understand CPP solution.
simple-and-easy-to-understand-cpp-soluti-wx1m
Intuition\nThe code checks if a given number n is fascinating or not by following a specific approach. It concatenates n, 2n, and 3n, sorts the resulting string
nidhi_jat
NORMAL
2023-06-11T16:17:53.168193+00:00
2023-06-11T16:17:53.168242+00:00
535
false
# Intuition\nThe code checks if a given number n is fascinating or not by following a specific approach. It concatenates n, 2n, and 3n, sorts the resulting string, and then checks for any repeated digits or zeros. If there are any repeated digits or zeros, the number is considered not fascinating.\n\n# Approach\n- Multiply the given number n by 2 and 3 to obtain n2 and n3, respectively.\n- Convert n, n2, and n3 to strings using the to_string function.\n- Concatenate the three strings (s, s2, and s3) to form a single string called ans.\n- **Sort the characters in the ans string in ascending order using the sort function**.\n- Iterate through each character in ans from the beginning to the second-to-last character.\n - If the current character is \'0\' or the same as the next character, return false as the fascinating property is violated.\n- If no violations are found during the iteration, return true, indicating that the number n is fascinating.\n\nIn summary, the code **concatenates the string** representations of n, 2n, and 3n, **sorts the resulting string**, and checks for any **repeated digits or zeros**. This approach efficiently determines whether a number is fascinating or not based on the defined properties\n\n# Complexity\n- Time complexity:\n**O(nlogn)**\n\n\n\n# Code\n```\nclass Solution {\npublic:\n bool isFascinating(int n) {\n\n int n2 = 2*n;\n int n3 = 3*n;\n\n string s = to_string(n);\n string s2 = to_string(n2);\n string s3 = to_string(n3);\n\n string ans = s+s2+s3;\n sort(ans.begin(), ans.end());\n for(int i=0; i<ans.length()-1;i++){\n if(ans[i] == \'0\' || ans[i] == ans[i+1]){\n return false;\n }\n }\n return true; \n }\n};\n```
3
1
['String', 'Sorting', 'C++']
0
check-if-the-number-is-fascinating
[C++/Java] Bitwise Operations for Efficient Digit Tracking
cjava-bitwise-operations-for-efficient-d-mbs8
We the process by concatenating n, 2*n, and 3*n. Following this, it verifies that the concatenated string\'s length is strictly 9. If not, it directly returns f
xiangcan
NORMAL
2023-06-10T18:57:40.248184+00:00
2023-06-10T19:04:10.409887+00:00
401
false
We the process by concatenating `n`, `2*n`, and `3*n`. Following this, it verifies that the concatenated string\'s length is strictly `9`. If not, it directly returns `false`, as it\'s not possible for the number to incorporate all digits from `1` to `9` individually.\n\nSubsequently, a `state` variable is defined, initialized to `0`. This will be used to track each digit from `1` to`9` in the concatenated number. The function proceeds with a loop, examining each character in the string, and performing two checks:\n\n* If the character equals `0`, the function directly returns false. This is because a fascinating number should not include any zeroes.\n\n* We also check whether the same digit has been encountered previously using bitwise operations. If the current digit\'s corresponding bit in the `state` variable is already 1, it denotes that the digit has been encountered before, and the function immediately returns false.\n\nIn the event that neither of these conditions is met, the function adjusts the `state` variable, setting the current digit\'s corresponding bit to `1` using bitwise operations.\n\nC++:\n```\nclass Solution {\npublic:\n bool isFascinating(int n) {\n string s = to_string(n) + to_string(2 * n) + to_string(3 * n);\n if (s.length() != 9) return false;\n int state = 0;\n for (int i = 0; i < s.length(); i++) {\n int c = s[i] - \'0\';\n if (c == 0 || ((state >> c) & 1) == 1) return false;\n state |= (1 << c);\n }\n return true;\n }\n};\n```\n\nJava:\n```\nclass Solution {\n public boolean isFascinating(int n) {\n StringBuilder sb = new StringBuilder();\n sb.append(n).append(2 * n).append(3 * n);\n if (sb.length() != 9) return false;\n int state = 0;\n for (int i = 0; i < sb.length(); i++) {\n int c = sb.charAt(i) - \'0\';\n if (c == 0 || ((state >> c) & 1) == 1) return false;\n state |= (1 << c); \n }\n return true;\n }\n}\n```
3
0
['C', 'Java']
0
check-if-the-number-is-fascinating
Python Elegant & Short | Counter
python-elegant-short-counter-by-kyrylo-k-ukao
Complexity\n- Time complexity: O(n)\n- Space complexity: O(n)\n\n\n# Code\n\nclass Solution:\n DIGITS = Counter(\'123456789\')\n\n def isFascinating(self,
Kyrylo-Ktl
NORMAL
2023-06-10T17:55:11.654405+00:00
2023-06-10T17:55:11.654445+00:00
400
false
# Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(n)$$\n\n\n# Code\n```\nclass Solution:\n DIGITS = Counter(\'123456789\')\n\n def isFascinating(self, n: int) -> bool:\n return Counter(str(n) + str(2 * n) + str(3 * n)) == self.DIGITS\n\n```
3
0
['Hash Table', 'Python', 'Python3']
0
check-if-the-number-is-fascinating
Java easy solution
java-easy-solution-by-ydvaaman-owb2
\nclass Solution {\n public boolean isFascinating(int n) {\n String str = String.valueOf(n) + String.valueOf(2*n) + String.valueOf(3*n);\n Hash
ydvaaman
NORMAL
2023-06-10T17:15:12.412638+00:00
2023-06-10T17:15:12.412688+00:00
297
false
```\nclass Solution {\n public boolean isFascinating(int n) {\n String str = String.valueOf(n) + String.valueOf(2*n) + String.valueOf(3*n);\n HashSet<Integer> set = new HashSet<>();\n System.out.println(str);\n for(int i=0;i<str.length();i++){\n int ch = str.charAt(i)-\'0\'; \n if(ch == 0){ \n return false;\n }else{\n if(set.contains(ch)){\n return false;\n }else{\n set.add(ch);\n if(set.size()==9) return true;\n }\n }\n \n }\n return false;\n }\n}\n```
3
0
['Java']
3
check-if-the-number-is-fascinating
easy hai like to_string karo store karo check karo ki 1 to 9 hai by help of an arr aisa :D
easy-hai-like-to_string-karo-store-karo-iwgrv
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
yesyesem
NORMAL
2024-08-27T07:16:18.766387+00:00
2024-08-27T07:16:18.766455+00:00
76
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n bool isFascinating(int n) {\n \n int n2=2*n;\n int n3=3*n;\n string two=to_string(n2);\n string three=to_string(n3);\n\n string one=to_string(n);\n\n string s=one+two+three;\n int arr[10]={0};\n\n for(int i=0;i<s.size();i++)\n {\n arr[s[i]-\'0\']++;\n }\n\n for(int i=1;i<=9;i++)\n {\n if(arr[i]!=1)\n return false;\n }\n\n return true;\n }\n};\n```
2
0
['C++']
0
check-if-the-number-is-fascinating
Easy Brototype javascript solution
easy-brototype-javascript-solution-by-ah-8oyu
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
ahmedrithas48
NORMAL
2024-01-21T07:44:30.634147+00:00
2024-01-21T07:44:30.634177+00:00
66
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} n\n * @return {boolean}\n */\nvar isFascinating = function(n) {\n \n let n2 = 2*n;\n let n3 = 3*n;\n let result = \'\'+n+\'\'+n2+\'\'+\'\'+n3;\n if(result.length > 9){\n return false;\n }\n result = result.split(\'\').sort((a,b)=>a-b).join(\'\');\n\n for(let i=1 ; i<=9 ; i++){\n if(result[i-1] != i){\n return false;\n }\n }\n return true;\n};\n```
2
0
['JavaScript']
0
check-if-the-number-is-fascinating
easy to understand JS
easy-to-understand-js-by-javad_pk-66gv
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
javad_pk
NORMAL
2024-01-19T15:54:52.633243+00:00
2024-01-19T15:54:52.633269+00:00
151
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} n\n * @return {boolean}\n */\nvar isFascinating = function (n) {\n return \'123456789\' === (n.toString() + 2 * n + 3 * n).split(\'\').sort().join(\'\');\n};\n```
2
0
['JavaScript']
0
check-if-the-number-is-fascinating
Simplest solution ever in python beat 90%
simplest-solution-ever-in-python-beat-90-18mk
\n\n# Code\n\nclass Solution:\n def isFascinating(self, n: int) -> bool:\n num=str(n)+str(2*n)+str(3*n)\n for i in num:\n if num.cou
hrishikeshprasadc
NORMAL
2024-01-19T09:04:15.759510+00:00
2024-01-19T09:04:15.759546+00:00
90
false
\n\n# Code\n```\nclass Solution:\n def isFascinating(self, n: int) -> bool:\n num=str(n)+str(2*n)+str(3*n)\n for i in num:\n if num.count(i)>1 or \'0\' in num:\n return False\n return True\n \n```
2
0
['Python', 'Python3']
0
check-if-the-number-is-fascinating
Python code to check if the number is fascinating (TC&SC: O(log(n)))
python-code-to-check-if-the-number-is-fa-1jvm
\n# Complexity\n- Time complexity:\nO(log(n))\n\n- Space complexity:\nO(log(n))\n\n# Code\n\nclass Solution:\n def isFascinating(self, n: int) -> bool:\n
Nayandhika
NORMAL
2023-10-13T05:36:30.470428+00:00
2023-10-13T05:36:30.470459+00:00
41
false
\n# Complexity\n- Time complexity:\nO(log(n))\n\n- Space complexity:\nO(log(n))\n\n# Code\n```\nclass Solution:\n def isFascinating(self, n: int) -> bool:\n count = 0\n z = str(n)+str(2*n)+str(3*n)\n for i in range(1,10):\n if str(i) in z:\n count = count+1\n if count == len(z):\n return True\n```
2
0
['Python', 'Python3']
0
check-if-the-number-is-fascinating
Power of JavaScript using String Interpolation and Sorting
power-of-javascript-using-string-interpo-si3l
Complexity\n- Time complexity: O(Nlog(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
gouravojha4321
NORMAL
2023-07-01T19:30:41.948690+00:00
2023-07-01T19:30:41.948707+00:00
146
false
# Complexity\n- Time complexity: O(Nlog(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```\nfunction isFascinating(n: number): boolean {\n let allNumbers = \'123456789\'\n let fancyNumber = `${n}${n * 2}${n * 3}`.split("").sort().join("")\n if(allNumbers == fancyNumber){\n return true\n }\n return false\n};\n```
2
0
['Math', 'Sorting', 'TypeScript', 'JavaScript']
0
check-if-the-number-is-fascinating
C++ Easy To Understand Solution | Using Sets
c-easy-to-understand-solution-using-sets-pjb6
Approach\n Describe your approach to solving the problem. \n\n1. Converting the number to string is first step.\n2. Adding all the characters to a set as it con
shweta0098
NORMAL
2023-06-30T03:06:49.998939+00:00
2023-06-30T03:06:49.998964+00:00
32
false
# Approach\n<!-- Describe your approach to solving the problem. -->\n\n1. Converting the number to string is first step.\n2. Adding all the characters to a set as it contains only unique characters.\n3. The size of string and set must be exactly equal to 9 i.e. it contains all the digits from 1 to 9 exactly once.\n4. Last thing to check is that 0 is not present in the set.\n\n# Code\n```\nclass Solution {\npublic:\n bool isFascinating(int n) {\n string res = to_string(n);\n res += to_string(2*n);\n res += to_string(3*n);\n \n unordered_set<char> us(res.begin(),res.end());\n \n if(us.size() == 9 && res.size() == 9 && us.find(\'0\') == us.end()) \n return true;\n return false;\n }\n};\n```
2
0
['C++']
0
check-if-the-number-is-fascinating
C++ Easy Solution ✅✅
c-easy-solution-by-shubhamjain287-kxks
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-06-29T06:49:32.187548+00:00
2023-06-29T06:49:32.187575+00:00
246
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 bool isFascinating(int n) {\n string num1 = to_string(2*n);\n string num2 = to_string(3*n);\n string s = to_string(n);\n\n string ans = s + num1 + num2;\n unordered_map<char,int> mp;\n\n for(auto it : ans){\n mp[it]++;\n }\n\n for(auto it : mp){\n if(it.first==\'0\' || it.second>1) return false;\n }\n\n return mp.size()==9;\n }\n};\n```
2
0
['C++']
0
check-if-the-number-is-fascinating
Easy Python Solution
easy-python-solution-by-vistrit-wqpv
Code\n\nclass Solution:\n def isFascinating(self, n: int) -> bool:\n s=str(n)+str(n*2)+str(n*3)\n k="123456789"\n return set(s)==set(k)
vistrit
NORMAL
2023-06-27T18:28:23.039559+00:00
2023-06-27T18:28:23.039593+00:00
306
false
# Code\n```\nclass Solution:\n def isFascinating(self, n: int) -> bool:\n s=str(n)+str(n*2)+str(n*3)\n k="123456789"\n return set(s)==set(k) and len(s)==9\n```
2
0
['Python3']
0
check-if-the-number-is-fascinating
Beginners Approach
beginners-approach-by-bhaskarkumar07-53bw
\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#
bhaskarkumar07
NORMAL
2023-06-22T06:22:02.391433+00:00
2023-06-22T06:22:02.391464+00:00
429
false
\n# Complexity\n- Time complexity:O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public boolean isFascinating(int n) {\n String res= (n)+""+(n*2)+""+(n*3);\n \n\n \n\n if(res.contains("0")) return false;\n if(res.length()>9) return false;\n HashSet<Character> set= new HashSet<>();\n for(int i=0;i<res.length();i++){\n char c= res.charAt(i);\n set.add(c);\n }\n\n return set.size()==9 ? true: false; \n }\n}\n```
2
0
['Java']
0
check-if-the-number-is-fascinating
Simplest Python solution - 1,2 liner
simplest-python-solution-12-liner-by-try-z6g7
\n# Code\n\nclass Solution:\n def isFascinating(self, n: int) -> bool:\n s = str(n)+str(2*n)+str(3*n)\n return len(s) == 9 and max(Counter(s).v
tryingall
NORMAL
2023-06-10T16:43:57.614403+00:00
2023-06-10T16:43:57.614447+00:00
540
false
\n# Code\n```\nclass Solution:\n def isFascinating(self, n: int) -> bool:\n s = str(n)+str(2*n)+str(3*n)\n return len(s) == 9 and max(Counter(s).values()) == 1 and \'0\' not in Counter(s).keys()\n```
2
0
['Python3']
1
check-if-the-number-is-fascinating
[Python3] Solution with explanation
python3-solution-with-explanation-by-fro-6chn
We have to check if a resulting string contains unique digits except for zero. The first condition cuts off cases when there are more digits than needed: For ex
frolovdmn
NORMAL
2023-06-10T16:38:38.772440+00:00
2025-01-19T14:40:21.303610+00:00
469
false
We have to check if a resulting string contains unique digits except for zero. The first condition cuts off cases when there are more digits than needed: For example, n = 334, then we have '3346681002'. Length of this string is 10, but we should have a maximum of 9 digits. The second one is obvious, so as not to get zero when multiplied by 2. ```python [] class Solution: def isFascinating(self, n: int) -> bool: if n > 333: return False if n % 10 == 5 or n % 10 == 0: return False num = str(n) + str(2 * n) + str(3 * n) return len(set(num)) == len(num) and '0' not in num ```
2
0
['Python', 'Python3']
0
check-if-the-number-is-fascinating
C++ | O(1) | Full Explanation | Easy Solution with comments
c-o1-full-explanation-easy-solution-with-d5i1
\n# Approach\n- Convert the input number n into a string str.\n- Compute n2 = 2 * n and n3 = 3 * n.\n- Concatenate str with the strings representing n2 and n3.\
Jeetaksh
NORMAL
2023-06-10T16:04:28.008932+00:00
2023-06-10T16:06:18.704013+00:00
374
false
\n# Approach\n- Convert the input number n into a string str.\n- Compute n2 = 2 * n and n3 = 3 * n.\n- Concatenate str with the strings representing n2 and n3.\n- Initialize an array digitCount of size 10 to keep track of the count of each digit from 0 to 9.\n- Iterate through each character in string.\n-If the character is \'0\', return false as fascinating numbers should not contain any zeros.\n-Increment the count of the corresponding digit in digitCount.\n-Check if each digit from 1 to 9 appears exactly once in digitCount. If not, return false.\n-If all conditions are satisfied, return true as the number is fascinating.\n\n# Complexity\n- Time complexity: O(1)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n bool isFascinating(int n) {\n string str = to_string(n);\n int n2 = n * 2;\n int n3 = n * 3;\n str += to_string(n2);\n str += to_string(n3);\n\n vector<int> digitCount(10); // count of each digit from 0 to 9\n\n for (int i = 0; i < str.size(); i++) {\n if (str[i] == \'0\')\n return false; // If any digit is 0, return false\n digitCount[str[i] - \'0\']++;\n }\n\n for (int i = 1; i <= 9; i++) {\n if (digitCount[i] != 1)\n return false; // If any digit appears more than once or none, return false\n }\n\n return true; // All conditions satisfied, return true\n}\n};\n```\n**Please upvote if it helped. Happy Coding!**
2
0
['C++']
0
check-if-the-number-is-fascinating
C++ [Easy] 🔥
c-easy-by-varuntyagig-w1py
Code
varuntyagig
NORMAL
2025-02-23T07:29:47.272268+00:00
2025-02-23T07:29:47.272268+00:00
81
false
# Code ```cpp [] class Solution { public: bool isFascinating(int n) { string ans = to_string(n) + to_string(2 * n) + to_string(3 * n); for (int i = 0; i < ans.length(); ++i) { if (ans[i] == '0') { return false; } } unordered_set<char> digits; for (int i = 0; i < ans.length(); ++i) { digits.insert(ans[i]); } if ((digits.size() == ans.length()) && (ans.length() == 9)) { return 1; } return 0; } }; ```
1
0
['Math', 'Ordered Set', 'C++']
0
check-if-the-number-is-fascinating
O(N) set
on-set-by-piramidka1989-wy4e
IntuitionApproachComplexity Time complexity: O(N) Space complexity: Code
piramidka1989
NORMAL
2025-02-16T17:19:16.722291+00:00
2025-02-16T17:19:16.722291+00:00
46
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: O(N) - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] class Solution: def isFascinating(self, n: int) -> bool: string = str(n) + str(n*2) + str(n*3) s = set(['1', '2', '3', '4', '5', '6', '7', '8', '9']) s1 = set(string) return True if s1 == s and len(string) == 9 else False ```
1
0
['Python3']
0
check-if-the-number-is-fascinating
Легчайшая
legchaishaia-by-danisdeveloper-65ho
Code
DanisDeveloper
NORMAL
2025-01-07T12:29:56.968074+00:00
2025-01-07T12:29:56.968074+00:00
11
false
# Code ```kotlin [] class Solution { fun isFascinating(n: Int): Boolean { if(n > 333) return false; val str = n.toString() + (2 * n).toString() + (3 * n).toString() return str.all { it != '0' } && str.toSet().size == str.length } } ```
1
0
['Kotlin']
0
check-if-the-number-is-fascinating
Easy Solution | For and dictionary | O(1) Complexity
easy-solution-for-and-dictionary-o1-comp-5f2m
IntuitionThe problem revolves around the concept of a "fascinating number." A number n is fascinating if the concatenation of n, 2n, and 3n contains all the dig
arjunravi726
NORMAL
2025-01-03T04:48:52.713568+00:00
2025-01-03T04:48:52.713568+00:00
64
false
# Intuition The problem revolves around the concept of a "fascinating number." A number n is fascinating if the concatenation of n, 2n, and 3n contains all the digits from 1 to 9 exactly once. My initial thought was to validate this by generating the concatenated string and ensuring it forms a valid permutation of the digits 1-9. # Approach * Compute 2n and 3n. * Concatenate the string representations of n, 2n, and 3n. * Check the following conditions: * The concatenated string should contain all digits from 1 to 9 exactly once. * The digit '0' should not be present. * No digit should repeat. * Return True if all conditions are met; otherwise, return False. # Complexity - Time complexity: O(1) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity:O(1) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] class Solution: def isFascinating(self, n: int) -> bool: double = 2 * n triple = 3 * n nums = str(n) + str(double) + str(triple) print(nums) dct = {} for n in nums: n = int(n) if n == 0: return False if n in dct: return False else: dct[n] = 1 values = list(dct.keys()) print(values) if len(values) == 9: return True return False ```
1
0
['Python3']
0
check-if-the-number-is-fascinating
Efficient Java Solution
efficient-java-solution-by-abhivatsa1185-6czn
Intuition\n Describe your first thoughts on how to solve this problem. \nMy initial thought was to check if a number n is "fascinating" by verifying that the co
abhivatsa1185
NORMAL
2024-11-07T14:23:44.981471+00:00
2024-11-07T14:23:44.981498+00:00
171
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMy initial thought was to check if a number n is "fascinating" by verifying that the concatenation of n, 2\xD7n and 3 \xD7 \uD835\uDC5B contains exactly the digits 1 through 9 with no zeros or repetitions. If this combined number meets these conditions, then n is fascinating.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Compute Multiples: Calculate 2\xD7n and 3 \xD7 \uD835\uDC5B\n\n- Digit Extraction: Using three loops, I individually extract each digit from n, 2\xD7n and 3 \xD7 \uD835\uDC5B.\n\n- I use modulo and division to isolate each digit and check if it\'s zero or if it has already been seen.\n\n- If the digit is zero or already in the set, return false.\n\n- If it\u2019s a valid, unique digit, add it to a HashSet to keep track.\n\n- Final Check: After processing all digits, check if the HashSet contains exactly 9 digits, indicating we have every digit from 1 to 9 exactly once. If so, return true; otherwise, return false.\n\n- This approach efficiently checks each digit for uniqueness and excludes any invalid cases like zeros or duplicates.\n\n# Complexity\n- Time complexity: log(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```java []\nclass Solution {\n public boolean isFascinating(int n) {\n int a = 2*n;\n int b = 3*n;\n HashSet<Integer> hs = new HashSet<>();\n while(a != 0){\n int r = a % 10;\n if(r==0 || hs.contains(r)){\n return false;\n }\n hs.add(r);\n a/=10;\n }\n while(b != 0){\n int r = b % 10;\n if(r==0 || hs.contains(r)){\n return false;\n }\n hs.add(r);\n b/=10;\n }\n while(n != 0){\n int r = n % 10;\n if(r==0 || hs.contains(r)){\n return false;\n }\n hs.add(r);\n n/=10;\n }\n return hs.size() == 9;\n }\n}\n```
1
0
['Java']
0
check-if-the-number-is-fascinating
👨🏻‍💻EASY APPROACH || Python Easy CODE ✅✅
easy-approach-python-easy-code-by-kingz_-vozf
Code\npython3 []\nclass Solution:\n def isFascinating(self, n: int) -> bool:\n nStr = str(n) + str(2*n) + str(3*n)\n if len(nStr) != 9: \n
aryann_0101
NORMAL
2024-10-20T17:07:57.305159+00:00
2024-10-20T17:07:57.305194+00:00
16
false
# Code\n```python3 []\nclass Solution:\n def isFascinating(self, n: int) -> bool:\n nStr = str(n) + str(2*n) + str(3*n)\n if len(nStr) != 9: \n return False\n digits = set(nStr)\n return digits == set("123456789")\n```
1
0
['String', 'Python3']
0
check-if-the-number-is-fascinating
Easy Method, Less Code:)
easy-method-less-code-by-afnanpk-amin
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
AfnanPk
NORMAL
2024-07-03T09:29:33.301533+00:00
2024-07-03T09:29:33.301560+00:00
9
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {number} n\n * @return {boolean}\n */\nvar isFascinating = function (n) {\n val = String(n) + String(n * 2) + String(n * 3)\n if (val.length !== 9) return false\n val = val.split(\'\').sort()\n\n for (i = 1; i <= 9; i++) {\n if (val[i - 1] != i) return false\n }\n return true\n\n\n};\n```
1
0
['JavaScript']
0
check-if-the-number-is-fascinating
Easy Java Solution || HashMap
easy-java-solution-hashmap-by-ravikumar5-y2zi
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
ravikumar50
NORMAL
2024-06-21T19:20:18.237979+00:00
2024-06-21T19:20:18.238006+00:00
166
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public boolean isFascinating(int n) {\n int a = n*2;\n int b = n*3;\n HashSet<Integer> hp = new HashSet<>();\n while(a!=0){\n int r = a%10;\n if(hp.contains(r)) return false;\n hp.add(r);\n a=a/10;\n }\n\n while(b!=0){\n int r = b%10;\n if(hp.contains(r)) return false;\n hp.add(r);\n b = b/10;\n }\n\n while(n!=0){\n int r = n%10;\n if(hp.contains(r)) return false;\n hp.add(r);\n n=n/10;\n }\n\n System.out.println(hp);\n if(hp.contains(0) || hp.size()!=9) return false;\n return true;\n }\n\n}\n```
1
0
['Java']
0
check-if-the-number-is-fascinating
Simple java code 1 ms beats 96 % && 40 mb beats 78 %
simple-java-code-1-ms-beats-96-40-mb-bea-t94i
\n# Complexity\n-\n\n# Code\n\nclass Solution {\n public boolean isFascinating(int n) {\n int arr[]=new int[10];\n int temp=n;\n while(t
Arobh
NORMAL
2024-01-30T02:49:33.383417+00:00
2024-01-30T02:49:33.383445+00:00
16
false
\n# Complexity\n-\n![image.png](https://assets.leetcode.com/users/images/7250bc20-33eb-4a48-8c08-911ff4f39f24_1706582937.1476665.png)\n# Code\n```\nclass Solution {\n public boolean isFascinating(int n) {\n int arr[]=new int[10];\n int temp=n;\n while(temp>0){\n arr[temp%10]++;\n temp=temp/10;\n }\n temp=2*n;\n while(temp>0){\n arr[temp%10]++;\n temp=temp/10;\n }\n temp=3*n;\n while(temp>0){\n arr[temp%10]++;\n temp=temp/10;\n }\n if(arr[0]>0){\n return false;\n }\n for(int i=1;i<10;i++){\n if(arr[i]!=1){\n return false;\n }\n }\n return true;\n }\n}\n```
1
0
['Math', 'Java']
0
check-if-the-number-is-fascinating
Simple Solution
simple-solution-by-adhilalikappil-qj4l
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
adhilalikappil
NORMAL
2024-01-19T05:07:53.289471+00:00
2024-01-19T05:07:53.289506+00:00
104
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} n\n * @return {boolean}\n */\nvar isFascinating = function(n) {\n let arr = \'\'+n+(n*2)+(n*3)\n let check = new Set(arr)\n return (arr.length===check.size) && !check.has(\'0\')\n \n};\n```
1
0
['JavaScript']
0
check-if-the-number-is-fascinating
python3 code
python3-code-by-manasaanand1711-itwe
Intuition\nThe method multiplies the input integer n by 2 and 3, and creates a list l with the string representation of n, 2n, and 3n. It then concatenates the
manasaanand1711
NORMAL
2023-10-13T05:36:55.115663+00:00
2023-10-13T05:36:55.115688+00:00
23
false
# Intuition\nThe method multiplies the input integer n by 2 and 3, and creates a list l with the string representation of n, 2n, and 3n. It then concatenates the strings in l to form a single string m.\n\nThe method then iterates through each character in m, appends it to a list q, and converts each character in q to an integer, which is stored in a list s.\n\nFinally, the method checks whether each digit from 1 to 9 appears exactly once in s, and whether the digit 0 does not appear in s. If both conditions are true, the method returns True, otherwise it returns False.\n\n# Approach\nThe code takes an input integer n and checks if the concatenation of n, 2n, and 3n contains all digits from 1 to 9 exactly once and does not contain the digit 0.\n\nTo achieve this, the code multiplies n by 2 and 3 and stores the results in x and y. It then creates a list l with the string representations of n, x, and y, and concatenates them into a single string m.\n\nNext, the code iterates through each character in m, appends it to a list q, and converts each character in q to an integer, which is stored in a list s.\n\nFinally, the code checks whether each digit from 1 to 9 appears exactly once in s, and whether the digit 0 does not appear in s. If both conditions are true, the code returns True, otherwise it returns False.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n def isFascinating(self, n: int) -> bool:\n x = 2*n \n y = 3*n \n l=[] \n q=[]\n l.append(str(n))\n l.append(str(x))\n l.append(str(y))\n m = \'\'.join(l)\n for i in m:\n q.append(i)\n s = [int(i) for i in q]\n if all(s.count(i)==1 for i in range(1,10)):\n if all(i!=\'0\' for i in s):\n return True\n else:\n return False\n\n```
1
0
['Python3']
0
check-if-the-number-is-fascinating
Java Set Solution
java-set-solution-by-bema3420-ycjx
\n# Code\n\nclass Solution {\n public boolean isFascinating(int n) {\n String strs = Integer.toString(n) + Integer.toString(2 * n) + Integer.toString(
bema3420
NORMAL
2023-09-16T03:59:41.372028+00:00
2023-09-16T03:59:41.372056+00:00
4
false
\n# Code\n```\nclass Solution {\n public boolean isFascinating(int n) {\n String strs = Integer.toString(n) + Integer.toString(2 * n) + Integer.toString(3 * n);\n Set<Integer> set = new HashSet<>();\n\n for (int i = 0; i < strs.length(); i++) {\n int curr = strs.charAt(i) - \'0\';\n if (curr == 0) {\n return false;\n }\n if (set.contains(curr)) {\n return false;\n }\n set.add(curr);\n }\n\n return set.size() == 9;\n }\n}\n```
1
0
['Java']
0
check-if-the-number-is-fascinating
Using sprintf() method🧵|| functions mania😵‍💫 || but Simple!
using-sprintf-method-functions-mania-but-86jy
Intuition\nAt the starting of solve this problem, i thought i can done this problem without using any built-in functions.But it is more tideous, so that i used
Bothi_3
NORMAL
2023-08-07T09:28:33.263349+00:00
2023-08-07T09:28:33.263381+00:00
60
false
# Intuition\nAt the starting of solve this problem, i thought i can done this problem without using any built-in functions.But it is more tideous, so that i used the functions like sprintf(),strcat(),atoi().\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Calculate `two_N` and `three_N`: The function calculates `two_N` and `three_N`, which are the results of multiplying the input `n` by 2 and 3, respectively.\n\n2. Convert integers to strings: Three character arrays `s0`, `s1`, and `s2` are used to store the string representations of `n`, `two_N`, and `three_N`, respectively. The `sprintf()` function is used to convert the integers into strings and store them in these arrays.\n\n3. Concatenate the strings: The strings `s1` and `s2` are concatenated using the `strcat()` function, resulting in a new string that contains the digits of `two_N` followed by the digits of `three_N`.\n\n4. Concatenate again and convert back to integer: The string `s1` (with digits of `two_N` and `three_N`) is then concatenated with the string `s0` (with digits of `n`). The resulting string is converted back to an integer using the `atoi()` function, and the result is stored in the `res` variable.\n\n5. Check for fascinating property: The code then iterates over digits from 1 to 9 (using the variable `i`). For each digit, it checks if it appears exactly once in the `res` integer. If it finds a digit that is not present or appears more than once, it returns `false`, indicating that `n` is not a fascinating number.\n\n6. Count fascinating digits: The code counts the number of digits that appear exactly once in `res` for all digits from 1 to 9. If all digits appear exactly once, the variable `num` is incremented.\n\n7. Check the final result: Finally, the code checks if `num` is equal to 9 (since there are 9 digits from 1 to 9). If `num` is equal to 9, it means all digits from 1 to 9 appear exactly once in the `res` integer, and the function returns `true`, indicating that `n` is a fascinating number. Otherwise, it returns `false`.\n\n\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(log 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![images.jpg](https://assets.leetcode.com/users/images/adda409b-7631-401b-9ad3-8df3031280f3_1691399743.314916.jpeg)\n\n# Code\n```\nbool isFascinating(int n){\nint two_N=2*n;\nint three_N=3*n;\nchar s0[100],s1[50],s2[50];\nsprintf(s0,"%d",n); // sprintf() is used to assign number to char array[]\nsprintf(s1,"%d",two_N);\nsprintf(s2,"%d",three_N);\nstrcat(s1,s2); // concatenate the strings\nstrcat(s0,s1);\nint res=atoi(s0); // atoi() is used to convert the string respresentation to integer \nint rem,temp,num=0,count=0;\nfor(int i=1;i<=9;i++)\n{\nint temp=res;\nwhile(temp>0)\n{\n rem=temp%10;\n if(rem==0) return false;\n else\n {\n if(rem==i) count++;\n }\n temp/=10;\n}\nif(count==1) num++;\ncount=0;\n}\nif(num==9) return true;\nelse return false;\n}\n\n```
1
0
['Math', 'String', 'C']
0
check-if-the-number-is-fascinating
Worst Java Solution
worst-java-solution-by-timode-6-fcmt
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
timode-6
NORMAL
2023-07-27T12:51:55.278676+00:00
2023-07-27T12:51:55.278694+00:00
27
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(1)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public boolean isFascinating(int n) {\n return n == 192 || n == 219 || n == 273 || n == 327;\n }\n}\n```\n![\u043F\u04352.jpg](https://assets.leetcode.com/users/images/5ecc1b5b-8a66-4bef-a27b-d8884c51a9e2_1690462296.7836988.jpeg)\n
1
0
['Number Theory', 'Java']
0
check-if-the-number-is-fascinating
Check if The Number is Fascinating : - Time complexity: O(log(n)), Space complexity: O(1)
check-if-the-number-is-fascinating-time-v5s0l
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nCreate a HashMap to keep track of the digits encountered during the check
_Its_jUMBO_
NORMAL
2023-07-17T21:19:10.714597+00:00
2023-07-17T21:19:10.714641+00:00
452
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nCreate a HashMap to keep track of the digits encountered during the checks.\n\nCompute 2*n and 3*n.\n\nIterate through the digits of n, 2*n, and 3*n, one by one.\n\nFor each digit encountered, check if it is already present in the HashMap or if it is equal to 0. If so, return false as it violates the fascinating condition.\n\nIf the digit is not already in the HashMap, add it to the HashMap.\n\nRepeat steps 3 to 5 for all digits in n, 2*n, and 3*n.\n\nIf all digits are unique and not equal to 0 in the HashMap, return true, indicating that the number is fascinating.\n\nIf any violation is found during the checks, return false.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(log(n))\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public boolean isFascinating(int n) {\n HashMap<Integer, Integer> m = new HashMap<>();\n\n int a = 2*n;\n int b = 3*n;\n while(n >0){\n int r = n%10;\n if(m.containsKey(r) || r == 0){\n return false;\n }\n else{\n m.put(r,1);\n }\n n = n/10;\n\n }\n while(a >0){\n int r = a%10;\n if(m.containsKey(r) || r==0){\n return false;\n }\n else{\n m.put(r,1);\n } \n a = a/10;\n\n }\n while(b >0){\n int r = b%10;\n if(m.containsKey(r) || r==0){\n return false;\n }\n else{\n m.put(r,1);\n } \n b = b/10;\n }\n return true;\n \n }\n}\n```
1
0
['Java']
1
check-if-the-number-is-fascinating
C++ | Brute Force | Beginner Friendly | Sorting | O(n log n)
c-brute-force-beginner-friendly-sorting-2y13b
Intuition\nThe code checks if a number n is fascinating or not. To determine this, it concatenates n, 2n, and 3n into a single string and sorts it. By iterating
IshanRakte
NORMAL
2023-07-13T12:15:16.651379+00:00
2023-07-13T12:15:16.651402+00:00
32
false
**Intuition**\nThe code checks if a number n is fascinating or not. To determine this, it concatenates n, 2*n, and 3*n into a single string and sorts it. By iterating through the sorted string, if any digit is \'0\' or there are repeated digits, the number is not fascinating. Otherwise, it is considered fascinating.\n\n**Time Complexity**\nThe time complexity of sorting an array of size n using a comparison-based sorting algorithm, such as the one used in the std::sort function, is generally O(n log n). The for loop iterates through the sorted string, which also takes O(n) time.\n\n**Code**\n```\nclass Solution {\npublic:\n bool isFascinating(int n) {\n // Create variables for 2*n and 3*n.\n int n2 = 2 * n;\n int n3 = 3 * n;\n \n // Convert the numbers to strings.\n string s = to_string(n);\n string s2 = to_string(n2);\n string s3 = to_string(n3);\n\n // Concatenate the strings.\n string ans = s + s2 + s3;\n \n // Sort the concatenated string.\n sort(ans.begin(), ans.end());\n \n // Check for \'0\' or repeated digits.\n for (int i = 0; i < ans.size() - 1; i++) {\n if (ans[i] == \'0\' || ans[i] == ans[i + 1]) {\n return false;\n }\n }\n \n return true; \n }\n};\n```\n\nPlease consider upvoting and leaving any comments or feedback if you found the solution helpful. Thank you! \uD83D\uDE0A
1
0
['C', 'Sorting', 'C++']
1
check-if-the-number-is-fascinating
Easiest approach in Python3
easiest-approach-in-python3-by-pranjul_2-ua2b
\n\n\n# Code\n\nclass Solution:\n def isFascinating(self, n: int) -> bool:\n m=str(n*2)\n o=str(n*3)\n p=str(n)+m+o\n k=0\n
pranjul_23
NORMAL
2023-07-12T17:31:58.808018+00:00
2023-07-12T17:31:58.808039+00:00
7
false
\n\n\n# Code\n```\nclass Solution:\n def isFascinating(self, n: int) -> bool:\n m=str(n*2)\n o=str(n*3)\n p=str(n)+m+o\n k=0\n L=[\'1\',\'2\',\'3\',\'4\',\'5\',\'6\',\'7\',\'8\',\'9\']\n for i in range(9):\n if p[i] in L:\n k+=1\n L.remove(p[i])\n else:continue\n if k==9:\n return True\n else:\n return False\n```
1
0
['Python3']
0
check-if-the-number-is-fascinating
Java solution || Using Hashset
java-solution-using-hashset-by-anishapat-q836
\n# Approach\n1.Create a string(ans) which store the resultant string after concatenate.\n2.Create a Hashset which will store elements of string uniquely later.
anishapatil1248
NORMAL
2023-07-12T12:37:53.395373+00:00
2023-07-12T12:37:53.395402+00:00
372
false
\n# Approach\n1.Create a string(ans) which store the resultant string after concatenate.\n2.Create a Hashset which will store elements of string uniquely later.\n3.Now chech if ans contains "0" if yes return false. Also check if length of ans is greater than 9 if yes return false.\n4.Now iterate in ans and check if set already contains a element return false. Else add the element in the string.\n5.Now check if the size of hashset is 9 then return true. Else return false. \n\n# Code\n```\nimport java.util.*;\nclass Solution {\n public boolean isFascinating(int n) {\n String ans = String.valueOf(n) + String.valueOf(2*n) + String.valueOf(3*n); \n // int a = 2*n;\n // int b = 3*n;\n // String str = Integer.toString(n);\n // String str1 = Integer.toString(a);\n // String str2 = Integer.toString(b);\n // String ans = str+str1+str2;\n\n HashSet<Character> h = new HashSet<>();\n \n if(ans.contains("0")) return false;\n if(ans.length()>9) return false;\n for(int i=0; i<ans.length(); i++){\n char ch = ans.charAt(i);\n if(h.contains(ch)){\n return false;\n }else{\n h.add(ch);\n }\n }\n if(h.size()==9){\n return true;\n }\n return false;\n }\n}\n```
1
0
['Java']
0
check-if-the-number-is-fascinating
Count digits as we go
count-digits-as-we-go-by-fengolly-g5bv
Intuition\n Output should not have a 0\n Count digits as we make 2x and 3x of n, and look for dupes as we go\n\n# Approach\n Use an array as our map, much faste
fengolly
NORMAL
2023-07-08T19:40:17.791979+00:00
2023-07-08T19:40:17.792007+00:00
12
false
# Intuition\n* Output should not have a `0`\n* Count digits as we make 2x and 3x of n, and look for dupes as we go\n\n# Approach\n* Use an array as our map, much faster than a `map`\n* Look for `0`s\n* Count digits and look for dupes as we go\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\nfunc isFascinating(n int) bool {\n\tm := [9]bool{}\n\n\tfor i, curr := 1, n; i <= 3; i, curr = i+1, n*(i+1) {\n\t\tfor curr > 0 {\n\t\t\td := curr % 10\n\t\t\tif d == 0 {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tcurr /= 10\n\t\t\tif m[d-1] {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tm[d-1] = true\n\t\t}\n\t}\n\treturn true\n}\n```\n\n##### Using an array vs map to look for dupes:\n\n```\nBenchmark_isFascinatingMap\nBenchmark_isFascinatingMap-8 \t 3680568\t 297.1 ns/op\nBenchmark_isFascinating\nBenchmark_isFascinating-8 \t57233817\t 21.02 ns/op\n```
1
0
['Go']
0
check-if-the-number-is-fascinating
Check if The Number is Fascinating 👨🏻‍💻👨🏻‍💻 || Java solution code 💻💻...
check-if-the-number-is-fascinating-java-fjgpe
Code\n\nclass Solution {\n public boolean isFascinating(int n) {\n int a = n*2;\n int b = n*3;\n String s = n+""+a+""+b;\n\n if(s
Jayakumar__S
NORMAL
2023-07-08T18:13:46.118339+00:00
2023-07-08T18:13:46.118359+00:00
410
false
# Code\n```\nclass Solution {\n public boolean isFascinating(int n) {\n int a = n*2;\n int b = n*3;\n String s = n+""+a+""+b;\n\n if(s.length() < 8){\n return false;\n }\n for(int i=0; i<s.length(); i++){\n if(s.charAt(i) == \'0\'){\n return false;\n }\n for(int j= i+1; j<s.length(); j++){\n if(s.charAt(i) == s.charAt(j) ){\n return false;\n }\n }\n }\n return true;\n }\n}\n```
1
0
['Java']
0
check-if-the-number-is-fascinating
Beats 100% C++
beats-100-c-by-antony_ft-of9v
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
antony_ft
NORMAL
2023-07-07T12:28:24.999579+00:00
2023-07-07T12:28:24.999603+00:00
10
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 bool isFascinating(int n) {\n string str = "";\n int a = n*2,b=n*3;\n str = to_string(n)+to_string(a)+to_string(b);\n vector<int> v(10,0);\n for(auto &i: str){\n v[i-\'0\']++;\n }\n for(int i = 0; i < 10; i++){\n if(i==0){\n if(v[i])return false;\n }else{\n if(v[i]!=1)return false;\n }\n }\n return true;\n }\n};\n```
1
0
['C++']
0
check-if-the-number-is-fascinating
Beats 100% C++
beats-100-c-by-antony_ft-00pt
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
antony_ft
NORMAL
2023-07-07T12:28:11.850091+00:00
2023-07-07T12:28:11.850115+00:00
8
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n bool isFascinating(int n) {\n string str = "";\n int a = n*2,b=n*3;\n str = to_string(n)+to_string(a)+to_string(b);\n vector<int> v(10,0);\n for(auto &i: str){\n v[i-\'0\']++;\n }\n for(int i = 0; i < 10; i++){\n if(i==0){\n if(v[i])return false;\n }else{\n if(v[i]!=1)return false;\n }\n }\n return true;\n }\n};\n```
1
0
['C++']
0
check-if-the-number-is-fascinating
✅✅Easy Solution Using Set ✅✅
easy-solution-using-set-by-vinit250000-ycn2
\n\n void check(int n,string& temp)\n {\n while(n!=0)\n {\n temp.push_back((n%10)+\'0\');\n n=n/10;\n }\n }
vinit250000
NORMAL
2023-06-29T06:55:33.256178+00:00
2023-06-29T06:55:33.256208+00:00
74
false
```\n\n void check(int n,string& temp)\n {\n while(n!=0)\n {\n temp.push_back((n%10)+\'0\');\n n=n/10;\n }\n }\n \n bool isFascinating(int n) \n {\n string temp;\n set<int> s;\n int num=n;\n \n check(num,temp);\n \n int t1 = n*2;\n check(t1,temp);\n int t2 = 3*n;\n check(t2,temp);\n \n for(int i=0;i<temp.size();i++)\n {\n int x = temp[i]-\'0\';\n if(s.find(x)!=s.end() || x==0)\n {\n return false;\n }\n else\n {\n s.insert(x);\n }\n }\n return true; \n\n```
1
0
[]
0
check-if-the-number-is-fascinating
[C++] Simplest Solution using frequency.
c-simplest-solution-using-frequency-by-i-rwfr
Complexity\n- Time complexity:\nO(1)\n\n- Space complexity:\nO(1)\n\n# Code\n\nclass Solution {\npublic:\n bool isFascinating(int n) {\n\n if(n >= 334
Irfan_gouri
NORMAL
2023-06-24T12:39:26.523120+00:00
2023-06-24T12:39:26.523148+00:00
54
false
# Complexity\n- Time complexity:\nO(1)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\n bool isFascinating(int n) {\n\n if(n >= 334) return false;\n\n vector<int> freq(10, 0);\n\n string temp = to_string(n);\n n = 2 * n;\n temp += to_string(n);\n n = n/2 * 3;\n temp += to_string(n);\n\n cout << temp << endl;\n\n for(int i=0; i<temp.size(); i++) {\n freq[temp[i] - \'0\']++;\n if(temp[i] == \'0\' || freq[temp[i] - \'0\'] > 1) return false;\n }\n\n return true;\n \n }\n};\n```
1
0
['Hash Table', 'Math', 'C++']
0
check-if-the-number-is-fascinating
100% FAST Simple Solution
100-fast-simple-solution-by-bekki3-z44u
Intuition\nThere are few such number between 100-999\n\n# Code\n\nclass Solution {\npublic:\n bool isFascinating(int n) {\n if(n==192){\n r
bekki3
NORMAL
2023-06-20T13:44:15.796713+00:00
2023-06-20T13:44:15.796740+00:00
245
false
# Intuition\nThere are few such number between 100-999\n\n# Code\n```\nclass Solution {\npublic:\n bool isFascinating(int n) {\n if(n==192){\n return true;\n }\n else if(n==273){\n return true;\n }\n else if(n==327){\n return true; \n }\n else if(n==219){\n return true;\n }else{\n return false;\n }\n }\n};\n```
1
0
['Math', 'C++', 'Java', 'Python3', 'JavaScript']
0
check-if-the-number-is-fascinating
Python3 ✅✅✅ || easy and fast || 5 lines
python3-easy-and-fast-5-lines-by-blackho-uvyb
Code\n\nclass Solution:\n def isFascinating(self, n: int) -> bool:\n num = str(n)\n num += str(2 * n)\n num += str(3 * n)\n count
Little_Tiub
NORMAL
2023-06-19T04:27:29.969303+00:00
2023-06-19T04:27:29.969321+00:00
13
false
# Code\n```\nclass Solution:\n def isFascinating(self, n: int) -> bool:\n num = str(n)\n num += str(2 * n)\n num += str(3 * n)\n counts = [num.count(x) for x in num]\n return "0" not in num and counts.count(1) == len(counts)\n```\n![image.png](https://assets.leetcode.com/users/images/a7e473d2-17a6-446a-bef2-df5bd3ca82ba_1687148819.7501976.png)\n\n![image.png](https://assets.leetcode.com/users/images/e1619ae5-35a7-4b6c-bcb9-66b1716d4211_1687148841.0468395.png)\n
1
0
['Python3']
0
check-if-the-number-is-fascinating
Java Easy to Understand Solution
java-easy-to-understand-solution-by-brot-p2qp
\nclass Solution {\n public boolean isFascinating(int n) {\n if (Math.floor(Math.log(n) + 1) < 3)\n\t\t\t\t\treturn false; // false if the number is n
brothercode
NORMAL
2023-06-18T14:03:20.573821+00:00
2023-06-18T14:03:20.573844+00:00
68
false
```\nclass Solution {\n public boolean isFascinating(int n) {\n if (Math.floor(Math.log(n) + 1) < 3)\n\t\t\t\t\treturn false; // false if the number is not a 3 digit number\n String str = String.valueOf(n) + String.valueOf(2 * n) + String.valueOf(3 * n); // concatenate the results.\n char ch1[] = { \'1\', \'2\', \'3\', \'4\', \'5\', \'6\', \'7\', \'8\', \'9\' }; // construct the Character Map\n char ch2[] = str.toCharArray();\n Arrays.sort(ch2); // Sort the concatenated result\n return Arrays.equals(ch1, ch2); // Return true if both char arry matches else false.\n }\n}\n```
1
0
['Java']
0
check-if-the-number-is-fascinating
C# Linq OneLiner
c-linq-oneliner-by-7bnx-dirh
\n\npublic class Solution {\n public bool IsFascinating(int n)\n => $"{n}{n*2}{n*3}".OrderBy(x => x).SequenceEqual("123456789");\n}\n
7bnx
NORMAL
2023-06-17T20:53:43.570384+00:00
2023-06-17T20:53:43.570403+00:00
45
false
\n```\npublic class Solution {\n public bool IsFascinating(int n)\n => $"{n}{n*2}{n*3}".OrderBy(x => x).SequenceEqual("123456789");\n}\n```
1
0
['C#']
0
check-if-the-number-is-fascinating
JAVA | Simple solution | No String | 100% Faster
java-simple-solution-no-string-100-faste-kb8p
Complexity\n- Time complexity: O(log(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\
ilyastuit
NORMAL
2023-06-12T05:49:16.015407+00:00
2023-06-22T05:46:31.050764+00:00
735
false
# Complexity\n- Time complexity: $$O(log(n))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n\n public boolean isFascinating(int n) {\n boolean[] facinatingDigits = new boolean[10];\n int n2 = 2 * n;\n int n3 = 3 * n;\n while (n > 0) {\n facinatingDigits[n % 10] = true;\n facinatingDigits[n2 % 10] = true;\n facinatingDigits[n3 % 10] = true;\n n /= 10;\n n2 /= 10;\n n3 /= 10;\n }\n for (int i = 1; i < facinatingDigits.length; i++) {\n if (!facinatingDigits[i]) {\n return false;\n }\n }\n\n return true;\n }\n}\n```
1
0
['Math', 'Java']
2
check-if-the-number-is-fascinating
Super Easy C++ Solution
super-easy-c-solution-by-lotus18-dpj4
Code\n\nclass Solution \n{\npublic:\n bool isFascinating(int n) \n {\n int n2=2*n;\n int n3=3*n;\n string s=to_string(n)+to_string(n2
lotus18
NORMAL
2023-06-11T13:51:36.334974+00:00
2023-06-11T13:51:36.335016+00:00
111
false
# Code\n```\nclass Solution \n{\npublic:\n bool isFascinating(int n) \n {\n int n2=2*n;\n int n3=3*n;\n string s=to_string(n)+to_string(n2)+to_string(n3);\n set<char> st;\n for(auto ch: s) \n {\n if(ch==\'0\') return false;\n st.insert(ch);\n }\n return st.size()==9 && s.size()==9;\n }\n};\n```
1
0
['C++']
0
check-if-the-number-is-fascinating
Video Solution || Accepted✅✅
video-solution-accepted-by-sanjeev_pu-3ih2
Intuition\n Describe your first thoughts on how to solve this problem. \nsorting will be the hero\n\n# Approach\n Describe your approach to solving the problem.
Sanjeev_PU
NORMAL
2023-06-10T21:14:18.460021+00:00
2023-06-10T21:14:18.460065+00:00
367
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nsorting will be the hero\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1) fimd the actual number after computation in string form\n2) sort the string\n3) check the duplicate or zero value \n\nclick to see the video solution\n[click me](https://youtu.be/-mx_Q4tdVRI)\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(nlogn)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n\n# Code\n```\nclass Solution {\npublic:\n bool isFascinating(int n) {\n int m = 2*n;\n int p = 3*n;\n string a = to_string(n);\n string b = to_string(m);\n string c = to_string(p);\n string ans = a+b+c;\n sort(ans.begin(), ans.end());\n bool flag = 0;\n int num = ans.size();\n for(int i=0;i<num-1;i++){\n if(ans[i]==\'0\'){\n flag = 1;\n break;\n }\n if(ans[i]==ans[i+ 1]){\n flag = 1;\n break;\n }\n }\n if(flag == 1){\n return false;\n }\n else{\n return true;\n }\n \n \n \n \n }\n};\n```
1
0
['C++']
0
check-if-the-number-is-fascinating
✅ Simple | Beginners friendly | C++ Solution 🚀
simple-beginners-friendly-c-solution-by-b9eyl
\nclass Solution {\npublic:\n bool isFascinating(int n) {\n \n string s1 = to_string(n);\n string s2 = to_string(2*n);\n string s
aryan1shrivastava
NORMAL
2023-06-10T20:18:30.408533+00:00
2023-06-10T20:18:30.408574+00:00
61
false
```\nclass Solution {\npublic:\n bool isFascinating(int n) {\n \n string s1 = to_string(n);\n string s2 = to_string(2*n);\n string s3 = to_string(3*n);\n \n string s = s1 + s2 + s3;\n \n unordered_map<char, int> mp;\n \n for(auto c: s){\n if(mp[c] == 1 || c == \'0\'){\n return false;\n }\n mp[c] =1;\n }\n return true;\n }\n};\n```
1
0
['String', 'C']
1
check-if-the-number-is-fascinating
java easy solution for beginner
java-easy-solution-for-beginner-by-jatin-639v
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
Jatin_mohan_gupta
NORMAL
2023-06-10T17:45:00.925065+00:00
2023-06-10T17:45:00.925110+00:00
64
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public boolean isFascinating(int n) {\n int a = 2 * n;\n int b = 3 * n;\n String s ="";\n s=s+a+b+n;\n long arr[] = new long[10];\n for(int i = 0;i<s.length();i++){\n arr[s.charAt(i)-\'0\']++;\n\n }\n int count = 0;\n if(arr[0] >= 1){\n return false;\n }\n for(int i =1;i<arr.length;i++){\n if(arr[i] == 0){\n count++;\n }\n if(arr[i] > 1){\n return false;\n }\n }\n if(count > 0)\n return false;\n return true;\n \n \n \n \n }\n}\n```
1
0
['Java']
0