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
cracking-the-safe
c++ | easy | short
c-easy-short-by-venomhighs7-vsbg
\n\n# Code\n\nclass Solution {\npublic:\n unordered_set<string> hash;\n string ans;\n int k;\n \n void dfs(string u) {\n for (int i = 0; i
venomhighs7
NORMAL
2022-11-01T03:50:37.501495+00:00
2022-11-01T03:50:37.501529+00:00
767
false
\n\n# Code\n```\nclass Solution {\npublic:\n unordered_set<string> hash;\n string ans;\n int k;\n \n void dfs(string u) {\n for (int i = 0; i < k; i++) {\n auto e = u + to_string(i);\n if (!hash.count(e)) {\n hash.insert(e);\n dfs(e.substr(1));\n ans += to_string(i);\n }\n }\n }\n \n string crackSafe(int n, int _k) {\n k = _k;\n string start(n - 1, \'0\');\n dfs(start);\n return ans + start;\n }\n};\n```
4
1
['C++']
0
cracking-the-safe
C++ | Backtracking | Easy
c-backtracking-easy-by-vaibhavshekhawat-ebrf
```\nclass Solution {\npublic:\n int total;\n unordered_set st;\n bool func(int i,int k,int n,string& s){\n if(i==total) return 1;\n \n
vaibhavshekhawat
NORMAL
2022-07-18T08:27:52.295359+00:00
2022-07-18T08:32:36.253123+00:00
758
false
```\nclass Solution {\npublic:\n int total;\n unordered_set<string> st;\n bool func(int i,int k,int n,string& s){\n if(i==total) return 1;\n \n for(int j=0;j<k;j++){\n s.push_back(j+\'0\');\n \n if(s.size()>=n){\n string a = s.substr(s.size()-n);\n if(st.find(a)==st.end()){\n st.insert(a);\n if(func(i+1,k,n,s)) return 1;\n st.erase(a);\n }\n }\n else if(func(i,k,n,s)) return 1;\n \n s.pop_back();\n }\n \n return 0;\n }\n string crackSafe(int n, int k) {\n total = pow(k,n);\n string s;\n func(0,k,n,s);\n return s;\n }\n};\n\n
4
0
['Backtracking', 'C']
0
cracking-the-safe
Python DFS Intuitive Explanation
python-dfs-intuitive-explanation-by-_dee-i7z0
I spent hours on this problem getting stuck because I couldn\'t find a clear and intuitive explanation.\n\nThis video provides an awesome intuition: https://www
_deep_
NORMAL
2022-07-08T01:41:54.187593+00:00
2022-07-08T01:53:58.220973+00:00
397
false
I spent hours on this problem getting stuck because I couldn\'t find a clear and intuitive explanation.\n\nThis video provides an awesome intuition: https://www.youtube.com/watch?v=iPLQgXUiU14\n\nThe first half of this video is helpful and also goes through some examples: https://www.youtube.com/watch?v=VZvU1_oPjg0\n\nAfter reading the most voted solutions in this forum and watching those two videos, I went back to my intuition. We can represent every single sequence of length n from alphabet k as nodes in a graph. A directed edge from node a to node b indicates that the sequence at node b can be formed by taking the last n-1 digits of a and appending a digit to it.\n\nEach time we visit a node, we transition to the next sequence w/ the smallest number of changes possible (1 digit change), and we can append that different digit to a string we build. How do we know the resulting string meets the criteria? 1. We\'ve visited every node, so it will contain all subsequences and 2. Each time we visit a node, we\'re only changing 1 digit so intuitively that will result in the smallest resulting string.\n\nWith this understanding, I just implemented DFS to see what sort of solution came out of it:\n\n```\n# THIS IS WRONG AND I\'M SHARING IT BECAUSE IT HELPED ME UNDERSTAND HOW TO GET TO THE CORRECT SOLUTION\nclass Solution:\n def crackSafe(self, n: int, k: int) -> str:\n res = "".join(["0"] * n)\n\n visited = set([res])\n\n def dfs(s):\n nonlocal visited, res\n\n # handle beginning where res already starts out as a sequence of 0s of length n\n if s != "".join(["0"] * n):\n res = f"{res}{s[-1]}"\n\n for i in range(k):\n if f"{s[1:]}{i}" not in visited:\n visited.add(f"{s[1:]}{i}")\n dfs(f"{s[1:]}{i}")\n return\n\n dfs(res)\n\n return res\n\ns = Solution()\n# print(s.crackSafe(1, 2))\nprint(s.crackSafe(2, 2))\n```\n\n![image](https://assets.leetcode.com/users/images/53ec455b-0a1d-4a58-91bd-bb7c25dc1ca1_1657244348.9943395.png)\n\nMy solution is wrong and produces 00101, when instead we want 00110. Why is it wrong? The sequence 00 \u2192 01 \u2192 10 \u2192 11 doesn\u2019t visit each node exactly once (respecting the direction of the edges). For example, 10 \u2192 11 is not valid, it actually goes from 10 back to 01 to 11.\n\nTherefore, my implementation misses accounting for the fact that not all paths will visit every single node in the graph, and so we must backtrack when this happens. After hitting 10, it should backtrack to 01 by popping off 10. How does it know to backtrack? The sequence 00 \u2192 01 \u2192 10 does not allow any other unvisited nodes to be traversed, and only 3 of the 4 total nodes have been traversed. Thus we know this isn\u2019t the path we\u2019re looking for.\n\nWhen using DFS, paths can lead to dead ends where the path doesn\'t visit every single node in the graph. When reaching a dead end, you must backtrack and explore the other routes.\n\nIf we\u2019re at a dead end, but the number of visited nodes is less than k^n, then this path has failed and we must back track.\n\nHere\'s my summary:\n1. We can represent all sequences of length n of alphabet [0, k-1] as nodes in a graph. A directed edge from node a to node b indicates that the sequence at node b can be formed by taking the last n-1 digits of node a and appending the last digit in node b. There are k^n such nodes in the graph, since there are k^n such subsequences of length n from an alphabet k.\n2. We want to find a path that visits all the nodes in this graph exactly once. We can form a resulting string by appending the last character in each new node each time we travel along an edge. How do we know this string is what we\u2019re looking for? It will contain all k^n possible sequences since it visits all nodes. How do we know it\u2019s the shortest? It transitions from each node to the next node by changing only one character.\n3. To find such a path, perform DFS. Note that not all traversals will lead to a path that visits all nodes. Some traversals will be dead ends.\n4. How do we know if we\u2019ve reached a dead end? When there are no more nodes to travel to from the current node, and the amount of nodes we\u2019ve visited in this path does not equal k^n. How do we know if we\u2019ve succeeded? When the number of nodes we\u2019ve visited equals k^n.\n5. When we reach a dead end of a path that doesn\u2019t visit every node, we must backtrack and \u201Cundo\u201D the appending of nodes to the result string as well as appending of nodes to our container of visited nodes.\n6. When we\u2019ve visited all k^n nodes, we can terminate DFS and return the string that we\u2019ve build so far.\n\nFinally, a correct solution:\n\n```\nclass Solution:\n def crackSafe(self, n: int, k: int) -> str:\n res = "".join(["0"] * n)\n\n visited = set([res])\n\n def dfs(s):\n nonlocal visited, res\n\n # handle beginning where res already starts out as a sequence of 0s of length n\n if s != "".join(["0"] * n):\n res = f"{res}{s[-1]}"\n\n if len(visited) == k**n:\n # we\'ve visited every node, so res is the minimum length sequence\n return True\n\n for i in range(k):\n next_node = f"{s[1:]}{i}"\n if next_node not in visited:\n visited.add(next_node)\n if dfs(next_node):\n return True\n\n # the path we just did DFS on is not a path that visits every node, so backtrack\n visited.remove(next_node)\n res = res[:-1]\n\n return False\n\n dfs(res)\n\n return res\n```
4
0
[]
0
cracking-the-safe
Solution
solution-by-deleted_user-qb58
C++ []\nclass Solution {\npublic:\n using VT = pair<vector<string>,unordered_map<string,int>>;\n VT gNodes(int n, int k) {\n if (n==1) return VT({"
deleted_user
NORMAL
2023-04-25T08:16:59.313553+00:00
2023-04-25T08:29:27.130942+00:00
1,311
false
```C++ []\nclass Solution {\npublic:\n using VT = pair<vector<string>,unordered_map<string,int>>;\n VT gNodes(int n, int k) {\n if (n==1) return VT({""},{{"",0}});\n VT ns;\n auto prev = gNodes(n-1,k).first;\n for (auto s: prev) {\n s += " ";\n for (int i=0; i<k; ++i) {\n s.back() = \'0\'+i;\n ns.second[s] = ns.first.size();\n ns.first.push_back(s);\n }\n }\n return ns;\n }\n string crackSafe(int n, int k) {\n if (n<2) return string("0123456789").substr(0,k);\n auto [ns,hn] = gNodes(n,k);\n auto N = ns.size();\n vector<pair<int,int>> arcs;\n for (auto [s,x]: hn) {\n auto t = s.substr(1,-1)+" "; \n for (int i=0; i<k; ++i) {\n t.back() = \'0\'+i;\n arcs.emplace_back(x,hn[t]);\n }\n }\n vector<vector<int>> unused(N,[k](){vector<int> t(k); iota(t.begin(),t.end(),0); return t;}());\n string code;\n int ss = 0;\n while (ss>=0) {\n auto cm(0);\n code += ns[ss];\n bool cont(true);\n while (cont) {\n auto nx = \'0\'+unused[ss].back();\n unused[ss].pop_back();\n code += nx;\n ss = hn[code.substr(code.length()-n+1,n-1)];\n cont = !unused[ss].empty();\n }\n ss = -1;\n }\n return code;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def crackSafe(self, n: int, k: int) -> str:\n if n == 1:\n return \'\'.join([str(i) for i in range(k)])\n if k == 1:\n return \'0\' * n\n suffix_map = {}\n all_combinations = [\'0\']*(n-1)\n for _ in range(k**n):\n suffix = \'\'.join(all_combinations[1-n:])\n suffix_map[suffix] = suffix_map.get(suffix, k) - 1\n all_combinations.append(str(suffix_map[suffix]))\n return \'\'.join(all_combinations)\n```\n\n```Java []\nclass Solution {\n public String crackSafe(int n, int k) {\n if(n==1){\n StringBuilder sb = new StringBuilder();\n for(int i = 0; i < k; i++){\n sb.append(i);\n }\n return sb.toString();\n }\n int[] biggest_edge = new int[(int) Math.pow(k, n - 1)];\n Arrays.fill(biggest_edge, k - 1);\n StringBuilder sb = new StringBuilder("0".repeat(n - 1));\n int current = 0;\n while (biggest_edge[current] != -1) {\n int edge = biggest_edge[current]--;\n sb.append(edge);\n current = (current * k) % (int) Math.pow(k, n-1) + edge;\n }\n return sb.toString();\n }\n public static String mergeTwoStringShortest(String left, String right) {\n int noOverlap =longestHeadTailIntersection(left,right);\n return left.substring(0, left.length()) + right.substring(noOverlap, right.length());\n }\n private static int longestHeadTailIntersection( String T, String P) {\n int n = T.length(), m = P.length();\n int[] pi = computePrefixFunction(P);\n int q = 0;\n for (int i = 0; i < n; i++) {\n while (q > 0 && P.charAt(q) != T.charAt(i)) {\n q = pi[q];\n }\n if (P.charAt(q) == T.charAt(i)) {\n q++;\n }\n if (q == m) {\n q = pi[q];\n }\n }\n return q;\n }\n private static int[] computePrefixFunction( String P) {\n int m = P.length();\n int[] pi = new int[m + 1];\n pi[1] = 0;\n for (int q = 1, k = 0; q < m; q++) {\n while (k > 0 && P.charAt(k) != P.charAt(q)) {\n k = pi[k];\n }\n if (P.charAt(k) == P.charAt(q)) {\n k++;\n }\n pi[q + 1] = k;\n }\n return pi;\n }\n public static boolean next(int[] arr, int k) {\n boolean remain = false;\n for (int i = arr.length - 1; i >= 0; i--) {\n arr[i]++;\n if (arr[i] == k) {\n arr[i] = 0;\n remain = true;\n } else {\n remain = false;\n break;\n }\n }\n return !remain;\n }\n private static String numArrToString(int[] arr) {\n StringBuilder sb = new StringBuilder();\n for (var i : arr) {\n sb.append(i);\n }\n return sb.toString();\n }\n}\n```\n
3
0
['C++', 'Java', 'Python3']
1
cracking-the-safe
backtrack python
backtrack-python-by-djdheeraj5701-4x8h
Have a set of visited permutations\nbase case: if all permutations found then store current string and return True\nrecursion case: \n try all po
djdheeraj5701
NORMAL
2022-08-14T09:42:30.910758+00:00
2022-08-14T09:42:30.910805+00:00
588
false
Have a set of visited permutations\nbase case: if all permutations found then store current string and return True\nrecursion case: \n try all possible i from 0 to k as a new character\n\t\t\t\tcall the function again \n\t\t\t\treturn False if none of them worked\n```\nclass Solution:\n def crackSafe(self, n: int, k: int) -> str:\n self.ans=None\n self.visited=set()\n def backtrack(curr):\n # print(curr,self.visited)\n if len(self.visited)==k**n:\n self.ans=curr\n return True\n \n for i in range(k):\n new_curr=str(i)+curr\n if new_curr[:n] not in self.visited:\n self.visited.add(new_curr[:n])\n if backtrack(new_curr):\n return True\n self.visited.remove(new_curr[:n])\n return False\n backtrack(\'0\'*(n-1))\n return self.ans\n \n```\n
3
0
['Backtracking', 'Recursion', 'Python']
0
cracking-the-safe
Java 2ms DFS
java-2ms-dfs-by-jowangcn-wj96
These are how I reduce the time:\n(1) Use a boolean[] to store which number has been included. and to avoid the transform the number from decimal to other base,
jowangcn
NORMAL
2021-11-29T23:59:10.409104+00:00
2021-11-29T23:59:10.409149+00:00
865
false
These are how I reduce the time:\n(1) Use a boolean[] to store which number has been included. and to avoid the transform the number from decimal to other base, I use the extra space to make it easy. This is quicker than HashSet/HashMap. \n(2) pass the current tested password in integer in the recursion, so that the next number can be easily calcuated as a decimal number;\n\n\n```\nclass Solution {\n public String crackSafe(int n, int k) {\n int targetCnt = (int)Math.pow(k,n);\n boolean[] visited = new boolean[(int)Math.pow(10,n)];\n visited[0] = true;\n int visitedCnt = 1;\n StringBuilder crackStr = new StringBuilder();\n for(int i=0;i<n;i++){\n crackStr.append(\'0\');\n }\n dfsAddPwd(n,k,crackStr,0,visited, visitedCnt,targetCnt); \n return foundStr;\n }\n \n String foundStr;\n \n private void dfsAddPwd(int n, int k, StringBuilder crackStr,int prev, boolean[] visited,int visitedCnt, int targetCnt){\n if(foundStr!=null ) return;\n if(visitedCnt == targetCnt){\n foundStr = crackStr.toString();\n //System.out.println(foundStr);\n return;\n }\n \n int root = 10*prev % ((int)Math.pow(10,n));\n for(int i=0;i<k;i++){\n int current = root +i;\n if(!visited[current]){ \n crackStr.append(i);\n visited[current] = true;\n dfsAddPwd(n,k,crackStr,current,visited,visitedCnt+1,targetCnt);\n crackStr.setLength(crackStr.length()-1);\n visited[current] = false;\n }\n }\n }\n}\n```
3
3
['Depth-First Search', 'Java']
0
cracking-the-safe
[Python 3] De Bruijn Sequence
python-3-de-bruijn-sequence-by-bakerston-h1x1
\ndef crackSafe(self, n: int, k: int) -> str: \n if n == 1:\n return "".join(map(str, range(k)))\n if k == 1:\n return
Bakerston
NORMAL
2021-04-11T01:00:34.343070+00:00
2021-04-11T01:00:34.343121+00:00
402
false
```\ndef crackSafe(self, n: int, k: int) -> str: \n if n == 1:\n return "".join(map(str, range(k)))\n if k == 1:\n return "0" * n\n alpha = list(map(str, range(k)))\n a = [0] * k * n\n seq = []\n def db(t, p):\n if t > n:\n if n % p == 0:\n seq.extend(a[1 : p + 1])\n else:\n a[t] = a[t - p]\n db(t + 1, p)\n for j in range(a[t - p] + 1, k):\n a[t] = j\n db(t + 1, t)\n db(1, 1)\n ans = "".join(alpha[i] for i in seq)\n return ans + ans[:n - 1]\n```
3
0
[]
0
cracking-the-safe
Easy Python solution with explanation
easy-python-solution-with-explanation-by-lyi2
Total number of passwords is k^n. Create a set to record our accessible numbers.\nTo make our key shortest, we need the maximum overlap with every two different
yixizhou
NORMAL
2020-09-30T22:53:30.648128+00:00
2020-09-30T22:53:30.648159+00:00
293
false
Total number of passwords is k^n. Create a set to record our accessible numbers.\nTo make our key shortest, we need the maximum overlap with every two different passwords, which is n-1.\nStart with "0"*n, pick the last n-1 numbers and add other new numbers to the end, if the new number is not in the set, we add it to the set.\nRepeat the steps until we got a set with length k^n.\n```\nclass Solution:\n def crackSafe(self, n: int, k: int) -> str:\n x = "0"*n\n d = {x}\n while len(d) < k**n:\n y = x[-1:-n:-1][::-1]\n for z in range(k-1,-1,-1):\n if y + str(z) not in d:\n x += str(z)\n d.add(y+str(z))\n break\n return x\n```
3
0
[]
3
cracking-the-safe
C++, DFS and backtracking
c-dfs-and-backtracking-by-paulpsp-8kin
You don\'t need to pre generate the graph, you can create it on the fly and each state has to create all the next possible states and record them in a set, the
paulpsp
NORMAL
2020-08-08T00:45:22.708375+00:00
2020-08-08T00:45:22.708412+00:00
403
false
You don\'t need to pre generate the graph, you can create it on the fly and each state has to create all the next possible states and record them in a set, the down side is that you to generate all the other `k` states which might have already been visited previously, but it is easier than maintaining the graph stcutrue and doesn\'t require pre processing\n\n```\nclass Solution {\npublic:\n bool dfs(int n ,int k, unordered_set<string>& visited, string& password, int len, int goal) {\n if (len == goal) {\n return true;\n }\n \n string next = password.substr(password.length()-n+1);\n \n for (int i = 0 ; i < k; ++i) {\n next.push_back(\'0\' + i);\n if (visited.find(next) == visited.end()) {\n visited.insert(next);\n password.push_back(\'0\' + i);\n if (dfs(n, k, visited, password, len+1, goal)) {\n return true;\n }\n password.pop_back();\n visited.erase(next);\n }\n next.pop_back();\n }\n \n return false;\n }\n \n string crackSafe(int n, int k) {\n unordered_set<string> visited;\n \n string cur = string(n, \'0\');\n string password = string(n, \'0\');\n visited.insert(cur);\n \n dfs(n, k, visited, password, 1, pow(k, n) /*how many states do we need to visit*/);\n \n return password;\n }\n};\n```
3
0
[]
0
cracking-the-safe
Python short & simple
python-short-simple-by-dylan20-1sp9
\nclass Solution(object):\n def crackSafe(self, n, k):\n toVisit = collections.defaultdict(lambda: map(str, range(k)))\n toVisit["0" * (n - 1)]
dylan20
NORMAL
2018-01-06T16:41:12.224000+00:00
2018-01-06T16:41:12.224000+00:00
754
false
```\nclass Solution(object):\n def crackSafe(self, n, k):\n toVisit = collections.defaultdict(lambda: map(str, range(k)))\n toVisit["0" * (n - 1)] = map(str, range(1, k))\n ans = "0" * n\n while True:\n cur = ans[len(ans) - n + 1:]\n if not toVisit[cur]: return ans\n ans += toVisit[cur].pop()\n```
3
0
[]
2
cracking-the-safe
Java Solution
java-solution-by-archivebizzle-t5ug
Intuition\nThe goal is to find the shortest possible password that contains all possible combinations of the given digits\n\n# Approach\nInitialize Variables:\n
archivebizzle
NORMAL
2024-01-11T13:49:51.431291+00:00
2024-01-11T13:49:51.431311+00:00
534
false
# Intuition\nThe goal is to find the shortest possible password that contains all possible combinations of the given digits\n\n# Approach\nInitialize Variables:\n\nCreate a string allZeros containing \'n\' zeros, representing the initial state of the password.\nCreate a StringBuilder sb and initialize it with allZeros.\nInitialize a set seen with the initial password allZeros.\n\nDepth-First Search (DFS) Function (dfs):\n\nThe DFS function is designed to explore and generate the password recursively.\nBase Case: If the size of the seen set equals the total number of possible combinations (passwordSize), return true, indicating that all combinations have been covered.\nExtract the last \'n-1\' characters from the current password path to form a prefix prefix.\nIterate through each digit from \'0\' to \'0+k-1\'.\nAppend the digit to the prefix and convert it to a string (prefixStr).\nIf prefixStr is not in the seen set:\nAdd prefixStr to the seen set.\nAppend the digit to the password path.\nRecursively call the dfs function with the updated parameters.\nIf the recursive call returns true, indicating a valid password is found, return true.\nBacktrack by removing the last character from the password and removing prefixStr from the seen set.\n\nMain Function (crackSafe):\n\nInitialize variables and call the dfs function to generate the password.\nReturn the final password as a string.\nResult:\n\nThe final password is built using the DFS approach, ensuring that all possible combinations are included, and the shortest possible password is generated.\nThe approach focuses on exploring the solution space efficiently through DFS, maintaining a set of seen combinations to avoid duplicates, and backtracking when necessary. The resulting password is guaranteed to meet the specified criteria.\n\n# Complexity\n- Time complexity:\n O(k^(passwordSize/n))\n\n- Space complexity:\nO(passwordSize + n)\n\n# Code\n```\nclass Solution {\n public String crackSafe(int n, int k) {\n final String allZeros = "0".repeat(n);\n StringBuilder sb = new StringBuilder(allZeros);\n dfs((int) Math.pow(k, n), n, k, new HashSet<>(Arrays.asList(allZeros)), sb);\n return sb.toString();\n }\n\n private boolean dfs(int passwordSize, int n, int k, Set<String> seen, StringBuilder path) {\n if (seen.size() == passwordSize)\n return true;\n\n StringBuilder prefix = new StringBuilder(path.substring(path.length() - n + 1));\n\n for (char c = \'0\'; c < \'0\' + k; ++c) {\n prefix.append(c);\n final String prefixStr = prefix.toString();\n if (!seen.contains(prefixStr)) {\n seen.add(prefixStr);\n path.append(c);\n if (dfs(passwordSize, n, k, seen, path))\n return true;\n path.deleteCharAt(path.length() - 1);\n seen.remove(prefixStr);\n }\n prefix.deleteCharAt(prefix.length() - 1);\n }\n\n return false;\n }\n}\n```
2
0
['Java']
0
cracking-the-safe
JAVA solution
java-solution-by-21arka2002-udzd
\nclass Solution {\n public String crackSafe(int n, int k) {\n HashSet<String>v=new HashSet<>();\n String ans="";\n for(int i=0;i<n;i++)
21Arka2002
NORMAL
2023-04-28T16:13:25.609682+00:00
2023-04-28T16:13:25.609748+00:00
408
false
```\nclass Solution {\n public String crackSafe(int n, int k) {\n HashSet<String>v=new HashSet<>();\n String ans="";\n for(int i=0;i<n;i++) ans+=\'0\';\n int len = n + (int)Math.pow(k,n) - 1;\n ans=dfs(ans,n,k,v,len);\n return ans;\n }\n public String dfs(String s,int n,int k,HashSet<String>v,int len)\n {\n int l=s.length();\n v.add(s.substring(l-n,l));\n for(int i=0;i<k;i++)\n {\n if(v.contains(s.substring(l-n+1,l)+Integer.toString(i))==false)\n {\n String temp = dfs(s+Integer.toString(i),n,k,v,len);\n if(temp.length()==len)\n {\n s=temp;\n break;\n }\n v.remove(s.substring(l-n+1, l)+Integer.toString(i));\n }\n }\n return s;\n }\n}\n```
2
0
['Depth-First Search', 'Recursion', 'Java']
0
cracking-the-safe
✅Python 3 - fast (95%+) - explained 😃 - de Bruijn sequence
python-3-fast-95-explained-de-bruijn-seq-e40p
\n\n\n# Intuition\nIt is very intuitive that two adjacent passwords should differ by first and last digits\n- example for n = 3, k = 2:\n\nwe have 8 (2 ** 3) di
noob_in_prog
NORMAL
2023-01-11T12:36:11.138594+00:00
2023-01-11T12:38:13.647861+00:00
317
false
![image.png](https://assets.leetcode.com/users/images/0865974f-c981-497d-9936-701f3f44a38e_1673439994.1812327.png)\n\n\n# Intuition\nIt is very intuitive that two **adjacent passwords** should **differ by first and last digits**\n- example for `n = 3`, `k = 2`:\n```\nwe have 8 (2 ** 3) different passwords\n\nsolution: 0001011100 (one of several possible solutions)\npassword 1: 000| | |\npassword 2: 001 | |\npassword 3: 010 | |\npassword 4: 101| |\npassword 5: 011 |\npassword 6: 111 |\npassword 7: 110|\npassword 8: 100\n\nlength of solution = 2 ** 3 + (3 - 1) = 10\n```\n\n# Approach\n\n---\n\n**de Bruijn sequence** - a **cyclic sequence** in which every substring **occurs exactly once**\n- description on [wiki](https://en.wikipedia.org/wiki/De_Bruijn_sequence)\n- thanks to [leetCode community](https://leetcode.com/problems/cracking-the-safe/solutions/153039/dfs-with-explanations/)\n\n---\n\n\n\n\n1. cyclic sequence (standard case)\n$$length = k^n$$\n\n- for `n = 2`, `k = 2` (c) [wiki](https://en.wikipedia.org/wiki/De_Bruijn_sequence)\n![image.png](https://assets.leetcode.com/users/images/a8d74d5f-4e12-4183-bfdb-300854046556_1673437879.4385016.png)\n- for `n = 3`, `k = 2` (c) [wiki](https://en.wikipedia.org/wiki/De_Bruijn_sequence#Construction)\n![image.png](https://assets.leetcode.com/users/images/370ceb1a-3d08-4d19-b80f-b4deb24b6519_1673438726.5019128.png)\n\n\n\n\n2. non-cyclic sequense (our problem)\n$$length = k^n + (n - 1)$$\n> A de Bruijn sequence can be used to **shorten a brute-force attack on a PIN-code lock** that does not have an "enter" key and accepts the last n digits entered. \nFor example, a digital door lock with a **4-digit** code (each digit **from 0 to 9**) would have **at most 10000 + 3 = 10003**, whereas trying all codes separately would require **4 \xD7 10000 = 40000** presses. (c) [wiki - de Bruijn sequence - attacks on locks](https://en.wikipedia.org/wiki/De_Bruijn_sequence#Brute-force_attacks_on_locks)\n- once we found the **target length** for solution, we can use a simple backTracking algorithm to find it \n\n\n\n# Code\n```\nclass Solution:\n def crackSafe(self, n: int, k: int) -> str:\n\n def dfs(prv, res, res_l):\n if len(res) == trg_l: # reached target length\n res_arr.append(res)\n return\n\n prv = prv[1:] # remove first number\n for i in map(str, range(k)): # convert integer to string\n \n cur = prv + i \n if cur in visited: continue # already have current password -> skip\n\n visited.add(cur) \n dfs(cur, res + i, res_l + 1) # try to find next password\n visited.remove(cur) # this try was unsuccessful -> remove current password from set \n\n if res_arr: return # interruption: find solution -> interrupt\n\n\n\n res_arr = []\n start_p = \'0\' * n # initial password \'0..0\'\n visited = set([start_p]) \n trg_l = k ** n + (n - 1) # (n - 1) - because there is no cycle\n \n dfs(start_p, start_p, n) # previous password, solution, current length of solution \n\n return res_arr[0]\n```
2
0
['Backtracking', 'Python3']
0
cracking-the-safe
C++ solution, simple to understand
c-solution-simple-to-understand-by-cptsm-vqvm
Constructing a De Bruijn sequence solves the question. For any permutation x, a new permutation y can be obtained by removing the first character of x and appen
CPTSMONSTER
NORMAL
2021-12-27T00:07:22.389553+00:00
2021-12-27T00:07:22.389584+00:00
571
false
Constructing a De Bruijn sequence solves the question. For any permutation x, a new permutation y can be obtained by removing the first character of x and appending a new character to the end of x from the set of letters in [0, k-1]. The first n-1 characters of any permutation can be constructed as nodes in a graph and any appended new character forms edges between the nodes. Thus, the De Bruijn sequence is obtained when such a graph is traversed on all edges.\n\n```\nclass Solution {\npublic:\n string crackSafe(int n, int k) {\n unordered_set<string> visited;\n \n string starting_node = string(n - 1, \'0\');\n string deBruijn = starting_node;\n \n helper(starting_node, k, &deBruijn, &visited);\n \n return deBruijn;\n }\n void helper(string curr_node, const int& k, string* deBruijn, unordered_set<string>* visited) {\n for (int e = k - 1; e >= 0; --e) {\n string next_node = curr_node + to_string(e);\n \n if (visited->find(next_node) == visited->end()) {\n visited->insert(next_node);\n *deBruijn += to_string(e);\n helper(next_node.substr(1), k, deBruijn, visited);\n }\n }\n }\n};\n```
2
1
[]
0
cracking-the-safe
Easy to understand Java DFS
easy-to-understand-java-dfs-by-viveksinu-ae3h
\n/*\nWe need string of n digits with each digit ranging from 0 to k, so max combination = k^n\nstart with "0000" if k=2, then next can be 00001=> this has 2 c
viveksinub
NORMAL
2021-09-03T08:40:59.116634+00:00
2021-09-03T08:40:59.116675+00:00
561
false
```\n/*\nWe need string of n digits with each digit ranging from 0 to k, so max combination = k^n\nstart with "0000" if k=2, then next can be 00001=> this has 2 combinatioons 0000 , 0001\nlast n digits tell the combination\nstart with all 0 add eack of k numbers in end if not visited\n*/\nclass Solution {\n String ans;\n public String crackSafe(int n, int k) {\n ans=null;\n String start = new String(new char[n-1]).replace(\'\\0\',\'0\');\n if(dfs(start,new HashSet<>(),n,k))return ans;\n else return "";\n }\n //boolean because as soon as any reaches end , stop\n boolean dfs(String prefix,Set<String> visited, int n,int k){\n if(visited.size()==Math.pow(k,n)){\n ans=prefix;\n return true;\n }\n String prevN_1_digits = prefix.substring(prefix.length()-n+1);\n \n for(char s=\'0\';s<\'0\'+k;s++){\n String newPass = prevN_1_digits + s;\n if(visited.contains(newPass)) continue;\n visited.add(newPass);\n if(dfs(prefix+s,visited,n,k)) return true;\n visited.remove(newPass);\n }\n return false;\n }\n}\n```
2
0
[]
0
cracking-the-safe
Java | simple backtracking, space trade off faster than 80%
java-simple-backtracking-space-trade-off-l2wf
Check the suffix substring with size of n\n\nclass Solution {\n \n int maxCombination = 1;\n int K;\n int N;\n String res;\n public boolean cr
zoey_mameshiba
NORMAL
2021-05-07T23:32:09.804158+00:00
2021-05-07T23:34:06.403180+00:00
503
false
Check the suffix substring with size of n\n```\nclass Solution {\n \n int maxCombination = 1;\n int K;\n int N;\n String res;\n public boolean crackSafeHelper(String prefix, Set<String> allCombs) {\n if (prefix.length() >= N \n\t\t\t&& allCombs.contains(prefix.substring(prefix.length() - N))) {\n return false;\n }\n if (prefix.length() >= N) allCombs.add(prefix.substring(prefix.length() - N));\n if (allCombs.size() >= maxCombination) {\n res = prefix;\n return true;\n }\n \n for (int i = 0; i < K; i++) {\n if(crackSafeHelper(prefix + String.valueOf(i), allCombs)) return true;\n }\n if (prefix.length() >= N) allCombs.remove(prefix.substring(prefix.length() - N));\n return false;\n }\n public String crackSafe(int n, int k) {\n // minimize the overlap that covers\n // all the combination with length of n picked from number [0, k - 1]\n K = k;\n N = n;\n for (int i = 0; i < N; i++) {\n maxCombination *= K;\n }\n crackSafeHelper("", new HashSet<>());\n return res;\n }\n}\n```
2
0
[]
0
cracking-the-safe
Swift DFS
swift-dfs-by-johnamcruz-lv13
\nclass Solution {\n var result = ""\n \n func crackSafe(_ n: Int, _ k: Int) -> String {\n if n == 1 && k == 1 {\n return "0"\n
johnamcruz
NORMAL
2020-11-06T09:18:00.809585+00:00
2020-11-06T09:18:00.809612+00:00
191
false
```\nclass Solution {\n var result = ""\n \n func crackSafe(_ n: Int, _ k: Int) -> String {\n if n == 1 && k == 1 {\n return "0"\n }\n \n var visited = Set<String>()\n var start = String(repeating: "0", count: n-1)\n dfs(start, k, &visited)\n result.append(start)\n return result\n }\n \n func dfs(_ start: String, _ k: Int, _ visited: inout Set<String>) {\n for index in 0..<k {\n var neighbor = "\\(start)\\(index)"\n if !visited.contains(neighbor) {\n visited.insert(neighbor)\n var charArray = [Character](neighbor)\n dfs(String(charArray[1...]), k, &visited)\n result.append(String(index))\n }\n }\n }\n}\n\nextension StringProtocol {\n subscript(index: Int) -> Character {\n return self[self.index(self.startIndex, offsetBy: index)]\n }\n}\n```
2
0
[]
0
cracking-the-safe
Java DFS to make sure short circuit!
java-dfs-to-make-sure-short-circuit-by-h-fvph
\nclass Solution {\n int t, n, k;\n public String crackSafe(int n, int k) {\n this.t = (int) Math.pow(k, n);\n this.n = n;\n this.k =
hobiter
NORMAL
2020-03-02T06:48:41.031174+00:00
2020-03-02T06:48:41.031222+00:00
337
false
```\nclass Solution {\n int t, n, k;\n public String crackSafe(int n, int k) {\n this.t = (int) Math.pow(k, n);\n this.n = n;\n this.k = k;\n StringBuilder sb = new StringBuilder();\n String first = String.join("", Collections.nCopies(n, "0"));\n sb.append(first);\n Set<String> vs = new HashSet<>();\n vs.add(first);\n dfs(vs, sb);\n return sb.toString();\n }\n \n private boolean dfs(Set<String> vs, StringBuilder sb) {\n if (vs.size() == t) return true;\n String s = sb.substring(sb.length() - n + 1);\n for (char i = \'0\'; i < \'0\' + k; i++) {\n String curr = s + i;\n if (!vs.contains(curr)) {\n vs.add(curr);\n sb.append(i);\n if (dfs(vs, sb)) return true;\n sb.deleteCharAt(sb.length() - 1);\n vs.remove(curr);\n }\n }\n return false;\n }\n}\n```\n\nIt is a very tricky problem, dfs is almost brutal force.\nref: https://leetcode.com/problems/cracking-the-safe/discuss/153039/DFS-with-Explanations
2
0
[]
0
cracking-the-safe
O(k * k^n) just loop
ok-kn-just-loop-by-aqin-nzb3
\nclass Solution {\n public String crackSafe(int n, int k) {\n StringBuilder sb = new StringBuilder();\n Set<String> set = new HashSet<>();\n
aqin
NORMAL
2020-01-28T02:26:35.329607+00:00
2020-01-28T02:26:35.329662+00:00
193
false
```\nclass Solution {\n public String crackSafe(int n, int k) {\n StringBuilder sb = new StringBuilder();\n Set<String> set = new HashSet<>();\n for (int i = 0; i < n; i++){\n sb.append("0");\n }\n set.add(sb.toString());\n boolean stop = false;\n while(!stop){\n String prefix = sb.substring(sb.length() - n + 1);\n stop = true;\n for (int i = k - 1; i >= 0; i--){\n if (!set.contains(prefix + i)){\n sb.append(i);\n set.add(prefix + i);\n stop = false;\n break;\n }\n }\n }\n return sb.toString();\n }\n}\n```
2
0
[]
1
cracking-the-safe
Python DP+DFS solution beats 98%, short explanation
python-dpdfs-solution-beats-98-short-exp-zla0
It is not hard to get that the minimum length for given n and k is k^n+n-1. Then the question becomes:\n1) for any n and k, can we always reach the minimum len
zhipengyu2015
NORMAL
2019-08-21T05:25:25.245129+00:00
2019-08-21T05:25:25.245181+00:00
353
false
It is not hard to get that the minimum length for given `n` and `k` is `k^n+n-1`. Then the question becomes:\n1) for any `n` and `k`, can we always reach the minimum lenth\n2) if 1) is true, how to construct such string with the minimum length\n\n\nFor 1), I don\'t know how to prove it but I can always find the string with minimum length by hand.\nFor 2), you can always get a string for `n` and `k` based on the optimal string of `n` and `k-1`. (by appending)\n\n```\nclass Solution(object):\n def crackSafe(self, n, k):\n if k<=0:\n return\n \n string=\'0\'*n\n visited=set([string])\n \n def dfs(string,n,visited,i):\n if len(string)==(i+1)**n+n-1:\n return string\n lastStr=string[-n+1:] if n>1 else \'\'\n for d in range(i+1):\n if lastStr + str(d) not in visited:\n visited.add(lastStr + str(d))\n res=dfs(string+str(d),n,visited,i)\n if res:\n return res\n visited.remove(lastStr + str(d))\n return None\n \n for i in range(1,k):\n string=dfs(string,n,visited,i) \n return string\n```
2
0
[]
1
cracking-the-safe
Please Help with my Hamiltonian Path Solution (Passed 37/38 Testcases)
please-help-with-my-hamiltonian-path-sol-ev0a
I made a solution that builds a directed graph showing the current node and the nodes reachable from the current node. (Stored as an adjacency list in dict_).\n
spie2005
NORMAL
2018-12-19T08:18:10.961534+00:00
2018-12-19T08:18:10.961575+00:00
1,737
false
I made a solution that builds a directed graph showing the current node and the nodes reachable from the current node. (Stored as an adjacency list in dict_).\n\nI then run hamiltonian search on this dictionary to find the shortest path that touches every node.\n\nThis solution passed 37/38 testcases. The solution gives a time limit exceeded error. \n\nCould anyone help optimize this?\n\nThanks!\n\n```\nfrom collections import defaultdict\nfrom itertools import product\nclass Solution: \n dict_ = {}\n vertices = []\n visited = {}\n\n def hamilton(self,G, size, pt, path=[]):\n # print(\'hamilton called with pt={}, path={}\'.format(pt, path))\n if pt not in set(path):\n path.append(pt)\n if len(path)==size:\n return path\n for pt_next in G.get(pt, []):\n res_path = [i for i in path]\n candidate = self.hamilton(G, size, pt_next, res_path)\n if candidate is not None: # skip loop or dead end\n return candidate\n # print(\'path {} is a dead end\'.format(path))\n else:\n pass\n # print(\'pt {} already in path {}\'.format(pt, path))\n # loop or dead end, None is implicitly returned\n \n def crackSafe(self, n, k):\n k_list = [str(i) for i in range(k)]\n vertices = []\n if n == 1:\n return \'\'.join(k_list)\n edges = []\n vertices = [\'\'.join(i) for i in list(product(k_list,repeat = n))]\n # print(vertices)\n dict_ = {}\n for i in range(len(vertices)):\n temp = vertices[i][1:]\n for k in k_list:\n if temp + k in vertices:\n if vertices[i] in dict_:\n dict_[vertices[i]] += [temp+k]\n else:\n dict_[vertices[i]] = [temp+k]\n self.dict_ = dict_\n path = self.hamilton(self.dict_,len(vertices),vertices[0],[])\n # print(self.dict_)\n cnt = True\n ans = ""\n for i in path:\n if cnt:\n ans += i\n cnt = False\n else:\n ans+=i[-1]\n # print(path)\n return ans\n```
2
0
[]
1
cracking-the-safe
Simple C++ beats 100%
simple-c-beats-100-by-kevincabbage-odka
Say there is a string A the length of which is n - 1. we can put k different digits in front of it to get k different string B whose length is n. And we can als
kevincabbage
NORMAL
2018-10-04T02:33:34.962882+00:00
2018-10-11T07:29:20.913752+00:00
486
false
Say there is a string A the length of which is n - 1. we can put k different digits in front of it to get k different string B whose length is n. And we can also put k different digits at the end of it to get another k different string C.\n\nSo we can always find a digit and add it to the end of previous string, and we can prove that the last n digits nerver occur before if we choose the approiate digit. Because the last n digits of previous string appears, it means the number of B is less than k, so the number of C (the last n digits of current string) is also less than k. But how can we get the appropriate digit? We can add digits in some order to prevent repetition. We should pay attention to the first n digits, because it has no B in front of it. Indeed the last n digits of answer has no C. So in the solution below, the last n digits of the answer become the B of the first n digits. In other words, the last n - 1 digits and the first n - 1 digits are the same.\n\n```\n // reverse order\n string crackSafe(int n, int k) {\n int i, total = pow(k, n);\n unordered_map<string, int> record;\n string ans;\n \n ans.assign(n, \'0\');\n for(i = 1; i < total; ++i) ans += \'0\' + k - ++record[ans.substr(ans.length() - n + 1, n - 1)];\n \n return ans;\n }\n\t\t\n // normal order\n string crackSafe(int n, int k) {\n int i, total = pow(k, n);\n unordered_map<string, int> record;\n string ans;\n \n ans.assign(n, \'0\' + k - 1);\n for(i = 1; i < total; ++i) ans += \'0\' + record[ans.substr(ans.length() - n + 1, n - 1)]++;\n \n return ans;\n }\n```
2
0
[]
0
cracking-the-safe
Java Bitwise DFS beats 90%
java-bitwise-dfs-beats-90-by-crunner-bcqs
Based on the assumptions of k and n, we use 4 bits to represent k and an integer to represent the password.\n\n\n public String crackSafe(int n, int k) {\n
crunner
NORMAL
2018-09-20T01:18:06.235844+00:00
2018-09-20T01:18:06.235891+00:00
314
false
Based on the assumptions of k and n, we use 4 bits to represent k and an integer to represent the password.\n\n```\n public String crackSafe(int n, int k) {\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < n; i++)\n sb.append(0);\n Set<Integer> visited = new HashSet<Integer>();\n visited.add(0);\n int count = (int)Math.pow(k, n);\n scan(sb, n, k, count, visited);\n return sb.toString();\n }\n \n private boolean scan(StringBuilder sb, int n, int k, int count, Set<Integer> visited) {\n if (visited.size() == count)\n return true;\n int code = 0;\n for (int i = 1; i <= n-1; i++) {\n code |= (sb.charAt(sb.length()-i)-\'0\');\n code <<= 4;\n }\n for (int i = 0; i < k; i++) {\n if (!visited.contains(code|i)) {\n visited.add(code|i);\n sb.append(i);\n if (scan(sb, n, k, count, visited))\n return true;\n sb.deleteCharAt(sb.length()-1);\n visited.remove(code|i);\n }\n }\n return false;\n }\n```
2
0
[]
0
cracking-the-safe
Python simple DFS
python-simple-dfs-by-kleedy-zkge
\nclass Solution(object):\n def crackSafe(self, n, k):\n def dfs(cur, used):\n if len(used) == k**n - 1:\n return [True, cur
kleedy
NORMAL
2018-05-26T05:28:12.949041+00:00
2018-05-26T05:28:12.949041+00:00
558
false
```\nclass Solution(object):\n def crackSafe(self, n, k):\n def dfs(cur, used):\n if len(used) == k**n - 1:\n return [True, cur]\n used.add(cur[-n:])\n for digit in map(str,range(k)):\n new = cur + digit\n if new[-n:] not in used:\n temp = dfs(new, used)\n if temp[0]:\n return temp\n used.remove(cur[-n:])\n return [False, cur]\n return dfs(\'0\'*n, set())[1]\n```
2
0
[]
0
cracking-the-safe
6-liner to make new password with (n-1)-prefix (with explanation)
6-liner-to-make-new-password-with-n-1-pr-acsa
This solution is inspired by @\u5728\u7ebf\u75af\u72c2. Here is my brief explanation:\n\nThe problem is actually to ask for de Bruijn sequence (instead of makin
zzg_zzm
NORMAL
2017-12-31T03:51:18.024000+00:00
2017-12-31T03:51:18.024000+00:00
354
false
This solution is inspired by @\u5728\u7ebf\u75af\u72c2. Here is my brief explanation:\n\nThe problem is actually to ask for [de Bruijn sequence](https://en.wikipedia.org/wiki/De_Bruijn_sequence) (instead of making a cyclic sequence, we need to pad the end with first `n-1` chars).\n\nNote that [de Bruijn sequence](https://en.wikipedia.org/wiki/De_Bruijn_sequence) is not unique, but it is common to start with prefix `p = "00...0"` with `n-1` of `'0'`s. **Then with each subsequent digit `d` to append, we just need to make sure the `n`-suffix `p+d` is a new combination**. Since we start with lowest digits `0`, we will try to append larger digit `d` first to avoid early termination. We use a hash set `visited` to record all combinations we have constructed. The algorithm stops if no more new combinations.\n```cpp\n string crackSafe(int n, int k) \n {\n string res(n-1, '0'); // initial (n-1)-prefix \n for (unordered_set<string> visited; true; ) {\n char d = '0'+k-1; // try larger digits first \n // find largest digit for a new password\n for (string p(res.end()-n+1, res.end()); d >= '0' && !visited.insert(p+d).second; --d);\n if (d >= '0') res += d; // found digit d\n else return res; // no more new passwords\n }\n }\n```
2
0
['C++']
0
cracking-the-safe
C++, DFS, 3 ms
c-dfs-3-ms-by-zestypanda-3v6a
\nclass Solution {\npublic:\n string crackSafe(int n, int k) {\n string ans(n, '0');\n if (k == 1) return ans;\n int N = 10000;\n
zestypanda
NORMAL
2017-12-25T05:52:29.820000+00:00
2017-12-25T05:52:29.820000+00:00
1,034
false
```\nclass Solution {\npublic:\n string crackSafe(int n, int k) {\n string ans(n, '0');\n if (k == 1) return ans;\n int N = 10000;\n vector<int> visited(N, 0);\n ans += '1'; // starting with "0..01" due to symmetry\n visited[0] = 1;\n visited[1] = 1;\n int len = pow(k, n)+(n-1); //length of answer\n helper(visited, ans, n, k, len);\n return ans;\n }\nprivate:\n bool helper(vector<int>& visited, string& ans, int n, int k, int len) {\n if (ans.size() == len) return true;\n ans += '0';\n for (int i = 0; i < k; i++) {\n ans.back() = i + '0';\n int t = stoi(ans.substr(ans.size()-n, n));\n if (visited[t] == 0) {\n visited[t] = 1;\n if (helper(visited, ans, n, k, len)) return true;\n visited[t] = 0;\n }\n }\n ans.pop_back();\n return false;\n }\n};\n```
2
0
[]
0
cracking-the-safe
Java greedy solution
java-greedy-solution-by-hdchen-6rcc
\nclass Solution {\n public String crackSafe(int n, int k) { \n final int total = (int) Math.pow(k, n), mod = (int) Math.pow(10, n - 1)
hdchen
NORMAL
2017-12-25T17:16:10.235000+00:00
2017-12-25T17:16:10.235000+00:00
932
false
```\nclass Solution {\n public String crackSafe(int n, int k) { \n final int total = (int) Math.pow(k, n), mod = (int) Math.pow(10, n - 1);\n final Map<Integer, Integer> map = new HashMap();\n map.put(0, 0);\n final Stack<Integer> stack = new Stack();\n stack.add(0);\n while (stack.size() != total) {\n int top = stack.peek();\n int prefix = (top % mod) * 10;\n for (int i = map.get(top); i < k; ++i) {\n int next = prefix + i;\n if (!map.containsKey(next)) {\n map.put(top, i + 1);\n map.put(next, 0);\n stack.push(next);\n break;\n }\n }\n if (top == stack.peek()) {\n map.remove(top);\n stack.pop();\n }\n }\n final StringBuilder sb = new StringBuilder();\n while (1 != stack.size()) {\n sb.append(stack.pop() % 10);\n }\n return String.format(String.format("%%0%dd", n), stack.pop()) + sb.reverse().toString();\n }\n}\n```
2
1
[]
1
cracking-the-safe
simple py solution - using DFS beats 85%
simple-py-solution-using-bfs-beats-85-by-o6vp
IntuitionApproachComplexity Time complexity: Space complexity: Code
noam971
NORMAL
2025-03-01T09:41:35.278701+00:00
2025-03-01T09:59:07.830625+00:00
53
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] class Solution: def crackSafe(self, n: int, k: int) -> str: alphabet = [str(n) for n in range(k)] visited = set() res = [] def dfs(password): for digit in alphabet: new_password = password + digit if new_password not in visited: visited.add(new_password) dfs(new_password[1:]) res.append(digit) dfs("0" * (n - 1)) return "".join(res) + ("0" * (n - 1)) ```
1
0
['Python3']
0
cracking-the-safe
Python - Optimal, simple DFS
python-optimal-simple-dfs-by-babos-c5a1
Approach\n Describe your approach to solving the problem. \nThe key to the DFS is to move to the furthest node from the current one. Starting from passwords of
babos
NORMAL
2024-11-27T23:07:14.415980+00:00
2024-11-27T23:07:14.416005+00:00
60
false
# Approach\n<!-- Describe your approach to solving the problem. -->\nThe key to the DFS is to move to the furthest node from the current one. Starting from passwords of 0s, the next character added should be k-1. Therefore, we loop through the possible digits in reverse order. As a result, there is no need to check for completeness in the DFS function\u2013just return when all possible additions are already in seen set.\n\n# Code\n```python3 []\nclass Solution:\n def crackSafe(self, n: int, k: int) -> str:\n res = "0" * n\n\n # adds added in reverse order!\n nums = [str(i) for i in range(k-1, -1, -1)] \n\n seen = set([res])\n def dfs():\n nonlocal res\n cur = ""\n if n != 1:\n cur = res[-n+1:]\n \n for i in nums:\n if cur + i in seen:\n continue\n res += i\n seen.add(cur + i)\n dfs()\n return\n dfs()\n return res\n```
1
0
['Python3']
0
cracking-the-safe
Easy C++ Solution | Beats 70% | C++ | DFS
easy-c-solution-beats-70-c-dfs-by-rajhar-y95o
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
rajharsh_24
NORMAL
2024-10-16T06:34:34.814692+00:00
2024-10-16T06:34:34.814723+00:00
42
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 {\n unordered_set<string> st;\n string ans="";\n\n void dfs(string curr, int k){\n for(int i=k-1; i>=0; i--){\n char c=i+\'0\';\n string temp=curr.substr(1);\n temp.push_back(c);\n\n if(st.count(temp)==0){\n st.insert(temp);\n ans.push_back(c);\n dfs(temp, k);\n }\n }\n }\npublic:\n string crackSafe(int n, int k) {\n for(int i=0; i<n; i++){\n ans.push_back(\'0\');\n }\n\n st.insert(ans);\n\n dfs(ans, k);\n\n return ans;\n }\n};\n```
1
0
['Depth-First Search', 'Graph', 'C++']
0
cracking-the-safe
Solution from Marlen09 explained to myself
solution-from-marlen09-explained-to-myse-axre
Intuition\nI\'m only writing this shorter copy of Marlen09\'s solution to reinforce my understanding of the problem.\n\nThe graph we want to create is a graph w
Fustigate
NORMAL
2024-05-17T13:53:02.361282+00:00
2024-05-17T13:53:02.361306+00:00
25
false
# Intuition\nI\'m only writing this shorter copy of Marlen09\'s solution to reinforce my understanding of the problem.\n\nThe graph we want to create is a graph which maps one possible solution to the next possible solution. For example if n = 2 and k = 2, the solution should have 2 digits constructed by numbers in {0, 1}. Therefore in the graph below, from top left state 00 to bottom left state 01 we mark the edge to be 1, indicating that 00 + 1 -> 01 (discard first digit since problem says to check the most recent n digits). By applying the same process, we can fill out the rest of the graph.\n\n![\u5FAE\u4FE1\u56FE\u7247_20240517214839.jpg](https://assets.leetcode.com/users/images/9d2cf49f-9ac1-46bf-9e06-ebeae48f6dc7_1715953736.5984771.jpeg)\n\nTherefore the solution is to achieve a minimal distance, we just have to find a path that visits every single node in the least amount of edges. We do this by using DFS.\n\n# Code\n```python\nclass Solution:\n def crackSafe(self, n: int, k: int) -> str:\n if n == 1:\n return "".join(map(str, range(k)))\n \n seen = set()\n result = []\n start_node = "0" * (n - 1)\n \n def dfs(node):\n nonlocal seen, result\n for i in range(k):\n edge = node + str(i)\n if edge not in seen:\n seen.add(edge)\n dfs(edge[1:])\n result.append(str(i))\n \n dfs(start_node)\n return start_node + "".join(result)[::-1]\n```
1
0
['Depth-First Search', 'Graph', 'Python3']
0
cracking-the-safe
Easy Solution
easy-solution-by-anupamkumar-1-g6p7
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nThe approach used in th
20250411.AnupamKumar-1
NORMAL
2023-09-06T08:12:32.062056+00:00
2023-09-06T08:12:32.062087+00:00
38
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe approach used in this solution is to find a De Bruijn sequence, which is a sequence containing all possible combinations of characters of length n in a cyclic manner such that any substring of length n-1 appears exactly once as a contiguous substring. This will ensure that we can unlock the safe by entering the correct sequence of digits.\n\nTo construct a De Bruijn sequence, we can use a depth-first search (DFS) algorithm to explore all possible combinations of digits of length n in a cyclic manner. We start with an initial sequence of n-1 zeros and repeatedly add a new digit from 0 to k-1 to the right end of the sequence while ensuring that the resulting sequence of length n has not been visited before. When we reach a point where we cannot add any more digits, we backtrack to the previous state and continue exploring.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe DFS algorithm explores all possible combinations of digits of length n, so the time complexity is **O(k^n)**.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is **O(k^n)** due to the recursive call stack and the storage of visited sequences.\n# Code\n```\nclass Solution {\n public String crackSafe(int n, int k) {\n int totalCombinations = (int) Math.pow(k, n);\n StringBuilder sb = new StringBuilder();\n\n for (int i = 0; i < n; i++) {\n sb.append("0");\n }\n\n Set<String> visited = new HashSet<>();\n visited.add(sb.toString());\n\n dfs(sb, visited, n, k, totalCombinations);\n\n return sb.toString();\n }\n\n private boolean dfs(StringBuilder sb, Set<String> visited, int n, int k, int totalCombinations) {\n if (visited.size() == totalCombinations) {\n return true;\n }\n\n String lastDigits = sb.substring(sb.length() - n + 1);\n\n for (int i = 0; i < k; i++) {\n String newDigits = lastDigits + i;\n if (!visited.contains(newDigits)) {\n sb.append(i);\n visited.add(newDigits);\n if (dfs(sb, visited, n, k, totalCombinations)) {\n return true;\n }\n visited.remove(newDigits);\n sb.deleteCharAt(sb.length() - 1);\n }\n }\n\n return false;\n }\n}\n\n```
1
0
['Java']
0
cracking-the-safe
Easy-to-understand C++ solution, textbook dfs implementation
easy-to-understand-c-solution-textbook-d-vp8x
Approach by Example\nn = 2, k = 2\n\n[00]\n [01]\n [11]\n [10]\n\nWe start with 00, and every time we shift the window right by 1, we hope to find a new pass
taucross9368
NORMAL
2023-04-02T02:47:10.396975+00:00
2023-04-02T03:52:29.484180+00:00
108
false
# Approach by Example\nn = 2, k = 2\n```\n[00]\n [01]\n [11]\n [10]\n```\nWe start with `00`, and every time we shift the window right by 1, we hope to find a new password never tried before, until we have tried all possible passwords.\n\nUse dfs: keep trying above step by step. If we have tried all possible combinations exactly once, we have arrived at the shortest answer.\n# Code\n```\n// visited contains all tried passwords so far, and path contains all of them as\n// substrings.\nbool dfs(int all, int n, int k, unordered_set<string>& visited, string& path) {\n if (visited.size() >= all) {\n // path now contains all possible passwords, exactly once.\n return true;\n }\n\n // take the last n-1 suffix of path, and try all chars in the last position.\n string base = path.substr(path.size() - n + 1);\n for (int i = 0; i < k; i++) {\n // try \'i\' as the last digit.\n char c = \'0\' + i;\n\n string password = base + c;\n if (visited.contains(password)) continue;\n\n // try this password as next.\n path.push_back(c);\n visited.insert(password);\n\n // if we find a solution, cut short.\n if (dfs(all, n, k, visited, path)) return true;\n\n // undo the change.\n visited.erase(password);\n path.pop_back();\n }\n\n return false;\n}\n\nstring crack_safe(int n, int k) {\n int all = 1; // all = k ^ n\n for (int i = 0; i < n; i++) {\n all *= k;\n }\n\n string path(n, \'0\');\n unordered_set<string> visited;\n visited.insert(path);\n\n assert(dfs(all, n, k, visited, path));\n\n return path;\n}\n```
1
0
['C++']
0
cracking-the-safe
EASY TO UNDERSTAND 70% FASTER C++ SOLUTION
easy-to-understand-70-faster-c-solution-e29do
\nclass Solution {\npublic:\n \n string crackSafe(int n, int k) {\n string ans = string(n,\'0\');\n unordered_set<string> s;\n s.inse
abhay_12345
NORMAL
2022-11-27T08:33:20.521371+00:00
2022-11-27T08:33:20.521411+00:00
2,068
false
```\nclass Solution {\npublic:\n \n string crackSafe(int n, int k) {\n string ans = string(n,\'0\');\n unordered_set<string> s;\n s.insert(ans);\n for(int i = 0; i < (pow(k,n)); i++){\n string pre = ans.substr(ans.length()-n+1);\n for(int j = k-1; j>=0; j--){\n string now = pre + to_string(j);\n if(!s.count(now)){\n s.insert(now);\n ans += to_string(j);\n break;\n }\n }\n }\n return ans;\n }\n};\n\n\n```
1
0
['Depth-First Search', 'C', 'Iterator', 'Ordered Set', 'C++']
1
cracking-the-safe
The most ugly code but works [Java][backtracking]
the-most-ugly-code-but-works-javabacktra-idvh
The key idea is to check if all possible combination are occured without duplication. And the minLength of String is = Math.pow(k,n) + n - 1. So we can use a h
liuxiaomingskm
NORMAL
2022-07-27T22:27:12.778758+00:00
2022-07-27T22:27:12.778787+00:00
359
false
The key idea is to check if all possible combination are occured without duplication. And the minLength of String is = Math.pow(k,n) + n - 1. So we can use a hashset to store all combination and if it existed, jump to next number.\n```\n\nclass Solution {\n String ans;\n public String crackSafe(int n, int k) {\n int minLen = (int)Math.pow(k, n) + (n -1);\n \n dfs("", n ,k, new HashSet<String>(),minLen);\n return ans;\n }\n \n private void dfs(String s, int n, int k, HashSet<String>visited,int minLen){\n if (s.length() == minLen){\n ans = s;\n return;\n }\n if (s.length() > minLen){return;}\n \n \n for (int i = 0; i < k; i++){\n s += String.valueOf(i);\n String lastN = s.substring(Math.max(0,s.length() - n), s.length());\n //If already in hashset, rollback and continue;\n if (visited.contains(lastN)){\n s = s.substring(0, s.length() - 1);\n continue;}\n if(lastN.length() == n){ // only put n length string in hashset\n visited.add(lastN); \n }\n \n dfs(s,n,k,visited,minLen);\n if (visited.size() == minLen - n + 1){return;} // if hashset contains all possible combinations just return\n visited.remove(lastN); \n s = s.substring(0, s.length() - 1);\n }\n \n }\n}\n\n```
1
0
['Backtracking', 'Recursion', 'Java']
0
cracking-the-safe
DFS - De Bruijn Sequence - Commented code
dfs-de-bruijn-sequence-commented-code-by-yp2n
\nclass Solution {\npublic:\n string crackSafe(int n, int k) {\n //start with all zeros\n string ans(n,\'0\');\n \n //total no of
gazonda
NORMAL
2022-06-28T09:53:24.554763+00:00
2022-06-28T09:53:24.554813+00:00
349
false
```\nclass Solution {\npublic:\n string crackSafe(int n, int k) {\n //start with all zeros\n string ans(n,\'0\');\n \n //total no of sequences\n int total=pow(k,n);\n unordered_set<int> v;\n \n //storing the integer version of strings in visited array\n v.insert(0);\n dfs(ans,k,n,1,total,v);\n return ans;\n }\n \n bool dfs(string& ans,int k,int n,int count,int total,unordered_set<int>& v){\n //base case\n //we have traversed all sequences\n if(count==total)\n return true;\n \n int len=ans.length();\n \n //borrow n-1 chars from the last sequence\n //only the last character is different\n string prev=ans.substr(len-n+1);\n for(int i=0;i<k;++i){\n char c=\'0\'+i;\n string node=prev+c;\n int inode=stoi(node);\n if(v.count(inode)==0){\n v.insert(inode);\n if(dfs(ans+=c,k,n,count+1,total,v))\n return true;\n //backtrack\n ans.pop_back();\n v.erase(inode);\n }\n }\n \n return false;\n }\n};\n```
1
0
['Depth-First Search', 'C']
0
cracking-the-safe
Python || DFS || Sets || O(k * (k ^ n))
python-dfs-sets-ok-k-n-by-in_sidious-fry0
\nclass Solution:\n def crackSafe(self, n: int, k: int) -> str:\n seen=set()\n def dfs(s,last_n):\n if len(seen)==(k**n): return s\n
iN_siDious
NORMAL
2022-04-07T21:09:27.532011+00:00
2022-04-07T21:13:08.803105+00:00
494
false
```\nclass Solution:\n def crackSafe(self, n: int, k: int) -> str:\n seen=set()\n def dfs(s,last_n):\n if len(seen)==(k**n): return s\n if len(last_n)<n: # If len<n,keep adding zeros as and valid string can be returned\n if len(s+"0")==n: \n seen.add(s+"0")\n ans=dfs(s+"0",last_n+"0")\n return ans\n ans=None\n for i in range(k):\n new=last_n[1:]+str(i)\n if new not in seen:\n seen.add(new)\n ans=dfs(s+str(i),new)\n if ans: return ans\n seen.remove(new)\n return dfs("","")\n```
1
0
['Depth-First Search', 'Ordered Set', 'Python']
0
cracking-the-safe
Python greedy method 100%
python-greedy-method-100-by-lonelykid-ruc2
Use a base k number to represent node, maximum (n-1) digits.\nStart from 0 and always use largest available edge. \nNext node is (node*k+edge) % nodeNum\n\npyth
lonelykid
NORMAL
2022-02-09T00:44:35.925003+00:00
2022-02-09T00:44:35.925046+00:00
683
false
Use a base k number to represent node, maximum (n-1) digits.\nStart from 0 and always use largest available edge. \nNext node is (node*k+edge) % nodeNum\n\n```python\nclass Solution:\n def crackSafe(self, n: int, k: int) -> str:\n ans = list()\n nodeNum = k**(n-1)\n edges = [k-1]*nodeNum\n\n node = 0\n while edges[node] >= 0:\n edge = edges[node]\n edges[node] -= 1\n node = (node * k + edge) % nodeNum\n ans.append(str(edge))\n \n return "0"*(n-1) + "".join(ans)\n```
1
1
['Greedy', 'Python']
0
cracking-the-safe
C#. Euler path. Faster than 100%
c-euler-path-faster-than-100-by-ivananti-9g5d
Alogrithm\nJust a standard Euler path algorithm. Surprise, but it seems to be faster than 100% C# submissions. I thought that De Bruijn approach (Lyndon words)
IvanAntipov
NORMAL
2022-01-30T00:18:36.352212+00:00
2022-01-30T00:39:12.033948+00:00
511
false
# Alogrithm\nJust a standard Euler path algorithm. Surprise, but it seems to be faster than 100% C# submissions. I thought that De Bruijn approach (Lyndon words) should be faster.\n\n\nEach state is represented as the sum for i from 0 to n-2 of i_nth_symbols*k^1. \n\n<img src="https://render.githubusercontent.com/render/math?math=\\sum_{i=0}^{n-2} s_i*k^i">\n\n**where** $`s_i`$ is the i-th symbol of possible password\n\n\nThe implementation search for Euler path throughout the states\n\n# Code\n```\n\npublic class Solution {\n public string CrackSafe(int n, int k) {\n \n var numberOfStates = (int) Math.Pow(k, n-1);\n \n var result = new LinkedList<int>();\n var states = new Dictionary<int, int>();\n for(var i =0; i<numberOfStates; i++)\n {\n states[i] = 0;\n }\n\n void Dfs(int state, int symbol)\n {\n var nextStateBase = state*k % numberOfStates;\n \n while(states[state] < k)\n {\n var currentValue = states[state];\n var nextState = (nextStateBase + currentValue)%numberOfStates;\n var nextStateCurrentValue = states[nextState];\n states[state] = currentValue + 1;\n\n Dfs(nextState, currentValue); \n }\n result.AddFirst(symbol);\n\n }\n \n Dfs(0,0);\n result.RemoveFirst();\n foreach(var i in Enumerable.Range(0, n-1))\n { \n result.AddFirst(0);\n }\n var resultString = String.Join("", result.AsEnumerable());\n return resultString;\n }\n}\n```\n
1
0
['C#']
0
cracking-the-safe
C++ || Graph
c-graph-by-ujjwal2001kant-iptj
```\nclass Solution {\npublic:\n string crackSafe(int n, int k){\n unordered_sets;\n \n string cur="";\n for(int i=0; i<n; i++)\n
ujjwal2001kant
NORMAL
2022-01-07T07:02:01.181176+00:00
2022-05-01T00:22:26.149276+00:00
519
false
```\nclass Solution {\npublic:\n string crackSafe(int n, int k){\n unordered_set<string>s;\n \n string cur="";\n for(int i=0; i<n; i++)\n {\n cur+="0";\n }\n string ans1="";\n s.insert(cur);\n \n ans1+=cur;\n \n int ans=pow(k,n); \n dfs(n,k,cur,s,ans,ans1);\n return ans1;\n }\n \n bool dfs(int n,int k,string& cur,unordered_set<string>&s,int ans,string &ans1)\n {\n if(s.size()==ans)\n return true;\n \n string k1=cur.substr(1);\n string dem=k1;\n \n for(int i=0; i<k; i++)\n {\n char k2=char(\'0\'+i);\n \n k1+=k2;\n if(s.find(k1)==s.end())\n {\n s.insert(k1);\n ans1+=k2;\n if(dfs(n,k,k1,s,ans,ans1))\n return true;\n \n s.erase(k1);\n int p=ans1.size();\n ans1=ans1.substr(0,p-1);\n }\n \n k1=dem;\n }\n \n return false;\n }\n};
1
0
['Graph']
0
cracking-the-safe
javascript dfs/recursion and iteration 95ms
javascript-dfsrecursion-and-iteration-95-cnjw
dfs/recursion\n\nlet total, k, n, res;\nconst crackSafe = (N, K) => {\n n = N, k = K, total = k ** n;\n res = \'0\'.repeat(n), visit = new Set([res]);\n
henrychen222
NORMAL
2021-11-28T01:43:42.907492+00:00
2021-11-28T01:45:12.685672+00:00
240
false
dfs/recursion\n```\nlet total, k, n, res;\nconst crackSafe = (N, K) => {\n n = N, k = K, total = k ** n;\n res = \'0\'.repeat(n), visit = new Set([res]);\n dfs(visit, res);\n return res;\n};\n\nconst dfs = (visit) => {\n if (visit.size == total) return;\n let pre = res.slice(res.length - n + 1); // last n-1 digits\n for (let i = k - 1; ~i; i--) { // appending new digit from k-1 to 0\n let c = i + "", cur = pre + c;\n if (visit.has(cur)) continue;\n visit.add(cur);\n res += c;\n dfs(visit);\n }\n};\n```\niteration\n```\nconst crackSafe = (N, K) => {\n let res = \'0\'.repeat(N), visit = new Set([res]), tot = K ** N;\n while (tot--) {\n let pre = res.slice(res.length - N + 1);\n for (let i = K - 1; ~i; i--) {\n let c = i + "", cur = pre + c;\n if (visit.has(cur)) continue;\n visit.add(cur);\n res += c;\n break;\n }\n }\n return res;\n};\n```
1
0
['Depth-First Search', 'Recursion', 'Iterator', 'JavaScript']
1
cracking-the-safe
Swift (DFS + Backtracking) + Visualization + Explanation + Unit tests O(K^n) time O(K^n) space
swift-dfs-backtracking-visualization-exp-9pl6
\n// MARK: Unit Tests\nfunc testExample1(){\n let obj=Solution()\n let n = 1, k = 2\n let output = "10"\n assert(obj.crackSafe(n,k)==output,"failed
amhatami
NORMAL
2021-09-29T05:03:50.845041+00:00
2021-09-29T05:04:28.014726+00:00
360
false
```\n// MARK: Unit Tests\nfunc testExample1(){\n let obj=Solution()\n let n = 1, k = 2\n let output = "10"\n assert(obj.crackSafe(n,k)==output,"failed example 1")\n}\nfunc testExample2(){\n let obj=Solution()\n let n = 2, k = 2\n let output = "01100"\n assert(obj.crackSafe(n,k)==output,"failed example 2")\n}\n\ntestExample1()\ntestExample2()\n\n// Mark: Solution\nclass Solution {\n var result = ""\n /// time Complexity : O(K^n)\n ///. Space Complexity : O(K^n)\n func crackSafe(_ n: Int, _ k: Int) -> String {\n \n //base case\n if n==1 && k==1 {\n return "0"\n }\n \n // Memoize\n var visited = Set<String>()\n var start = String(repeating: "0", count: n-1)\n dfs(start, k , &visited)\n result.append(start)\n return result\n }\n \n func dfs(_ start: String, _ k: Int, _ visited: inout Set<String>){\n for index in 0..<k {\n var neighbor = "\\(start)\\(index)"\n if !visited.contains(neighbor) {\n visited.insert(neighbor)\n var charArray = [Character](neighbor)\n dfs(String(charArray[1...]), k , &visited)\n result.append(String(index))\n }\n }\n }\n}\n\nextension StringProtocol{\n subscript(index: Int) -> Character {\n return self[self.index(self.startIndex, offsetBy: index)]\n }\n}\n\n\n// MARK: Visulaization\n// We can utilize DFS to find the password:\n\n// goal: to find the shortest input password such that each possible n-length combination of digits [0..k-1] occurs exactly once as a substring.\n\n// node: current input password\n\n// edge: if the last n - 1 digits of node1 can be transformed to node2 by appending a digit from 0..k-1, there will be an edge between node1 and node2\n\n// start node: n repeated 0\'s\n// end node: all n-length combinations among digits 0..k-1 are visited\n\n// visitedComb: all combinations that have been visited\n// Input: n = 1, k = 2\n// Output: "10"\n\n// 1 "1"\n// 0 "10"\n\n// Input: n = 2, k = 2\n// Output: "01100"\n\n// 00 (\'00\' 110)\n// 01 (0 \'01\' 10)\n// 11 (00 \'11\' 0)\n// 10 (001 \'10\')\n```
1
1
[]
0
cracking-the-safe
JAVA AC DFS
java-ac-dfs-by-gwfz0720-4pd4
\nclass Solution {\n public String crackSafe(int n, int k) {\n Set<String> set = new HashSet<>();\n StringBuilder sb = new StringBuilder();\n
gwfz0720
NORMAL
2021-09-27T18:17:39.032467+00:00
2021-09-27T18:17:39.032512+00:00
296
false
```\nclass Solution {\n public String crackSafe(int n, int k) {\n Set<String> set = new HashSet<>();\n StringBuilder sb = new StringBuilder();\n if(dfs(n, k, set, sb)) //return boolean as mark that sb is the string of mininum length to meet the requirement.\n return sb.toString();\n return "";\n }\n public boolean dfs(int n, int k, Set<String> set, StringBuilder sb) {\n if(set.size() == Math.pow(k, n)){\n return true;\n }\n for(int i = 0; i < k; i++){\n sb.append(i);\n String str = sb.length() >= n ? sb.substring(sb.length() - n) : sb.substring(0); // if sb.length is larger than n, then take substring with length n, else take sb as str\n if(set.contains(str)){\n sb.setLength(sb.length() - 1); //if this is exist, remove the last added element in sb, because we are looking for string of minimum length\n continue;\n }\n if(str.length() == n)//only when substring with length n can be added into set\n set.add(str);\n if(dfs(n, k, set, sb))\n return true;\n //backtracking\n sb.setLength(sb.length() - 1);\n set.remove(str);\n }\n return false;\n }\n}```
1
0
[]
0
cracking-the-safe
Really easy to understand python DFS solution
really-easy-to-understand-python-dfs-sol-fl9z
\nclass Solution:\n def crackSafe(self, n: int, k: int) -> str:\n \'\'\'\n n = 2; k = 2\n \n nodes = 00,01,10,11\n 00\n
ikna
NORMAL
2021-09-24T05:42:42.374194+00:00
2021-09-24T05:42:42.374225+00:00
661
false
```\nclass Solution:\n def crackSafe(self, n: int, k: int) -> str:\n \'\'\'\n n = 2; k = 2\n \n nodes = 00,01,10,11\n 00\n 01\n 10 11\n 10 \n \n 00110\n \'\'\'\n out_len = k**n + 1\n \n depth = k**n \n \n visited = set()\n \n start_node = "0"*n\n \n def recurse(node, path):\n if len(path) == depth:\n return path\n \n ret = []\n for i in range(k):\n next_node = node[1:] + str(i)\n if next_node not in visited:\n visited.add(next_node)\n ret = recurse(next_node, path+[next_node])\n if len(ret) == depth: # we have already found a solution so lets just return it.\n return ret\n visited.remove(next_node) #backtrack\n \n return ret\n \n visited.add(start_node)\n res = recurse(start_node, [start_node])\n \n # build the output using res\n out = res[0]\n for ele in res[1:]:\n out += ele[n-1:] \n \n return out\n```
1
2
['Backtracking', 'Depth-First Search', 'Python']
0
cracking-the-safe
c++(0ms 100%)space 100% small solution (only math...)
c0ms-100space-100-small-solution-only-ma-3z66
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Cracking the Safe.\nMemory Usage: 6.2 MB, less than 100.00% of C++ online submissions for Crack
zx007pi
NORMAL
2021-08-25T12:38:41.736080+00:00
2021-08-25T13:15:11.544906+00:00
603
false
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Cracking the Safe.\nMemory Usage: 6.2 MB, less than 100.00% of C++ online submissions for Cracking the Safe.\n```\nclass Solution {\npublic:\n string crackSafe(int n, int k) {\n int table[10000] = {0}, p = --k, div = pow(10, n - 1);\n table[k] = 1;\n string answer(n, \'0\');\n answer[n-1] += k; \n \n while(true){\n p = (p % div) * 10 + k;\n \n for(int i = k; i >= 0; i--, p--)\n if(table[p] == 0){\n table[p] = 1, answer.push_back(\'0\' + i);\n goto mark;\n }\n \n return answer;\n mark:;\n }\n }\n};\n```
1
3
['C', 'C++']
3
cracking-the-safe
C++ | Simple | Eulerian Path
c-simple-eulerian-path-by-dheerajchugh30-um78
\n#include<queue>\n#include<stack>\n#include<string>\n#include<unordered_map>\n\nusing namespace std;\ntypedef unordered_map<string, vector<string>> GRAPH;\n\nu
dheerajchugh303
NORMAL
2021-08-15T20:13:32.561779+00:00
2021-08-15T20:13:32.561811+00:00
526
false
```\n#include<queue>\n#include<stack>\n#include<string>\n#include<unordered_map>\n\nusing namespace std;\ntypedef unordered_map<string, vector<string>> GRAPH;\n\nusing namespace std;\nclass Solution {\nprivate:\n GRAPH generateGraph(int n, int k)\n {\n GRAPH g;\n string str(n, \'0\');\n queue<string> pendingNodes;\n pendingNodes.push(str);\n while(!pendingNodes.empty())\n {\n string temp = pendingNodes.front();\n pendingNodes.pop();\n for (int j = 0; j < k; j++)\n {\n string nextStr = temp;\n nextStr.insert(0, to_string(j));\n nextStr.erase(n,1);\n g[temp].push_back(nextStr);\n if (g.count(nextStr)==0) {\n pendingNodes.push(nextStr);\n g[nextStr]; // just genrating the key in map\n }\n\n }\n }\n return g;\n }\n\n void findPathThroughDFS (string source, GRAPH & graph, stack<string>& pathIndForamtion) {\n while(graph[source].size() > 0)\n {\n string nextString = graph[source][0];\n graph[source].erase(graph[source].begin()); \n findPathThroughDFS(nextString, graph, pathIndForamtion);\n\n }\n pathIndForamtion.push(source);\n }\n\n\npublic:\n string crackSafe(int n, int k) {\n \n if(n ==1) {\n string result;\n for(int i =0 ; i<k ;i++)\n result.insert(0, to_string(i));\n return result; \n }\n \n \n \n GRAPH graph = generateGraph(n-1, k);\n stack<string> pathIndForamtion;\n\n string str(n-1, \'0\');\n findPathThroughDFS(str, graph, pathIndForamtion);\n string result = pathIndForamtion.top(); pathIndForamtion.pop();\n while (!pathIndForamtion.empty())\n {\n string next = pathIndForamtion.top(); \n pathIndForamtion.pop();\n result.insert(result.end(), next[0]);\n }\n return result;\n }\n};\n```
1
0
[]
0
cracking-the-safe
C++ | Simple | Hamiltonian Cycle
c-simple-hamiltonian-cycle-by-darkhorse7-my2h
\nclass Solution {\npublic:\n string getHamiltonianSequence(string current,int n, int k, unordered_set<string>& visited) {\n \n if(visited.siz
darkHorse77
NORMAL
2021-07-16T12:07:06.158308+00:00
2021-07-16T12:07:46.704650+00:00
886
false
```\nclass Solution {\npublic:\n string getHamiltonianSequence(string current,int n, int k, unordered_set<string>& visited) {\n \n if(visited.size()==pow(k,n)) //max number of sequences possible\n return "";\n \n for(int i = 0; i<k; ++i){\n \n string next = current.substr(current.size()-n+1,current.size())+to_string(i);\n \n if(visited.find(next)==visited.end()){\n \n visited.insert(next);\n \n string sequence_following = getHamiltonianSequence(next,n,k,visited);\n \n if(sequence_following!="-1"){\n return to_string(i) + sequence_following;\n }\n \n //backtrack\n visited.erase(next);\n }\n }\n \n return "-1";\n }\n \n \n string crackSafe(int n, int k) {\n \n string start ="";\n \n for(int i=0; i<n; ++i)\n start += "0";\n \n unordered_set<string> visited;\n visited.insert(start);\n \n string sequence = getHamiltonianSequence(start,n, k, visited);\n \n if(sequence != "-1")\n return start+sequence;\n \n return start;\n }\n};\n```
1
0
[]
0
cracking-the-safe
Super easy DFS | C++ | 0ms - beats 100%
super-easy-dfs-c-0ms-beats-100-by-_shiva-nb1k
\nclass Solution {\npublic:\n int power(int base, int exponent){\n if(exponent==0)return 1;\n int halfWork = power(base,exponent/2);\n i
_shivam7
NORMAL
2021-05-29T03:56:09.662457+00:00
2021-05-29T03:56:09.662496+00:00
827
false
```\nclass Solution {\npublic:\n int power(int base, int exponent){\n if(exponent==0)return 1;\n int halfWork = power(base,exponent/2);\n if(exponent&1)return halfWork*halfWork*base;\n return halfWork*halfWork;\n }\n \n bool dfs(int u, int n, int k, vector<vector<bool>> &vis, string &temp, int edges){\n if(edges == power(k,n)){\n return true;\n }\n for(int nextDigit=0;nextDigit<k;nextDigit++){\n if(!vis[u][nextDigit]){\n vis[u][nextDigit] = 1;\n int v = u*k+nextDigit;\n v %= power(k,n-1);\n temp.push_back(\'0\' + nextDigit);\n bool res = dfs(v, n, k, vis, temp, edges+1);\n if(res)return res;\n temp.pop_back();\n vis[u][nextDigit] = 0;\n }\n }\n return false;\n }\n string crackSafe(int n, int k) {\n string temp="";\n for(int i=0;i<n-1;i++)temp.push_back(\'0\');\n vector<vector<bool>>vis(power(k,n-1), vector<bool>(k,false));\n dfs(0, n, k, vis, temp, 0);\n return temp;\n }\n};\n```
1
0
['Depth-First Search', 'C']
0
cracking-the-safe
C++ short and sweet
c-short-and-sweet-by-galster-7qmc
\nclass Solution {\npublic:\n unordered_set<string> found;\n int totalStates = 0;\n \n string crackSafe(const string &curr, const string &state, int
galster
NORMAL
2021-03-22T03:48:32.356846+00:00
2021-03-22T03:48:32.356875+00:00
333
false
```\nclass Solution {\npublic:\n unordered_set<string> found;\n int totalStates = 0;\n \n string crackSafe(const string &curr, const string &state, int k){\n found.insert(state);\n \n if(found.size() == totalStates){\n return curr;\n }\n \n for(int i = 0; i < k; ++i){\n string newState = state.substr(1) + string(1, i + \'0\');\n \n if(!found.count(newState)){\n string res = crackSafe(curr + string(1,i + \'0\'),newState,k);\n \n if(res.empty() == false){\n return res;\n }\n }\n }\n \n found.erase(state);\n return "";\n }\n\n string crackSafe(int n, int k) {\n totalStates = pow(k,n);\n return crackSafe(string(n,\'0\'),string(n,\'0\'),k); \n }\n};\n```
1
0
[]
0
cracking-the-safe
python dfs + greedy
python-dfs-greedy-by-shuuchen-1g3v
```\nclass Solution:\n def crackSafe(self, n: int, k: int) -> str:\n \n def dfs(s, seen):\n \n if len(seen) == kn:\n
shuuchen
NORMAL
2021-03-06T04:05:22.669350+00:00
2021-03-06T04:05:22.669384+00:00
362
false
```\nclass Solution:\n def crackSafe(self, n: int, k: int) -> str:\n \n def dfs(s, seen):\n \n if len(seen) == k**n:\n return s\n \n for x in range(k):\n new_s = (s[-n+1:] if n > 1 else \'\') + str(x)\n if new_s in seen:\n continue\n \n seen.add(new_s)\n s_x = dfs(s + str(x), seen)\n if s_x:\n return s_x\n seen.remove(new_s)\n \n return None\n \n return dfs(\'0\'*n, set([\'0\'*n]))
1
0
[]
0
cracking-the-safe
Proof: why Eulerian Circuit works, and a strict O(k^n) solution
proof-why-eulerian-circuit-works-and-a-s-dd99
Most solutions assume Eulerian Circuit can generate De Brujin Sequence without proof.\nHere is a nice one:\n\nhttp://www-users.math.umn.edu/~reiner/Classes/DeBr
cal_apple
NORMAL
2020-12-06T17:58:48.734100+00:00
2020-12-06T17:59:32.111955+00:00
371
false
Most solutions assume Eulerian Circuit can generate De Brujin Sequence without proof.\nHere is a nice one:\n\nhttp://www-users.math.umn.edu/~reiner/Classes/DeBruijn.pdf\n\n\nPlus a strict` O(k^n)` solution\n\n```\n\n vector<vector<int>> graph;\n string res;\n int N, k;\n \n // de Brujin sequence can be constructed by Hamilton path of k^n nodes, or Euler path of k^(n-1) nodes\n \n void dfs(int u) {\n while(graph[u].size()) {\n int v = graph[u].back();\n graph[u].pop_back();\n dfs((u * k + v) % N); // from "000" to "001" if v=1\n res += v + \'0\'; // Euler path, record visited edge here\n }\n }\npublic:\n string crackSafe(int n, int k) {\n this->N = pow(k, n-1); // num of nodes\n this->k = k; // num of edges of each node\n \n // build graph\n graph.resize(N);\n for (int u = 0; u < N; u++) {\n for (int v = 0; v < k; v++) {\n graph[u].push_back(v);\n } \n }\n \n dfs(0);\n \n // res now contains edges in reversed order, total length = k^n + (n-1)\n return res+string(n-1, \'0\');\n }
1
0
[]
1
cracking-the-safe
Easy to understand java solution using DFS
easy-to-understand-java-solution-using-d-vbqe
\nclass Solution {\n public String crackSafe(int n, int k) {\n \n // k possibilities for each of the n digits - total number of combination is
podurisaicharan
NORMAL
2020-08-21T00:31:25.334512+00:00
2020-08-21T00:32:34.432931+00:00
235
false
```\nclass Solution {\n public String crackSafe(int n, int k) {\n \n // k possibilities for each of the n digits - total number of combination is k*k*k...(ntimes) = k^n\n int total = (int)Math.pow(k, n);\n \n // start with the basic one "000000" (n digits)\n StringBuffer sb = new StringBuffer();\n for(int i=0; i<n; i++)\n {\n sb.append(\'0\');\n }\n \n Set<String> visited = new HashSet<String>(); \n StringBuffer result = new StringBuffer(sb);\n \n boolean[] isFound = new boolean[1];\n\n dfs(sb.toString(), result, total, k, visited, isFound);\n return result.toString();\n }\n \n private void dfs(String source, StringBuffer result, int total, int k, Set<String> visited, boolean[] isFound)\n { \n \n visited.add(source);\n \n if(visited.size() == total)\n {\n isFound[0] = true;\n return;\n }\n \n for(int i=0; i<k; i++)\n {\n StringBuffer sb2 = new StringBuffer(source);\n\n // delete first character and append each of 0...k-1 to the last and see if it is visited or not\n sb2.deleteCharAt(0);\n sb2.append(i);\n result.append(i);\n \n if(!visited.contains(sb2.toString()))\n dfs(sb2.toString(), result, total, k, visited, isFound);\n \n // No need to traverse once we visted all the k^n possibilities\n if(isFound[0])\n break;\n \n\t\t\t// If we reach here it means we are unable to traverse all possibilities using this string - remove it from result\n result.deleteCharAt(result.length()-1);\n }\n \n visited.remove(source);\n }\n}\n```
1
0
[]
0
cracking-the-safe
c# DFS
c-dfs-by-lchunlosaltos-yuin
\npublic class Solution {\n //each password is n digits; \n //treat the password as nodes;\n //visit every nodes once to create the password with all p
lchunlosaltos
NORMAL
2020-05-08T02:40:52.110981+00:00
2020-05-08T02:40:52.111028+00:00
181
false
```\npublic class Solution {\n //each password is n digits; \n //treat the password as nodes;\n //visit every nodes once to create the password with all possible answers in one string.\n //use DFS; the node should be seeds with n-1 "0" and append a number from k each time;\n //Make sure we dont duplicate visit the same node;\n //so store all the nodes visited in a hashset visited;\n //00, 01,11,10 can be 00110\n public HashSet<string> visited = new HashSet<string>();\n StringBuilder ans = new StringBuilder(); \n public string CrackSafe(int n, int k) {\n //max length of the output is k^n + (n-1)\n string node = new string(\'0\',n-1);\n DFS(node,k);\n ans.Append(node);\n return ans.ToString();\n }\n public void DFS(string node, int k)\n {\n for(int i = 0; i < k; i++) //i from 0 .. up to k-1 possible digits;\n {\n int x = i;\n string next = node + x;\n if (!visited.Contains(next))\n {\n visited.Add(next);\n DFS(next.Substring(1), k); // only pass in the n-1 substring; \n ans.Append(x);\n }\n } \n }\n}\n```
1
0
[]
0
cracking-the-safe
[Python] Short dfs()
python-short-dfs-by-hjscoder-li6v
Explanation\n\nStart from "0"n, using a slide window idea, everytime the window moves toward right for 1 digit, for this digit we have k options to create a new
hjscoder
NORMAL
2020-05-06T00:45:00.817286+00:00
2020-05-06T00:45:00.817338+00:00
239
false
**Explanation**\n\nStart from "0"*n, using a slide window idea, everytime the window moves toward right for 1 digit, for this digit we have k options to create a new string that have never being created before. So we continue creating strings until the amount of unique strings equals to the maxium possible amount => total = k^n\n\nOnce we reach the maxium amount, return and do a backtrack to add all the process "char" into a process-string \nwith this process-string and start-string we can create all the possible password.\n\n\n def crackSafe(self, n: int, k: int) -> str: \n\t\ttotal = k**n; created = set(); res = []\n\t\tdef dfs(prev):\n\t\t\tif len(created) == total:\n\t\t\t\treturn \n\t\t\tfor d in map(str, range(k)):\n\t\t\t\tnext_ = (prev + d)[1:] \n\t\t\t\tif next_ not in created:\n\t\t\t\t\tcreated.add(next_)\n\t\t\t\t\tdfs(next_)\n\t\t\t\t\tres.append(d)\n\t\tstart = \'0\'*n; created.add(start)\n\t\tdfs(start)\n\t\treturn \'\'.join(res)+start
1
0
[]
0
cracking-the-safe
Simple Java Solution[BackTracking]
simple-java-solutionbacktracking-by-xlay-hf9a
\nclass Solution {\n Set<String> visited = new HashSet<>();\n int total = 0;\n StringBuilder ans = new StringBuilder();\n int k;\n private boolea
xlayman
NORMAL
2020-04-26T01:20:29.958376+00:00
2020-04-26T01:20:29.958408+00:00
159
false
```\nclass Solution {\n Set<String> visited = new HashSet<>();\n int total = 0;\n StringBuilder ans = new StringBuilder();\n int k;\n private boolean dfs(String start){\n if(visited.size() == total)\n return true;\n for(int i = 0; i < k; i++){\n String curr = start.substring(1) + Integer.toString(i);\n if(!visited.contains(curr)){\n visited.add(curr);\n ans.append(Integer.toString(i));\n if(dfs(curr))\n return true;\n ans.setLength(ans.length() - 1); \n visited.remove(curr);\n }\n }\n return false; \n }\n public String crackSafe(int n, int k) {\n StringBuilder start = new StringBuilder();\n total = (int)Math.pow(k, n);\n this.k = k;\n for(int i = 0; i < n; i++){\n start.append("0");\n }\n ans.append(start.toString());\n visited.add(start.toString());\n dfs(start.toString());\n return ans.toString();\n }\n}\n```
1
0
[]
0
cracking-the-safe
C# Solution DFS
c-solution-dfs-by-leonhard_euler-g259
\npublic class Solution \n{\n public string CrackSafe(int n, int k) \n {\n var sb = new StringBuilder();\n for (int i = 0; i < n; i++) \n
Leonhard_Euler
NORMAL
2020-01-03T07:52:31.793017+00:00
2020-01-03T07:52:31.793068+00:00
179
false
```\npublic class Solution \n{\n public string CrackSafe(int n, int k) \n {\n var sb = new StringBuilder();\n for (int i = 0; i < n; i++) \n sb.Append(\'0\');\n DFS(n, k, sb, new HashSet<string>(new string[] {sb.ToString()}));\n return sb.ToString();\n }\n \n private bool DFS(int n, int k, StringBuilder sb, HashSet<string> visited) \n {\n if (visited.Count == (int) (Math.Pow(k, n))) return true;\n var prev = sb.ToString(sb.Length - (n - 1), n - 1);\n for (int i = 0; i < k; i++) \n {\n var next = prev + i;\n if (visited.Add(next)) \n {\n sb.Append(i);\n if (DFS(n, k, sb, visited)) \n return true;\n else \n {\n visited.Remove(next);\n sb.Remove(sb.Length - 1, 1);\n }\n }\n }\n \n return false;\n }\n}\n```
1
0
[]
0
cracking-the-safe
Simple C++ solution with 2 for loops
simple-c-solution-with-2-for-loops-by-em-ozw6
\nclass Solution \n{\n public:\n string crackSafe(int n, int k) \n {\n string result(n,\'0\');\n unordered_set<string> v;\n for(in
eminem18753
NORMAL
2019-12-05T05:44:01.428545+00:00
2019-12-05T05:53:21.668706+00:00
219
false
```\nclass Solution \n{\n public:\n string crackSafe(int n, int k) \n {\n string result(n,\'0\');\n unordered_set<string> v;\n for(int i=0;i<pow(k,n)-1;i++)\n {\n for(int j=k-1;j>-1;j--)\n {\n string temp=result.substr((int)result.size()-n+1,n-1)+to_string(j);\n if(v.find(temp)==v.end())\n {\n result+=to_string(j);\n v.insert(temp);\n break;\n }\n }\n }\n return result;\n }\n};\n```
1
0
[]
0
cracking-the-safe
A Java Solution
a-java-solution-by-david137-id5x
\nclass Solution {\n private Set<String> visited = new HashSet<String>();\n private String ans = "";\n private int goal=1;\n \n public String cra
david137
NORMAL
2019-12-01T21:43:55.359853+00:00
2019-12-01T21:43:55.359892+00:00
256
false
```\nclass Solution {\n private Set<String> visited = new HashSet<String>();\n private String ans = "";\n private int goal=1;\n \n public String crackSafe(int n, int k) {\n visited.clear();\n goal = 1;\n ans="";\n for(int i=0; i < n; i++) {\n goal = goal*k;\n }\n\t /* n-1 zeros are created as the starting root for the dfs() function.\n\t for n=2, k=2 "0" will be created and passed into dfs() as the root.\n\t within the dfs() function, "00" = "0"+"0" will be checked to see if it is a new item.\n\t If so, the second "0" will be used as the root for the following dfs() function call.\n\t Within the second dfs() function call, "00" is no longer a new item and "01" will be \n\t a new item. This time "1" will be used as the root for the 3rd dfs() function call.\n\t if 4 (2^2=4) new items have been visited, the dfs() function will return.\n\t The recursive dfs (Depth First Search) function processes digit sequence from left to right, \n\t the unravelling of the recursive call requires adding digits (e.g., "0" for the 1st dfs() call and "1"\n\t\tfor the 2nd dfs() call) from the left to the answer string. \n\t At the end, the starting n-1 zeros are added from the left to the answer string.\n\t */\n\t \n\t \n StringBuilder sb = new StringBuilder();\n for(int i=0; i < n-1; i++) {\n sb.append("0");\n }\n dfs(sb.toString(), n, k);\n ans = sb.toString() + ans; // add back first n-1 "0"s\n return ans;\n }\n \n public void dfs(String root, int n, int k) {\n if(visited.size() == goal) return;\n for(int i=0; i < k; i++) {\n String node = root + i;\n if(! visited.contains(node)) {\n visited.add(node);\n dfs(node.substring(1), n, k);\n ans = i + ans; // add back digits in reversed order\n }\n }\n }\n}\n```
1
0
[]
0
cracking-the-safe
DFS Hamilton Cycle with explanation - JavaScript
dfs-hamilton-cycle-with-explanation-java-jy0q
\n 1. Get all perms of 0 ... k - 1 of length n (these are nodes of the graph)\n 2. Make a graph where each connection represents an overlap (Hamilton Cycle). A
auwdish
NORMAL
2019-11-02T14:23:24.135234+00:00
2019-11-02T14:28:13.668430+00:00
1,622
false
\n 1. Get all perms of 0 ... k - 1 of length n (these are nodes of the graph)\n 2. Make a graph where each connection represents an overlap (Hamilton Cycle). An overlap means that if we can add one number to the end of a permutation and another permutation is made in the process, then these two permutations overlap. For example, 11 and 12 overlap becuase we can add 2 to 11 and 112 includes 12. Also, 11 overlaps with itself becuase if we add 1 to the end we have two 11s.\n 3. Traverse a path that reaches all nodes (Hamilton Path) while building the password. For each edge we add the non overlapping part of the two permutions.\n\n![image](https://assets.leetcode.com/users/awdavids/image_1572704728.png)\n\n \n```javascript\nvar crackSafe = function(n, k) {\n if (k < 1 || n === 0) return \'\'\n let perms = getPerms(n, k)\n let graph = buildGraph(perms, k)\n let used = new Set\n let pass = dfs()\n return pass\n \n function dfs(current = perms[0], nextPerm = perms[0]) {\n used.add(nextPerm)\n if (used.size === perms.length) {\n return current\n }\n \n const children = graph[nextPerm]\n for (let overlapPerm of children) {\n if (used.has(overlapPerm)) continue\n let nonOverlap = overlapPerm.slice(overlapPerm.length - 1)\n let password = dfs(current + nonOverlap, overlapPerm)\n if (password.length) {\n return password\n }\n }\n \n used.delete(nextPerm)\n return \'\'\n }\n};\n\nfunction buildGraph(perms, k) {\n let graph = {}\n for (let perm of perms) {\n graph[perm] = []\n }\n for (let perm1 of perms) {\n for (let i = 0; i < k; i++) {\n let nextPerm = perm1.slice(1) + i\n for (let perm2 of perms) {\n if (nextPerm === perm2) {\n graph[perm1].push(perm2)\n }\n }\n }\n }\n return graph\n}\n\nfunction getPerms(n, k) {\n let perms = []\n getPermsRec()\n return perms\n \n function getPermsRec(curr = \'\') {\n if (curr.length === n) {\n perms.push(curr)\n return\n }\n for (let i = 0; i < k; i++) {\n getPermsRec(curr + i)\n }\n }\n}\n```
1
0
[]
0
cracking-the-safe
Python, easy to understand DFS
python-easy-to-understand-dfs-by-roozbeh-lvdf
My approach was calculate all the possible sequence for K and N, and then try to find the shortest one. Each node in the DFS is one sequence, and the search is
roozbeh3
NORMAL
2019-10-08T01:48:49.704144+00:00
2019-10-08T01:48:49.704189+00:00
197
false
My approach was calculate all the possible sequence for K and N, and then try to find the shortest one. Each node in the DFS is one sequence, and the search is trying to find the next sequence that has N-1 comming characters with it.\n\nThe runtime was slow, but the memory usage was better than 100% of the submissions.\n\n```\nclass Solution(object):\n def find_all_seqs(self, n, k):\n if n == 0:\n return []\n \n if n == 1:\n return map(str, range(0, k))\n \n rest = self.find_all_seqs(n-1, k)\n ret = []\n for i in map(str, range(0, k)):\n for r in rest:\n ret.append(i + r)\n \n return ret\n \n def crackSafe(self, n, k):\n """\n :type n: int\n :type k: int\n :rtype: str\n """\n if n == 0:\n return ""\n \n if n == 1:\n return "".join(map(str, range(0, k)))\n \n all_seqs = self.find_all_seqs(n, k)\n root = all_seqs[0]\n queue = [(root, all_seqs[1:])]\n process_count = 0\n while queue:\n cur_seq, remainings = queue.pop()\n process_count += 1\n if not remainings:\n return cur_seq\n \n rest_of_seq = cur_seq[-n+1:]\n for idx, s in enumerate(remainings):\n if rest_of_seq == s[:-1]:\n queue.append((cur_seq + s[-1], remainings[:idx] + remainings[idx+1:]))\n \n return "N/A"\n \n```
1
0
[]
1
cracking-the-safe
No Code, Proof of Correctness for Greedy Dequeue Approach
no-code-proof-of-correctness-for-greedy-uudbs
This is basically a re-explanation and expansion of the very excellent proof here.\n\nFirst we define a directed graph structure where the nodes are every possi
supermatthew
NORMAL
2019-08-27T15:37:47.001280+00:00
2019-11-20T16:58:14.458499+00:00
214
false
This is basically a re-explanation and expansion of [the very excellent proof here](https://leetcode.com/problems/cracking-the-safe/discuss/110261/Deque-solution-with-proof).\n\nFirst we define a directed graph structure where the nodes are every possible length-n sequence made from the alphabet {0,1,...,k-1}. Two nodes are connected if we can basically slide a length (n-1) window from one node to the next: for instance, with n = 5 and k = 2, we would have the edge 00101 -> 01011. In other words, all edges are situated thus:\n![image](https://assets.leetcode.com/users/supermatthew/image_1566917203.png)\nwhere W is some word of length n-1.\n\nNow a string that contains all possible passwords, is exactly the same as a path in this graph that visits every node at least once: given a string, just slide the window rightwards one unit at a time, to visualize traversing the path; conversely, given a path in the graph one can initialize a string with the first node\'s value, and then add one letter at a time depending on where the path takes you.\n\nNow the best possible answer is a path that visits each node exactly once. This means adjacent passwords have the most overlap possible, and we really can\'t improve upon this.\n\nThe magic is that such a path actually exists. (Mini exercise: can you calculate the length of the resulting string in terms of n and k?)\n\n**ALGORITHM**:\n```\n1. Initialize a deque (double-ended queue) with a single node\n2. WHILE (deque doesn\'t contain every node):\n\t(i) IF the end of the queue, call it X, has an edge X->Y with Y not yet in the queue,\n\t\t\tTHEN append Y to the queue.\n\t(ii) ELSE (every Y satisfying X->Y is already in the queue)\n\t\t\tCLAIM: X must be connected to the front of the queue, call it P; i.e., X->P\n\t\t\tTHEN we move P to the end of the queue.\n```\nSo we need to prove 2 assertions:\nA) in case 2(ii), we indeed have that X->P.\nB) the algorithm terminates.\n\nThe proof of (A) is essentially a counting argument. Denote the end of the queue by X = aW, and to prove that this is joined to the front of the queue, P, we must show that P = Wb for some letter b. Suppose for contradiction that this is not the case. Because we are in situation 2(ii), we have that every node with prefix W, denoted (W-) is already in the dequeue, and since the front of the dequeue is *not* of the form $Wb$, then every (W-) is preceded by a node with suffix W, (~W). This is very nearly a coupling between such nodes, except that the end of the queue is one of the (~W) nodes:\n![image](https://assets.leetcode.com/users/supermatthew/image_1566920224.png)\n\nSo the (~W) nodes outnumber the (W-) nodes by 1. But since the total number of (~W)\'s and (W-)\'s in the graph is equal (there are k of each), this means there must still be an unused (W-) that we can place after the (aW) at the end, a contradiction since we were supposed to be in case 2(ii).\n\n\nThe proof of (B) is as follows: Observe that we never add a duplicate node in our algorithm. Also observe that the size of the queue either increases because of a new node, or stays the same, for each iteration of the while loop. Now suppose for contradiction that some node Z never gets added to the queue. Then the queue\'s size must stabilize at after a certain point, since if it kept growing, then eventually Z would be added (there are after all, only finitely many different nodes). What does it mean for the size of the queue to *stabilize*? This means that every iteration of the while loop, we are just moving the front of the queue to the end, in an endless cycle. Now observe that the graph is path connected in the sense that every node can be joined to every other node (for instance, with n=5 and k=2, the nodes 00000 and 11111 are connected as: 00000->00001->00011->00111->01111->11111; mini exercise: what is the length of the shortest path joining two arbitrary nodes in terms of n and those nodes?)\n\nSo let X be any node in the queue; then there is some path X=X[0]->X[1]->X[2]->....->X[m]=Z. Note that the parent of Z in this path, X[m-1], can **not** be in the queue, since otherwise the endless cycling would have eventually put X[m-1] at the end, after which we would have appended X[m]=Z. For the same reason, X[m-2] can\'t be in the queue, since cycling would have eventually caused us to append X[m-1] eventually. Continuing this reasoning, we conclude X[0]=X wasn\'t in the queue, a contradiction since X was in the queue.\n
1
0
[]
0
cracking-the-safe
N-ary solution [C++]
n-ary-solution-c-by-timd000-kctg
Consider traversing a n-ary tree. There are k^n times of unique traverses starting from the root. The tree has n level. And since each parent node has exact k c
timd000
NORMAL
2019-07-16T05:23:30.976283+00:00
2019-07-16T05:23:30.976328+00:00
186
false
Consider traversing a n-ary tree. There are k^n times of unique traverses starting from the root. The tree has n level. And since each parent node has exact k childs, including the root node, each parent node of a leaf node will be visited k times from other n-1 level paths. That means all k^n paths could be fulfilled after traversals. One of traversal proposals is the following:\n```\nstring crackSafe(int n, int k) {\n int index = 0;\n string result(n - 1, \'0\');\n unordered_map<string, int> nextDigit;\n \n while (true) {\n string key = result.substr(index);\n \n if (nextDigit.find(key) == nextDigit.end()) {\n nextDigit[key] = k - 1;\n }\n if (nextDigit[key] < 0) {\n break;\n }\n result.push_back(nextDigit[key] + \'0\');\n nextDigit[key]--;\n index++;\n }\n \n return result;\n }\n```
1
0
[]
1
find-indices-with-index-and-value-difference-ii
[Java/C++/Python] One Pass, O(1) Space
javacpython-one-pass-o1-space-by-lee215-bjzp
Intuition\nThe brute force solution is two for loop to check all pairs.\n\nIf index difference d = 1,\nit will be more straight forward,\nwe can iterate the arr
lee215
NORMAL
2023-10-15T04:02:34.999875+00:00
2023-10-15T04:02:34.999904+00:00
4,767
false
# **Intuition**\nThe brute force solution is two `for` loop to check all pairs.\n\nIf index difference `d = 1`,\nit will be more straight forward,\nwe can iterate the array `A`,\nand keep minimum and maximum in the prefix of `A`.\n<br>\n\n# **Explanation**\nFor `d > 1`, we can do the same thing.\n`mini` is the index of minimum element in the prefix of `A`.\n`maxi` is the index of maximum element in the prefix of `A`.\n\nIterate `A[i]` from `A[d]` to `A[n - 1]`,\nWe compare `A[i - d]` with `A[mini]` and `A[maxi]`,\nand update `mini` and `maxi`.\n\nThen check if `A[i]` has enough value difference from `A[mini]` and `A[maxi]`.\nIf so, we return the pair.\n\nFinally, if we find nothing, we return `[-1, -1]`.\n<br>\n\n# **Complexity**\nTime `O(n)`\nSpace `O(1)`\n<br>\n\n**Java**\n```java\n public int[] findIndices(int[] A, int d, int v) {\n int mini = 0, maxi = 0, n = A.length;\n for (int i = d; i < n; i++) {\n if (A[i - d] < A[mini]) mini = i - d;\n if (A[i - d] > A[maxi]) maxi = i - d;\n if (A[i] - A[mini] >= v) return new int[] {mini, i};\n if (A[maxi] - A[i] >= v) return new int[] {maxi, i};\n }\n return new int[] { -1, -1};\n }\n```\n\n**C++**\n```cpp\n vector<int> findIndices(vector<int>& A, int d, int v) {\n int mini = 0, maxi = 0, n = A.size();\n for (int i = d; i < n; i++) {\n if (A[i - d] < A[mini]) mini = i - d;\n if (A[i - d] > A[maxi]) maxi = i - d;\n if (A[i] - A[mini] >= v) return {mini, i};\n if (A[maxi] - A[i] >= v) return {maxi, i};\n }\n return { -1, -1};\n }\n```\n\n**Python**\n```py\n def findIndices(self, A: List[int], d: int, valueDifference: int) -> List[int]:\n mini = maxi = 0\n for i in range(d, len(A)):\n if A[i - d] < A[mini]: mini = i - d\n if A[i - d] > A[maxi]: maxi = i - d\n if A[i] - A[mini] >= valueDifference: return [mini, i]\n if A[maxi] - A[i] >= valueDifference: return [maxi, i]\n return [-1, -1]\n```\n
104
3
['C', 'Python', 'Java']
18
find-indices-with-index-and-value-difference-ii
Map vs. Min/Max
map-vs-minmax-by-votrubac-fut1
Min/Max\nI initially came up with the map solution, only then to realize that we can just store min and max value.\nC++\ncpp\nvector<int> findIndices(vector<int
votrubac
NORMAL
2023-10-15T04:00:41.794081+00:00
2023-10-15T04:12:09.214759+00:00
1,739
false
## Min/Max\nI initially came up with the map solution, only then to realize that we can just store min and max value.\n**C++**\n```cpp\nvector<int> findIndices(vector<int>& nums, int indexDifference, int valueDifference) {\n int min_j = 0, max_j = 0;\n for (int i = indexDifference, j = 0; i < nums.size(); ++i, ++j) {\n min_j = nums[min_j] < nums[j] ? min_j : j;\n max_j = nums[max_j] > nums[j] ? max_j : j;\n if (abs(nums[i] - nums[min_j]) >= valueDifference)\n return {min_j, i};\n if (abs(nums[i] - nums[max_j]) >= valueDifference)\n return {max_j, i};\n }\n return {-1, -1};\n}\n```\n\n## Map\nWe go left-to-right, storing eligible numbers in a map (with their indices).\nThen, we binary-search in the map for numbers:\n- equal or higher than `nums[i] + valueDifference`\n- equal or lower than `nums[i] - valueDifference`\n \n**C++**\n```cpp\nvector<int> findIndices(vector<int>& nums, int indexDifference, int valueDifference) {\n map<int, int> m;\n for (int i = indexDifference; i < nums.size(); ++i) {\n m[nums[i - indexDifference ]] = i - indexDifference;\n auto it = m.lower_bound(nums[i] + valueDifference);\n if (it != end(m))\n return {i, it->second };\n it = m.upper_bound(nums[i] - valueDifference);\n if (it != begin(m))\n return {i, prev(it)->second };\n }\n return {-1, -1};\n}\n```
22
1
['C']
5
find-indices-with-index-and-value-difference-ii
Using priority queue || Very simple and easy to understand solution
using-priority-queue-very-simple-and-eas-5bg2
\n# Approach \n- Find the largest and smallest number which is away from i by indDiff distance. Then check if the smallest and ith or larget and ith having a di
kreakEmp
NORMAL
2023-10-15T04:01:35.004781+00:00
2023-10-15T04:23:30.254747+00:00
2,864
false
\n# Approach \n- Find the largest and smallest number which is away from i by indDiff distance. Then check if the smallest and ith or larget and ith having a diff greater than valueDiff\n- To do so we use min heap and max heap to find max and min after (i+ indDiff)th element\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> findIndices(vector<int>& nums, int indDiff, int valueDiff) {\n priority_queue<pair<int,int>> pq;\n priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> mpq;\n for(auto i = 0; i < nums.size(); ++i) { pq.push({nums[i], i}); mpq.push({nums[i], i}); }\n for(int i = 0; i + indDiff < nums.size(); ++i){\n while(pq.size() && pq.top().second < i+indDiff) pq.pop();\n while(mpq.size() && mpq.top().second < i+indDiff) mpq.pop();\n if(pq.size() && abs(nums[i] - pq.top().first) >= valueDiff ) return {i, pq.top().second};\n if(mpq.size() && abs(nums[i] - mpq.top().first) >= valueDiff ) return {i, mpq.top().second};\n }\n \n return {-1,-1};\n }\n};\n```
18
2
['C++']
3
find-indices-with-index-and-value-difference-ii
Easy Video Solution (Brute->Optimal) 🔥 || Suffix Max-Min 🔥 || C++,JAVA,PYTHON
easy-video-solution-brute-optimal-suffix-kyfv
Intuition\n Describe your first thoughts on how to solve this problem. \nTry to think about prefix and suffix\n\n# Detailed and easy Video Solution\n\nhttps://y
ayushnemmaniwar12
NORMAL
2023-10-15T05:12:02.280461+00:00
2023-10-19T14:55:47.942978+00:00
1,687
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTry to think about prefix and suffix\n\n# ***Detailed and easy Video Solution***\n\nhttps://youtu.be/neaCFDgBBn8\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe code finds indices in an array where the absolute difference between elements is at least \'value\' and the distance between indices is at least \'index.\' It optimizes by precomputing maximum and minimum values to reduce computation. The result is a pair of indices meeting the criteria.\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(N+N)->O(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(N)\n# Brute Force\n\n```C++ []\nclass Solution {\npublic:\n vector<int> findIndices(vector<int>& v, int index, int value) {\n int n=v.size();\n vector<int>ans(2,-1);\n for(int i=0;i<n;i++)\n {\n for(int j=i;j<n;j++)\n {\n if(abs(i-j)>=index && abs(v[i]-v[j])>=value)\n {\n ans[0]=i;\n ans[1]=j;\n break;\n }\n }\n }\n return ans;\n }\n};\n```\n```python []\nclass Solution:\n def findIndices(self, v, index, value):\n n = len(v)\n ans = [-1, -1]\n for i in range(n):\n for j in range(i, n):\n if abs(i - j) >= index and abs(v[i] - v[j]) >= value:\n ans[0] = i\n ans[1] = j\n break\n return ans\n\nif __name__ == "__main__":\n solution = Solution()\n v = [1, 2, 3, 4, 5]\n index = 2\n val = 2\n result = solution.findIndices(v, index, val)\n print(result)\n\n```\n```java []\n public int[] findIndices(int[] v, int index, int value) {\n int n = v.length;\n int[] ans = new int[]{-1, -1};\n for (int i = 0; i < n; i++) {\n for (int j = i; j < n; j++) {\n if (Math.abs(i - j) >= index && Math.abs(v[i] - v[j]) >= value) {\n ans[0] = i;\n ans[1] = j;\n break;\n }\n }\n }\n return ans;\n }\n```\n\n\n# Optimal Code\n```C++ []\nclass Solution {\npublic:\n vector<int> findIndices(vector<int>& v, int index, int value) {\n int n=v.size();\n vector<pair<int,int>>res(n);\n res[n-1].first=v[n-1];\n res[n-1].second=v[n-1];\n for(int i=n-2;i>=0;i--)\n {\n res[i].first=max(v[i],res[i+1].first);\n res[i].second=min(v[i],res[i+1].second);\n }\n vector<int>ans(2,-1);\n for(int i=0;i<n;i++)\n {\n int j=i+index;\n if(j<n && (abs(v[i]-res[j].first)>=value || abs(v[i]-res[j].second)>=value))\n { \n \n ans[0]=i;\n for(int k=j;k<n;k++)\n { \n \n if(abs(v[i]-v[k])>=value)\n {\n ans[1]=k;\n break;\n }\n }\n break;\n }\n }\n return ans;\n }\n};\n```\n```python []\n def findIndices(self, v, index, value):\n n = len(v)\n maxValues = [0] * n\n minValues = [0] * n\n ans = [-1, -1]\n\n maxValues[n - 1] = v[n - 1]\n minValues[n - 1] = v[n - 1]\n\n for i in range(n - 2, -1, -1):\n maxValues[i] = max(v[i], maxValues[i + 1])\n minValues[i] = min(v[i], minValues[i + 1])\n\n for i in range(n):\n j = i + index\n if j < n and (abs(v[i] - maxValues[j]) >= value or abs(v[i] - minValues[j]) >= value):\n ans[0] = i\n for k in range(j, n):\n if abs(v[i] - v[k]) >= value:\n ans[1] = k\n break\n break\n\n return ans\n```\n```java []\n public int[] findIndices(int[] v, int index, int value) {\n int n = v.length;\n int[] maxValues = new int[n];\n int[] minValues = new int[n];\n int[] ans = new int[]{-1, -1};\n\n maxValues[n - 1] = v[n - 1];\n minValues[n - 1] = v[n - 1];\n\n for (int i = n - 2; i >= 0; i--) {\n maxValues[i] = Math.max(v[i], maxValues[i + 1]);\n minValues[i] = Math.min(v[i], minValues[i + 1]);\n }\n\n for (int i = 0; i < n; i++) {\n int j = i + index;\n if (j < n && (Math.abs(v[i] - maxValues[j]) >= value || Math.abs(v[i] - minValues[j]) >= value)) {\n ans[0] = i;\n for (int k = j; k < n; k++) {\n if (Math.abs(v[i] - v[k]) >= value) {\n ans[1] = k;\n break;\n }\n }\n break;\n }\n }\n\n return ans;\n }\n```\n\n# ***If you like the solution Please Upvote and subscribe to my youtube channel***\n***It Motivates me to record more videos***\n\n*Thank you *\uD83D\uDE00\n\n
17
1
['Suffix Array', 'C++', 'Java', 'Python3']
4
find-indices-with-index-and-value-difference-ii
c++||Using Set || Very Easy
cusing-set-very-easy-by-baibhavkr143-79lf
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
baibhavkr143
NORMAL
2023-10-15T04:02:41.840096+00:00
2023-10-15T04:02:41.840118+00:00
1,559
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> findIndices(vector<int>& nums, int idx, int v) {\n set<pair<int,int>>st;\n for(int i=0;i<nums.size();i++)\n {\n if(i-idx<0)continue;\n st.insert({nums[i-idx],i-idx});\n \n auto val1=*st.begin();\n auto val2=*st.rbegin();\n \n if(abs(nums[i]-val1.first)>=v)\n {\n return {val1.second,i};\n }\n if(abs(nums[i]-val2.first)>=v)return {val2.second,i};\n }\n return {-1,-1};\n }\n};\n```
13
1
['C++']
3
find-indices-with-index-and-value-difference-ii
[Python3] greedy
python3-greedy-by-ye15-ro0f
\n\nclass Solution:\n def findIndices(self, nums: List[int], indexDifference: int, valueDifference: int) -> List[int]:\n mn = mx = -1 \n for i,
ye15
NORMAL
2023-10-15T04:01:13.256444+00:00
2023-10-15T04:01:13.256465+00:00
556
false
\n```\nclass Solution:\n def findIndices(self, nums: List[int], indexDifference: int, valueDifference: int) -> List[int]:\n mn = mx = -1 \n for i, x in enumerate(nums): \n if i >= indexDifference: \n if mn == -1 or nums[i-indexDifference] < nums[mn]: mn = i-indexDifference\n if mx == -1 or nums[i-indexDifference] > nums[mx]: mx = i-indexDifference\n if x - nums[mn] >= valueDifference: return [mn, i]\n if nums[mx] - x >= valueDifference: return [mx, i]\n return [-1, -1]\n```
10
0
['Python3']
0
find-indices-with-index-and-value-difference-ii
Best solution.✅NO Priority queue,NO sliding window. Just plane logic✅✅
best-solutionno-priority-queueno-sliding-c7on
Intuition\nIf we carefully see the problem, it may look like we need to store a lot many things if we are at index i, then we need to know every damn thing abou
adiityyya
NORMAL
2023-10-16T20:37:21.232906+00:00
2023-10-16T20:38:22.676159+00:00
298
false
# Intuition\nIf we carefully see the problem, it may look like we need to store a lot many things if we are at index i, then we need to know every damn thing about the values at indexes i - id, but that\'s not the case.\n\n# Approach\nWe will just keep a record of maximum, and minimum element in the range [0,i-id] if we are currently at index i. If we have this info, we can check whether the max element is satisfying the condtion or the min element. because everyhing in between the range of these two, are just useless.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> findIndices(vector<int>& nums, int id, int vd) {\n int n=nums.size();\n\n vector<int> ans;\n int ind1=0;\n int ind2=0;\n int x=nums[0],y=nums[0];\n //x, ind1->max element record\n //y, ind2->min element record\n for(int i=id;i<n;i++){\n if(nums[i-id] > x){\n x = nums[i-id];\n ind1 = i-id;\n }\n if(nums[i-id] < y){\n y = nums[i-id];\n ind2 = i-id;\n }\n if(abs(nums[i] - nums[ind1])>=vd){\n return {ind1,i};\n }\n if(abs(nums[i] - nums[ind2])>=vd){\n return {ind2,i};\n }\n }\n return {-1,-1};\n }\n};\n```
8
1
['Array', 'C++']
1
find-indices-with-index-and-value-difference-ii
✅☑[C++/C/Java/Python/JavaScript] || EXPLAINED🔥
ccjavapythonjavascript-explained-by-mark-z385
PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n(Also explained in the code)\n1. The function findIndices takes three parameters: nums (a vector of integer
MarkSPhilip31
NORMAL
2023-10-15T07:25:32.310951+00:00
2023-10-15T07:25:32.310974+00:00
465
false
# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n1. The function `findIndices` takes three parameters: `nums` (a vector of integers), `indexDifference` (an integer), and `valueDifference` (an integer). It aims to find a pair of indices in the vector nums such that the absolute difference between the values at these indices is less than or equal to `valueDifference`, and the indices themselves have a difference of at least `indexDifference`.\n\n1. We initialize a set `S` to store pairs of (value, index). This set will help us efficiently search for valid pairs.\n\n1. We iterate through the elements in the `nums` vector with a loop. For each element at index `i`, we check if we have a sufficient number of previous elements (at least `indexDifference`) to form a valid pair.\n\n1. If we have enough previous elements, we calculate `x`, the index of the element to potentially remove from the set, and `y`, the value at index `x`. We insert the pair (y, x) into the set `S`.\n\n1. Next, we search for two types of pairs:\n\n - Pairs where the absolute difference between `nums[i]` and the value in the set is less than or equal to `valueDifference`. We use `lower_bound` to find such pairs.\n - Pairs where the absolute difference between `nums[i]` and the value in the set is less than `valueDifference`. We adjust the lower bound to find these pairs.\n1. If we find a valid pair in either of these searches, we return the indices of the pair.\n\n1. If no valid pair is found throughout the loop, we return {-1, -1} to indicate that there\'s no such pair.\n\n\n\n# Complexity\n- *Time complexity:*\n $$O(n*logn)$$\n \n\n- *Space complexity:*\n $$O(n)$$\n \n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n vector<int> findIndices(vector<int>& nums, int indexDifference, int valueDifference) {\n int n = nums.size();\n set<pair<int, int>> S; // Create a set to store pairs of (value, index).\n\n for (int i = 0; i < n; i++) {\n if (i >= indexDifference) {\n int x = i - indexDifference; // Calculate the index \'x\' to check for removal.\n int y = nums[x]; // Get the value at index \'x\'.\n S.insert({y, x}); // Insert the pair (value, index) into the set.\n }\n\n // Find the lower bound for the pair (nums[i] + valueDifference, 0).\n auto it = S.lower_bound({nums[i] + valueDifference, 0});\n\n if (it != S.end()) {\n // If a pair is found in the set, return its indices.\n return {it->second, i};\n }\n\n // Find the lower bound for the pair (nums[i] - valueDifference + 1, 0).\n it = S.lower_bound({nums[i] - valueDifference + 1, 0});\n\n if (it != S.begin()) {\n --it; // Move the iterator to the previous element.\n // Return the indices of the found pair.\n return {it->second, i};\n }\n }\n\n return {-1, -1}; // If no valid pair is found, return {-1, -1}.\n }\n};\n\n\n```\n\n```C []\n#include <stdio.h>\n#include <stdlib.h>\n\nstruct Pair {\n int value;\n int index;\n};\n\nint* findIndices(int* nums, int numsSize, int indexDifference, int valueDifference, int* returnSize) {\n struct Pair* S = (struct Pair*)malloc(numsSize * sizeof(struct Pair));\n\n int* result = (int*)malloc(2 * sizeof(int));\n *returnSize = 2;\n\n for (int i = 0; i < numsSize; i++) {\n if (i >= indexDifference) {\n int x = i - indexDifference;\n int y = nums[x];\n S[x].value = y;\n S[x].index = x;\n }\n\n int left = i - 1;\n int right = i;\n\n while (left >= 0 && S[left].value > nums[i] - valueDifference) {\n if (S[left].index >= i - indexDifference) {\n result[0] = S[left].index;\n result[1] = i;\n return result;\n }\n left--;\n }\n\n while (right >= 0 && S[right].value <= nums[i] + valueDifference) {\n if (S[right].index >= i - indexDifference) {\n result[0] = S[right].index;\n result[1] = i;\n return result;\n }\n right--;\n }\n }\n\n result[0] = -1;\n result[1] = -1;\n return result;\n}\n\n\n```\n\n\n```Java []\nimport java.util.TreeSet;\nimport java.util.Arrays;\n\npublic class Solution {\n public int[] findIndices(int[] nums, int indexDifference, int valueDifference) {\n int n = nums.length;\n TreeSet<Pair> S = new TreeSet<>();\n int[] result = new int[2];\n \n for (int i = 0; i < n; i++) {\n if (i >= indexDifference) {\n int x = i - indexDifference;\n int y = nums[x];\n S.add(new Pair(y, x));\n }\n \n Pair upperBound = S.ceiling(new Pair(nums[i] + valueDifference, 0));\n if (upperBound != null) {\n result[0] = upperBound.index;\n result[1] = i;\n return result;\n }\n \n Pair lowerBound = S.floor(new Pair(nums[i] - valueDifference + 1, 0));\n if (lowerBound != null) {\n result[0] = lowerBound.index;\n result[1] = i;\n return result;\n }\n }\n \n result[0] = -1;\n result[1] = -1;\n return result;\n }\n\n class Pair implements Comparable<Pair> {\n int value;\n int index;\n \n public Pair(int value, int index) {\n this.value = value;\n this.index = index;\n }\n \n @Override\n public int compareTo(Pair other) {\n return Integer.compare(this.value, other.value);\n }\n }\n}\n\n\n```\n\n```python3 []\nfrom sortedcontainers import SortedList\n\nclass Solution:\n def findIndices(self, nums: List[int], indexDifference: int, valueDifference: int) -> List[int]:\n n = len(nums)\n S = SortedList()\n\n for i in range(n):\n if i >= indexDifference:\n x = i - indexDifference\n y = nums[x]\n S.add((y, x))\n\n upper_bound = S.bisect_left((nums[i] + valueDifference, 0))\n if upper_bound != len(S):\n return [S[upper_bound][1], i]\n\n lower_bound = S.bisect_left((nums[i] - valueDifference + 1, 0))\n if lower_bound > 0:\n return [S[lower_bound - 1][1], i]\n\n return [-1, -1]\n\n\n```\n\n```javascript []\n\nclass Solution {\n findIndices(nums, indexDifference, valueDifference) {\n const n = nums.length;\n const S = new SortedSet();\n const result = new Array(2);\n\n for (let i = 0; i < n; i++) {\n if (i >= indexDifference) {\n const x = i - indexDifference;\n const y = nums[x];\n S.add([y, x]);\n }\n\n const upperBound = S.bisect([nums[i] + valueDifference, 0]);\n if (upperBound < S.size) {\n result[0] = S.get(upperBound)[1];\n result[1] = i;\n return result;\n }\n\n const lowerBound = S.bisect([nums[i] - valueDifference + 1, 0]) - 1;\n if (lowerBound >= 0) {\n result[0] = S.get(lowerBound)[1];\n result[1] = i;\n return result;\n }\n }\n\n result[0] = -1;\n result[1] = -1;\n return result;\n }\n}\n\nclass SortedSet {\n constructor() {\n this.data = [];\n }\n\n get size() {\n return this.data.length;\n }\n\n add(item) {\n this.data.push(item);\n this.data.sort((a, b) => a[0] - b[0]);\n }\n\n get(index) {\n return this.data[index];\n }\n\n bisect(item) {\n let left = 0;\n let right = this.data.length;\n while (left < right) {\n const mid = Math.floor((left + right) / 2);\n if (this.data[mid][0] >= item[0]) {\n right = mid;\n } else {\n left = mid + 1;\n }\n }\n return left;\n }\n}\n\n\n```\n\n\n---\n\n\n\n# PLEASE UPVOTE IF IT HELPED\n\n---\n---\n\n\n---
6
0
['C', 'Ordered Set', 'C++', 'Java', 'Python3', 'JavaScript']
1
find-indices-with-index-and-value-difference-ii
✅✔️Easy to understand || clean code || C++ Solution ✈️✈️✈️✈️✈️
easy-to-understand-clean-code-c-solution-ly3w
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
ajay_1134
NORMAL
2023-10-15T04:06:03.131650+00:00
2023-10-15T04:06:03.131668+00:00
763
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> findIndices(vector<int>& nums, int d, int v) {\n int n = nums.size();\n \n vector<pair<int,int>>mn(n,{nums[n-1],n-1}), mx(n,{nums[n-1],n-1});\n \n for(int i=n-2; i>=0; i--){\n if(nums[i] < mn[i+1].first){\n mn[i] = {nums[i], i};\n }\n else{\n mn[i] = mn[i+1]; \n } \n if(nums[i] > mx[i+1].first){\n mx[i] = {nums[i],i};\n }\n else {\n mx[i] = mx[i+1];\n }\n }\n \n int i = 0;\n \n for(int j=0; j<n; j++){\n if(j-i < d) continue;\n if(abs(mn[j].first-nums[i]) >= v ){\n return {i,mn[j].second};\n }\n if(abs(mx[j].first - nums[i]) >= v){\n return {i,mx[j].second};\n }\n i++;\n }\n return {-1,-1};\n }\n};\n```
6
0
['Array', 'Sliding Window', 'Suffix Array', 'C++']
0
find-indices-with-index-and-value-difference-ii
Simple prefix sum
simple-prefix-sum-by-joe54-s1tx
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
joe54
NORMAL
2023-10-15T04:01:01.460758+00:00
2023-10-15T04:01:01.460779+00:00
571
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n $$O(n)$$\n\n- Space complexity:\n $$O(n)$$\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> findIndices(vector<int>& nums, int indexDifference, int valueDifference) {\n vector<pair<int, int>> leftMax(nums.size(), {0,0});\n vector<pair<int, int>> leftMin(nums.size(), {0,0});\n vector<pair<int, int>> rightMax(nums.size(), {0,0});\n vector<pair<int, int>> rightMin(nums.size(), {0,0});\n \n int curMin = INT_MAX;\n int curMax = INT_MIN;\n\n for (int i = 0; i < nums.size(); i++) {\n if (nums[i] < curMin) {\n curMin = nums[i];\n leftMin[i] = {nums[i], i};\n } else {\n leftMin[i] = leftMin[i - 1];\n }\n \n if (nums[i] > curMax) {\n curMax = nums[i];\n leftMax[i] = {nums[i], i};\n } else {\n leftMax[i] = leftMax[i - 1];\n }\n }\n\n curMin = INT_MAX;\n curMax = INT_MIN;\n \n for (int i = nums.size() - 1; i >= 0; i--) {\n if (nums[i] < curMin) {\n curMin = nums[i];\n rightMin[i] = {nums[i], i};\n } else {\n rightMin[i] = rightMin[i + 1];\n }\n \n if (nums[i] > curMax) {\n curMax = nums[i];\n rightMax[i] = {nums[i], i};\n } else {\n rightMax[i] = rightMax[i + 1];\n }\n }\n \n for (int i = 0; i < nums.size(); i++) {\n int left = i - indexDifference;\n int right = i + indexDifference;\n if (left >= 0) {\n if (abs(leftMax[left].first - nums[i]) >= valueDifference) return {leftMax[left].second, i};\n if (abs(leftMin[left].first - nums[i]) >= valueDifference) return {leftMax[left].second, i};\n }\n \n if (right < nums.size()) {\n if (abs(rightMax[right].first - nums[i]) >= valueDifference) return {rightMax[right].second, i};\n if (abs(rightMax[right].first - nums[i]) >= valueDifference) return {rightMax[right].second, i};\n }\n }\n \n return {-1, -1};\n \n \n }\n};\n```
5
0
['C++']
2
find-indices-with-index-and-value-difference-ii
Easy 4 liner explained O(n) time O(1) space, beats 100%, 100%
easy-4-liner-explained-on-time-o1-space-175df
Intuition\n Describe your first thoughts on how to solve this problem. \nSince we have to find an value which is greater than a given valueDifference which are
flame_blitz
NORMAL
2023-10-15T06:20:05.196305+00:00
2023-10-15T06:21:57.142017+00:00
155
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSince we have to find an value which is greater than a given valueDifference which are atleast indexDifference apart, we can just keep track of max and min values as we come across them and then just evaulate them with the current elemnt we\'re on.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- We take 2 variables, min and max, which stores the indices of min and max element respectively.\n- We start a loop with 2 pointers, one at 0 and the other indexDifference apart from it so we dont have to worry about the condition `abs(i - j) >= indexDifference` as it will always remain true.\n- We continue forward keeping track of the min and max element indices.\n- If at any point `Math.abs(nums[min]-nums[j])` or, `Math.abs(nums[max]-nums[j])` comes out to be greater than the `valueDifference`, we return the said indices.\n- If the entire array is traversed and we found no such instances, we return [-1,-1] instead.\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code with comments\n```\nvar findIndices = function(nums, indexDifference, valueDifference) {\n \n let max = 0, // index of max so far\n min = 0; // index of min so far\n \n //set a pointer to 0 and another one which is indexDifferent apart so that the index condition is always true\n for(let i=0, j=indexDifference ; j<nums.length ; j++,i++){ \n if(nums[min] > nums[i]) //if the number at min index is greater than current\n min = i; // update min index.\n else if(nums[max] < nums[i]) // same goes for max\n max = i;\n \n // if the other condition goes true for MIN and current elemnt of second pointer, return\n if(Math.abs(nums[min]-nums[j]) >= valueDifference) \n return [min,j];\n\n // if the other condition goes true for MAX and current elemnt of second pointer, return\n if(Math.abs(nums[max]-nums[j]) >= valueDifference)\n return [max,j];\n \n }\n //if no returns were made, then the conditions have not been met, return for the not found case.\n return [-1,-1];\n};\n```\n# Clean and concise code\n```\nvar findIndices = function(nums, indexDifference, valueDifference) {\n let max=0, min = 0; \n \n for(let i=0,j=i+indexDifference ; j<nums.length ; j++,i++){\n if(nums[min] > nums[i]) min = i;\n else if(nums[max] < nums[i]) max = i;\n if(Math.abs(nums[min]-nums[j]) >= valueDifference) return [min,j];\n if(Math.abs(nums[max]-nums[j]) >= valueDifference) return [max,j]; \n }\n\n return [-1,-1];\n};\n```
4
0
['Array', 'Two Pointers', 'JavaScript']
3
find-indices-with-index-and-value-difference-ii
Java Easy solution - O(N)
java-easy-solution-on-by-abhishek1208-cxyd
\nclass Solution {\n public int[] findIndices(int[] nums, int indexDifference, int valueDifference) {\n int[] ans = new int[]{-1,-1};\n \n
lcabhishek
NORMAL
2023-10-15T04:01:58.953451+00:00
2023-10-15T04:54:57.091641+00:00
454
false
```\nclass Solution {\n public int[] findIndices(int[] nums, int indexDifference, int valueDifference) {\n int[] ans = new int[]{-1,-1};\n \n List<int[]> list = new ArrayList<>();\n int min = 0;\n int max = 0;\n \n \n //store the max and min till the index i\n for(int i =0;i < nums.length; ++i){\n \n if(nums[i] < nums[min]) min = i;\n if(nums[i] > nums[max]) max = i;\n list.add(new int[]{min, max});\n }\n \n //try to find the second index where the condition can be satisfied\n for(int i =0; i < nums.length; ++i){\n \n int j = i-indexDifference;\n \n if(j>=0){\n \n if(Math.abs(nums[i] - nums[list.get(j)[0]])>=valueDifference){\n return new int[]{list.get(j)[0], i};\n } \n \n if(Math.abs(nums[i] - nums[list.get(j)[1]])>=valueDifference){\n return new int[]{list.get(j)[1], i};\n } \n \n }\n \n }\n \n\n // We can\'t satisfy the condition\n return new int[]{-1,-1};\n }\n}\n```
4
1
['Java']
2
find-indices-with-index-and-value-difference-ii
C++ very easy and optimised solution
c-very-easy-and-optimised-solution-by-aa-pdge
Intuition\n Describe your first thoughts on how to solve this problem. \n\njust use 2 stack and use logic\n\n# Approach\n Describe your approach to solving the
AAA_code
NORMAL
2023-10-17T16:43:06.209498+00:00
2023-10-17T16:43:06.209522+00:00
206
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\njust use 2 stack and use logic\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nmaking a two- way sliding window type that is sorted\n\n# Complexity\n- Time complexity:\n- o(n);\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> findIndices(vector<int>& nums, int index, int value) {\n int n = nums.size();\n \n int i =0;\n int j= index;\n stack<int>st;\n stack<int>st2;\n st2.push(0);\n st.push(0);\n \n while(j<n){\n \n if (nums[i]>nums[st.top()]){\n st.push(i);\n }\n else if (nums[i]<nums[st2.top()]) st2.push(i);\n \n \n // cout<<"j is "<<j<< "st.top() "<< st.top()<< "st2.top() "<<st2.top()<<endl;\n \n if (abs(nums[j]-nums[st.top()]) >= value){\n vector<int>v;\n v.push_back(st.top());\n v.push_back(j);\n return v;\n }\n \n else if (abs(nums[j]-nums[st2.top()]) >= value){\n vector<int>v;\n v.push_back(st2.top());\n v.push_back(j);\n return v;\n }\n i++;\n j++;\n \n \n \n \n }\n \n return {-1,-1};\n \n \n \n \n\n \n \n \n \n \n \n }\n};\n```
3
1
['Stack', 'C++']
0
find-indices-with-index-and-value-difference-ii
CPP || Two pointer || 100 % || TC:O(n) SC:O(1)
cpp-two-pointer-100-tcon-sco1-by-kgaurav-ey3h
Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem is about finding two indices in an array such that the absolute difference
kgaurav8026
NORMAL
2023-10-15T19:31:11.434436+00:00
2023-10-15T19:31:11.434454+00:00
220
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem is about finding two indices in an array such that the absolute difference between their values is greater than or equal to a given value and the absolute difference between the indices is greater than or equal to another given value. The first thought that comes to mind is to iterate over the array and keep track of the maximum and minimum values encountered so far. If we find a pair of indices that satisfy the conditions, we return them.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe approach is to iterate over the array twice. In the first iteration, we keep track of the maximum value encountered so far and its index. If we find an index such that the absolute difference between its value and the maximum value is greater than or equal to valueDifference and the absolute difference between their indices is greater than or equal to indexDifference, we return these indices. If no such pair of indices is found in the first iteration, we do a second iteration where we keep track of the minimum value encountered so far and its index, and look for a pair of indices that satisfy the conditions.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity is O(n) because we are iterating over the array twice.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is O(1) because we are using a constant amount of space to store the maximum and minimum values and their indices.\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> findIndices(vector<int>& nums, int indexDifference, int valueDifference) {\n int maxidx=0;\n int n = nums.size();\n for(int i=0 ; i<n-indexDifference ; i++){\n if(nums[i]>nums[maxidx]) maxidx = i;\n if(abs(nums[maxidx] - nums[i+indexDifference]) >= valueDifference) return {maxidx,i+indexDifference};\n \n } \n int minidx=0;\n for(int i=0 ; i<n-indexDifference ; i++){\n if(nums[i]<nums[minidx]) minidx = i;\n if(abs(nums[minidx] - nums[i+indexDifference]) >= valueDifference) return {minidx,i+indexDifference};\n \n } \n return {-1,-1};\n }\n};\n```
3
0
['Two Pointers', 'C++']
0
find-indices-with-index-and-value-difference-ii
✅ ✅ Indices with index and value difference | Beginner friendly | Min array & Max array ✅ ✅
indices-with-index-and-value-difference-j8gci
Hi,\n\nApproach: I utilized two arrays to store the minimum and maximum values, then used them to efficiently find indices with the desired value difference.\n\
Surendaar
NORMAL
2023-10-15T17:45:26.909420+00:00
2023-10-15T17:47:39.014407+00:00
106
false
Hi,\n\n**Approach:** I utilized two arrays to store the minimum and maximum values, then used them to efficiently find indices with the desired value difference.\n\n**Intuition:** Instead of a direct brute force approach which would result in TLE, I optimized by iterating through the loop fewer than n^2 times.\n\n**Steps:**\n\n1. Iterate through the loop from length-1 to 0, and store the maximum and minimum elements in two separate arrays.\n2. From 0 to length minus the given index difference, check if the current value has a difference greater than or equal to the desired value difference in both the min and max arrays at index equal to k.\n3. If such a value exists, iterate through the loop once to find that element and return the result.\n4. If no such element is found, return {-1,-1}.\n\n\nHappy learning! If you found this helpful, please do upvote. :)\n\n```\n public int[] findIndices(int[] nums, int indexDifference, int valueDifference) {\n int[] res = {-1, -1};\n int len = nums.length;\n int[] max = new int[len];\n int[] min = new int[len];\n max[len-1] = nums[len-1];\n min[len-1] = nums[len-1];\n for(int i=len-2; i>=0; i--){\n min[i] = Math.min(min[i+1], nums[i]);\n max[i] = Math.max(max[i+1], nums[i]);\n }\n for(int i=0; i<len-indexDifference; i++){\n if(Math.abs(nums[i]-min[i+indexDifference])<valueDifference && Math.abs(nums[i]-max[i+indexDifference])<valueDifference){\n continue;\n }\n for(int j=i+indexDifference; j<len; j++){\n if(Math.abs(nums[i]-nums[j])>=valueDifference){\n res[0]=i;\n res[1]=j;\n return res;\n }\n }\n }\n return res;\n }\n
3
0
['Array', 'Java']
0
find-indices-with-index-and-value-difference-ii
[C++] Insert the candidates {value, index} into an ordered set
c-insert-the-candidates-value-index-into-fq3n
Intuition\n Describe your first thoughts on how to solve this problem. \nFor each index i, try the minimum and maximum values in the indices j = [i + indexDIffe
pepe-the-frog
NORMAL
2023-10-15T07:22:01.786216+00:00
2023-10-15T07:22:01.786242+00:00
180
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFor each index `i`, try the minimum and maximum values in the indices `j = [i + indexDIfference, n)`\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- for each index `i`, only indices in `[i + indexDifference, n)` are treated as the candidates\n - insert `{value, index}` into an ordered set\n- remove the candidate who is out of range when `i` is increasing\n\n# Complexity\n- Time complexity: $$O(n * 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```\nclass Solution {\npublic:\n // time/space: O(nlogn)/O(n)\n vector<int> findIndices(vector<int>& nums, int indexDifference, int valueDifference) {\n int n = nums.size();\n\n // insert {value, index} into an ordered set\n set<pair<int, int>> hash;\n for (int i = indexDifference; i < n; i++) hash.insert({nums[i], i});\n \n for (int i = 0; i < n; i++) {\n // exit if there is no more candidate\n if (hash.empty()) break;\n // try the minimum value on the candidates\n auto [min_value, min_value_index] = *(hash.begin());\n if (abs(nums[i] - min_value) >= valueDifference) return {i, min_value_index};\n // try the maximum value on the candidates\n auto [max_value, max_value_index] = *(hash.rbegin());\n if (abs(nums[i] - max_value) >= valueDifference) return {i, max_value_index};\n // remove the candidate who is out of range\n int index = i + indexDifference;\n if (index < n) hash.erase(hash.find({nums[index], index}));\n }\n \n return {-1, -1};\n }\n};\n```
3
1
['Ordered Set', 'C++']
0
find-indices-with-index-and-value-difference-ii
Python3 | Binary Search
python3-binary-search-by-tkr_6-xmte
\n\n# Code\n\nclass Solution:\n def findIndices(self, nums: List[int], ind: int, val: int) -> List[int]:\n \n \n \n n=len(nums)\n
TKR_6
NORMAL
2023-10-15T05:44:48.546467+00:00
2023-10-15T05:44:48.546500+00:00
160
false
\n\n# Code\n```\nclass Solution:\n def findIndices(self, nums: List[int], ind: int, val: int) -> List[int]:\n \n \n \n n=len(nums)\n sl=[] #SortedList\n \n for i in range(ind,n):\n insort(sl,[nums[i-ind],i-ind])\n \n a,i1=sl[0]\n b,i2=sl[-1]\n \n if abs(a-nums[i])>=val:\n return [i,i1]\n if abs(b-nums[i])>=val:\n return [i,i2]\n \n \n return [-1,-1]\n \n \n \n \n \n```
3
0
['Binary Search', 'Python', 'Python3']
0
find-indices-with-index-and-value-difference-ii
C++ - Binary Search Solution
c-binary-search-solution-by-omkamble0800-k7jp
Complexity\n- Time complexity: O(nlogn)\n\n- Space complexity: O(n)\n\n# Code\n\nclass Solution {\npublic:\n vector<int> findIndices(vector<int>& nums, int i
omkamble0800
NORMAL
2023-10-15T04:19:17.271597+00:00
2023-10-15T04:19:17.271616+00:00
382
false
# Complexity\n- Time complexity: $$O(nlogn)$$\n\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> findIndices(vector<int>& nums, int id, int vd) {\n int n = nums.size();\n set<pair<int, int>> st;\n for(int i = id; i < n; i++){\n st.insert({nums[i - id], i - id});\n auto it = st.lower_bound({nums[i] + vd, -1});\n if(it != st.end()){\n return {i, it->second};\n }\n auto it1 = st.upper_bound({nums[i] - vd, INT_MAX});\n if(it1 != st.begin()){\n it1 = prev(it1);\n // cout << it1->first << \'\\n\';\n return {i, it1->second};\n }\n }\n return {-1, -1};\n }\n};\n```
3
1
['Array', 'Binary Search', 'Ordered Set', 'C++']
1
find-indices-with-index-and-value-difference-ii
Simple solution with comments which is easy to understand
simple-solution-with-comments-which-is-e-hj4x
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
Code_Of_Duty
NORMAL
2023-10-15T04:06:05.842691+00:00
2023-10-15T04:06:05.842709+00:00
270
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> findIndices(vector<int>& nums, int difference, int threshold) {\n int n = nums.size(); // Get the size of the input vector\n\n // Create two vectors of pairs to store minimum and maximum values\n vector<pair<int, int>> minValues(n), maxValues(n);\n\n // Iterate through the input vector in reverse order\n for (int i = n - 1; i >= 0; i--) {\n minValues[i] = maxValues[i] = {nums[i], i};\n // If not at the last element, update min and max values based on the next element\n if (i < n - 1) {\n minValues[i] = min(minValues[i], minValues[i + 1]);\n maxValues[i] = max(maxValues[i], maxValues[i + 1]);\n }\n }\n\n // Iterate through the vector to find the indices meeting the condition\n for (int i = 0; i + difference < n; i++) {\n // Check if the difference between the maximum value in the next \'difference\' elements and the current element is greater than or equal to \'threshold\'\n if (maxValues[i + difference].first - nums[i] >= threshold) {\n return {i, maxValues[i + difference].second};\n }\n // Check if the difference between the current element and the minimum value in the next \'difference\' elements is greater than or equal to \'threshold\'\n if (nums[i] - minValues[i + difference].first >= threshold) {\n return {i, minValues[i + difference].second};\n }\n }\n\n return {-1, -1}; // Return {-1, -1} if no such pair is found\n }\n};\n\n```
3
0
['Array', 'Prefix Sum', 'C++']
0
find-indices-with-index-and-value-difference-ii
🔥GREEDY : O(n) TC || ✅⚡Clean & Best Code
greedy-on-tc-clean-best-code-by-adish_21-19sk
Connect with me on LinkedIN : https://www.linkedin.com/in/aditya-jhunjhunwala-51b586195/\n\n# Complexity\n\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n
aDish_21
NORMAL
2023-10-15T04:03:20.886742+00:00
2023-10-15T04:05:39.405052+00:00
307
false
## Connect with me on LinkedIN : https://www.linkedin.com/in/aditya-jhunjhunwala-51b586195/\n\n# Complexity\n```\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n```\n\n# Code\n# Please Upvote if it helps\uD83E\uDD17\n```\nclass Solution {\npublic:\n vector<int> findIndices(vector<int>& nums, int indexDifference, int valueDifference) {\n int n = nums.size(), maxi = 0, mini = INT_MAX, x = -1, y = -1;\n vector<int> ans = {-1, -1};\n vector<pair<int, int>> minSuffix(n), maxSuffix(n);\n \n for(int i = n - 1 ; i >= 0 ; i--){\n if(nums[i] > maxi){\n maxi = nums[i];\n x = i;\n }\n maxSuffix[i] = {maxi, x};\n if(nums[i] < mini){\n mini = nums[i];\n y = i;\n }\n minSuffix[i] = {mini, y};\n }\n \n for(int i = 0 ; i < n ; i++){\n int j = indexDifference + i;\n if(j >= n)\n break;\n if(abs(nums[i] - minSuffix[j].first) >= valueDifference)\n return {i, minSuffix[j].second};\n if(abs(nums[i] - maxSuffix[j].first) >= valueDifference)\n return {i, maxSuffix[j].second};\n }\n return ans;\n }\n};\n```
3
0
['Greedy', 'C++']
0
find-indices-with-index-and-value-difference-ii
❇ find-indices-with-index-and-value-difference-ii Images👌 🏆O(N)❤️ Javascript🎯 Memory👀95%🕕 ++Exp
find-indices-with-index-and-value-differ-9zsb
Time Complexity: O(N)\uD83D\uDD55\nSpace Complexity: O(N)\n\n\nvar findIndices = function (nums, indexDifference, valueDifference) {\n if (indexDifference ==
anurag-sindhu
NORMAL
2024-09-26T18:28:08.827261+00:00
2024-09-26T18:30:39.017381+00:00
37
false
**Time Complexity: O(N)\uD83D\uDD55\nSpace Complexity: O(N)**\n\n```\nvar findIndices = function (nums, indexDifference, valueDifference) {\n if (indexDifference == 0) {\n if (valueDifference === 0) {\n return [0, 0];\n }\n }\n\n const bigNumArr = [];\n const bigNumArrIndexMapping = [];\n for (let index = nums.length - 1; index >= 0; index--) {\n const lastNum = bigNumArr[bigNumArr.length - 1];\n if (lastNum === undefined) {\n bigNumArr.push(nums[index]);\n bigNumArrIndexMapping.push(index);\n } else {\n if (nums[index] > lastNum) {\n bigNumArr.push(nums[index]);\n bigNumArrIndexMapping.push(index);\n } else {\n bigNumArr.push(lastNum);\n bigNumArrIndexMapping.push(bigNumArrIndexMapping[bigNumArrIndexMapping.length - 1]);\n }\n }\n }\n bigNumArrIndexMapping.reverse();\n bigNumArr.reverse();\n\n const smallNumArr = [];\n const smallNumArrIndexMapping = [];\n for (let index = nums.length - 1; index >= 0; index--) {\n const lastNum = smallNumArr[smallNumArr.length - 1];\n if (lastNum === undefined) {\n smallNumArr.push(nums[index]);\n smallNumArrIndexMapping.push(index);\n } else {\n if (nums[index] < lastNum) {\n smallNumArr.push(nums[index]);\n smallNumArrIndexMapping.push(index);\n } else {\n smallNumArr.push(lastNum);\n smallNumArrIndexMapping.push(\n smallNumArrIndexMapping[smallNumArrIndexMapping.length - 1],\n );\n }\n }\n }\n smallNumArrIndexMapping.reverse();\n smallNumArr.reverse();\n\n for (let index = 0; index < nums.length; index++) {\n if (Math.abs(nums[index] - bigNumArr[index + indexDifference]) >= valueDifference) {\n return [index, bigNumArrIndexMapping[index + indexDifference]];\n }\n if (Math.abs(nums[index] - smallNumArr[index + indexDifference]) >= valueDifference) {\n return [index, smallNumArrIndexMapping[index + indexDifference]];\n }\n }\n return [-1, -1];\n};\n```\n\nconst bigNumArr = [];\nconst bigNumArrIndexMapping = [];\nThis block creates an array bigNumArr to store the largest number from each index to the right. bigNumArrIndexMapping tracks the original indices of these numbers.\n\n\uD83C\uDF00 Loop from the end of nums to the beginning.\n\uD83D\uDD04 Compare each element with the last element added to bigNumArr.\nIf the current element is larger \u27A1\uFE0F add it.\nOtherwise \u27A1\uFE0F keep the previous large number at this position.\nFinally, the arrays are reversed so that they match the original order of nums.\n\n3\uFE0F\u20E3 Building the Small Numbers Array \uD83D\uDEE0\uFE0F\nSimilar to bigNumArr, the smallNumArr stores the smallest numbers from each index to the right. The process is the same as for the largest numbers, but this time, we compare and store the smaller values.\n\nthe function checks each element in the nums array:\n\nIt compares the difference between nums[index] and bigNumArr[index + indexDifference].\nIf the difference is greater than or equal to valueDifference \uD83C\uDFC1, it returns the index pair.\nThe same check is done for the smallNumArr.\nIf no valid pair is found, [-1, -1] is returned.\n\n![image](https://assets.leetcode.com/users/images/a8c28066-7180-4279-86fb-6a2b87ad3b14_1727375373.2605457.png)\n\n![image](https://assets.leetcode.com/users/images/3462cbb9-89db-46da-af85-73972b2b09ae_1727375099.2451308.png)\n\nPlease upvote \uD83D\uDCAA if like\n
2
0
['JavaScript']
0
find-indices-with-index-and-value-difference-ii
Java Simple Two Pointer Solution || With Detail Explanation
java-simple-two-pointer-solution-with-de-kgug
Intuition\n- We take 2 variables, min and max, which stores the indices of min and max element respectively.\n- We start a loop with 2 pointers, one at 0 and th
Shree_Govind_Jee
NORMAL
2024-07-03T15:41:38.580740+00:00
2024-07-03T15:41:38.580773+00:00
73
false
# Intuition\n- We take 2 variables, min and max, which stores the indices of **$$min$$** and **$$max$$** element respectively.\n- We start a loop with **$$2 pointers$$**, one at $$0$$ and the other indexDifference apart from it so we dont have to worry about the condition `Math.abs(i - j) >= indexDifference` as it will always remain **$$true$$**.\n- We continue forward keeping track of the **`min`** and **`max`** element indices.\n- If at any point `Math.abs(nums[min]-nums[j])` or, `Math.abs(nums[max]-nums[j])` comes out to be greater than the `valueDifference`, we return the said indices.\n- If the entire array is traversed and we found no such instances, we `return new int[]{-1,-1}` instead.\n\n# Complexity\n- Time complexity:$$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n// // BRUTE-FORCE SOLUTION\n// class Solution {\n// public int[] findIndices(int[] nums, int indexDifference,\n// int valueDifference) {\n// for (int i = 0; i < nums.length; i++) {\n// for (int j = 0; j < nums.length; j++) {\n// if (Math.abs(i - j) >= indexDifference &&\n// Math.abs(nums[i] - nums[j]) >= valueDifference) {\n// return new int[] { i, j };\n// }\n// }\n// }\n// return new int[] { -1, -1 };\n// }\n// }\n\nclass Solution {\n public int[] findIndices(int[] nums, int indexDifference,\n int valueDifference) {\n int min = 0; // index for first suitable value(min)\n int max = 0; // index for second suitable value(max)\n for (int i = 0, j = indexDifference; j < nums.length; i++, j++) {\n if (nums[min] > nums[i]) {\n min = i;\n } else if (nums[max] < nums[i]) {\n max = i;\n }\n\n // if current "min" and "j" is valid then return it\n if (Math.abs(nums[min] - nums[j]) >= valueDifference) {\n return new int[] { min, j };\n }\n // if current "max" and "j" is valid then return it\n else if (Math.abs(nums[max] - nums[j]) >= valueDifference) {\n return new int[] { max, j };\n }\n }\n return new int[] { -1, -1 }; // no any possibility\n }\n}\n```
2
0
['Array', 'Two Pointers', 'Greedy', 'Java']
0
find-indices-with-index-and-value-difference-ii
C++ || Segment Tree || Unique Solution 🔥✅💯
c-segment-tree-unique-solution-by-_kvsch-33mz
\n# Code\n\nclass Solution {\npublic:\n // SEGMENT TREES :- vector<int> seg(1000), vector<int>arr(1000), i = 0, l = 0, h = n-1, x = idx, v = val, (x,y) = (l,
_kvschandra_2234
NORMAL
2024-04-30T14:57:19.610680+00:00
2024-04-30T14:57:38.803954+00:00
20
false
\n# Code\n```\nclass Solution {\npublic:\n // SEGMENT TREES :- vector<int> seg(1000), vector<int>arr(1000), i = 0, l = 0, h = n-1, x = idx, v = val, (x,y) = (l,r).\n void buildSeg1(vector<int>& seg, const vector<int>& arr, int i, int l, int h) {\n if (l == h) {\n seg[i] = arr[l];\n return;\n }\n int m = (l + h) / 2;\n buildSeg1(seg, arr, 2*i + 1, l, m);\n buildSeg1(seg, arr, 2*i + 2, m + 1, h);\n seg[i] = min(seg[2*i + 1], seg[2*i + 2]);\n }\n void buildSeg2(vector<int>& seg, const vector<int>& arr, int i, int l, int h) {\n if (l == h) {\n seg[i] = arr[l];\n return;\n }\n int m = (l + h) / 2;\n buildSeg2(seg, arr, 2*i + 1, l, m);\n buildSeg2(seg, arr, 2*i + 2, m + 1, h);\n seg[i] = max(seg[2*i + 1], seg[2*i + 2]);\n }\n void updateSeg(vector<int>& seg, vector<int>& arr, int i, int l, int h, int x, int v) {\n if (l == h) {\n arr[x] = v;\n seg[i] = v;\n return;\n }\n int m = (l + h) / 2;\n (x <= m) ? updateSeg(seg, arr, 2*i + 1, l, m, x, v) : updateSeg(seg, arr, 2*i + 2, m + 1, h, x, v);\n seg[i] = min(seg[2*i + 1], seg[2*i + 2]);\n }\n int querySeg1(const vector<int>& seg, int i, int l, int h, int x, int y) {\n if (l > y || h < x) return INT_MAX;\n if (l >= x && h <= y) return seg[i];\n int m = (l + h) / 2;\n int leftMin = querySeg1(seg, 2*i + 1, l, m, x, y);\n int rightMin = querySeg1(seg, 2*i + 2, m + 1, h, x, y);\n return min(leftMin, rightMin);\n }\n int querySeg2(const vector<int>& seg, int i, int l, int h, int x, int y) {\n if (l > y || h < x) return INT_MIN;\n if (l >= x && h <= y) return seg[i];\n int m = (l + h) / 2;\n int leftMin = querySeg2(seg, 2*i + 1, l, m, x, y);\n int rightMin = querySeg2(seg, 2*i + 2, m + 1, h, x, y);\n return max(leftMin, rightMin);\n }\n \n vector<int> findIndices(vector<int>& nums, int indexDifference, int valueDifference) {\n int n = nums.size();\n int i = 0, j = indexDifference;\n vector<int>seg1(4*n+1), seg2(4*n+1);\n \n buildSeg1(seg1, nums, 0, 0, n-1);\n buildSeg2(seg2, nums, 0, 0, n-1);\n while(j < n) {\n int maxi1 = querySeg2(seg2, 0, 0, n-1, 0, i);\n int mini1 = querySeg1(seg1, 0, 0, n-1, 0, i);\n int maxi2 = querySeg2(seg2, 0, 0, n-1, j, n-1);\n int mini2 = querySeg1(seg1, 0, 0, n-1, j, n-1);\n if(abs(maxi1 - mini2) >= valueDifference) {\n int I = find(nums.begin(), nums.begin()+i, maxi1) - nums.begin();\n int J = find(nums.begin()+j, nums.end(), mini2) - nums.begin();\n return {I, J};\n } \n if(abs(mini1 - maxi2) >= valueDifference) {\n int I = find(nums.begin(), nums.begin()+i, mini1) - nums.begin();\n int J = find(nums.begin()+j, nums.end(), maxi2) - nums.begin();\n return {I, J};\n }\n j++;\n i++;\n }\n return {-1, -1};\n }\n};\n```
2
0
['Segment Tree', 'C++']
0
find-indices-with-index-and-value-difference-ii
[Java] 2ms, 88%, Sliding Window + CLEAN CODE
java-2ms-88-sliding-window-clean-code-by-f0hf
Approach\n1. Fail fast: if indexDiff >= nums.length, then return {-1,-1} as you cannot have such distant indices\n2. Looking at the indexDiff, you realise that
StefanelStan
NORMAL
2023-11-30T21:33:02.370370+00:00
2023-11-30T21:33:02.370391+00:00
50
false
# Approach\n1. Fail fast: if indexDiff >= nums.length, then return {-1,-1} as you cannot have such distant indices\n2. Looking at the indexDiff, you realise that if you pick i [0..n-indexDiff], then the next available number you can chose if after i + indexDiff.\n - Thus, we observe a gap/window: the other index must be outside this window\n3. If your right index is [indexDiff], then your left index is 0. \n - If your right index is [indedDiff +1], then your left indices could be [0, 1].\n4. We observe a pattern: if the right index is indexDiff + x, then the left side valid indices are between [0, x]\n5. The most relevant numbers to consider on the left side are min and max. Because Abs(max - nums[indexDiff + x]) OR abs(min - nums[indexDiff + x]) most probably will give you a diff greater than the valueDiff.\n6. Using such a window, traverse the array and keep track of min/max of the left index. Calculate abs(max - [rightIndex]) & abs(min-[rightIndex]). Stop when you find a valid combination.\n\n# Complexity\n- Time complexity:$$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int[] findIndices(int[] nums, int indexDifference, int valueDifference) {\n if (indexDifference >= nums.length) {\n return new int[]{-1,-1};\n }\n int minValue = Integer.MAX_VALUE, minIndex = 0;\n int maxValue = Integer.MIN_VALUE, maxIndex = 0;\n for (int i = nums.length - indexDifference - 1, j = nums.length -1; i >= 0; i--, j--) {\n if (nums[j] < minValue) {\n minValue = nums[j];\n minIndex = j;\n }\n if (nums[j] > maxValue) {\n maxValue = nums[j];\n maxIndex = j;\n }\n if (Math.abs(nums[i] - minValue) >= valueDifference) {\n return new int[]{i, minIndex};\n }\n if (Math.abs(nums[i] - maxValue) >= valueDifference) {\n return new int[]{i, maxIndex};\n }\n }\n return new int[]{-1, -1};\n }\n}\n```
2
0
['Two Pointers', 'Java']
0
find-indices-with-index-and-value-difference-ii
Best Java Solution || Beats 100%
best-java-solution-beats-100-by-ravikuma-bghn
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
ravikumar50
NORMAL
2023-10-15T07:34:32.044780+00:00
2023-10-15T07:34:32.044799+00:00
158
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int[] findIndices(int[] arr, int idxDiff, int diff) {\n int n = arr.length;\n\n int max = 0;\n int min = 0;\n\n for(int i=idxDiff; i<n; i++){\n if(arr[i-idxDiff]<arr[min]) min = i-idxDiff;\n if(arr[i-idxDiff]>arr[max]) max = i-idxDiff;\n\n if(arr[i]-arr[min]>=diff) return new int[]{min,i};\n if(arr[max]-arr[i]>=diff) return new int[]{max,i};\n }\n return new int[]{-1,-1};\n }\n}\n```
2
0
['Java']
0
find-indices-with-index-and-value-difference-ii
🔥🔥🔥 Python Simple Solution 🔥🔥🔥
python-simple-solution-by-hululu0405-hk8i
Brute force\n# Intuition\n Describe your first thoughts on how to solve this problem. \nCheck all combination in array.\n# Approach\n Describe your approach to
hululu0405
NORMAL
2023-10-15T06:31:21.656206+00:00
2023-10-16T02:11:56.108761+00:00
167
false
# Brute force\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nCheck all combination in array.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nGo through the array.\n# Complexity\n- Time complexity: O(n^2)\n- Space complexity: O(1)\n# Code\n```\nclass Solution:\n def findIndices(self, nums: List[int], indexDifference: int, valueDifference: int) -> List[int]:\n for i in range(len(nums)):\n for j in range(i+indexDifference, len(nums)):\n if abs(nums[i] - nums[j]) >= valueDifference:\n return[i, j]\n return [-1, -1]\n\n```\n\n# One pass\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIf there is a qualifying number before `indexDifference`, then the maximum or minimum value must satisfy the condition.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nRecord the maximum and minimum before `indexDifference` and check if any of them meet the condition.\n# Complexity\n- Time complexity: O(n)\n- Space complexity: O(1)\n# Code\n```\nclass Solution:\n def findIndices(self, nums: List[int], indexDifference: int, valueDifference: int) -> List[int]:\n prevMax, maxIdx = -float(\'inf\'), -1\n prevMin, minIdx = float(\'inf\'), -1\n \n for i in range(indexDifference, len(nums)):\n if nums[i-indexDifference] > prevMax:\n prevMax, maxIdx = nums[i-indexDifference], i-indexDifference\n if nums[i-indexDifference] < prevMin:\n prevMin, minIdx = nums[i-indexDifference], i-indexDifference\n if nums[i] - prevMin >= valueDifference:\n return [minIdx, i]\n if prevMax - nums[i] >= valueDifference:\n return [maxIdx, i]\n\n return [-1, -1]\n\n```
2
0
['Python3']
1
find-indices-with-index-and-value-difference-ii
One pass by record left_min index and left_max index
one-pass-by-record-left_min-index-and-le-a6gn
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
pohanchi
NORMAL
2023-10-15T04:07:46.007385+00:00
2023-10-15T04:07:46.007403+00:00
212
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def findIndices(self, nums: List[int], indexDifference: int, valueDifference: int) -> List[int]:\n \n left_min = 0\n left_max = 0\n right_min = 0\n right_max = 0\n \n for i in range(indexDifference,len(nums)):\n \n if nums[int(i-indexDifference)] < nums[int(left_min)]:\n left_min = int(i-indexDifference)\n if nums[int(i - indexDifference)] > nums[int(left_max)]:\n left_max = int(i-indexDifference)\n \n if nums[i] - nums[left_min] >= valueDifference:\n return [left_min, i]\n \n if nums[left_max] - nums[i] >= valueDifference:\n return [left_max, i]\n \n return [-1, -1]\n \n \n```
2
1
['Python3']
0
find-indices-with-index-and-value-difference-ii
Python/Rust/Go, O(n) time, O(1) space with explanation
pythonrustgo-on-time-o1-space-with-expla-d6ym
Intuition\n\nLets look at some array $v_0, v_1, v_2, ... v_n$ and take a look at some position $v_i$. How can we tell that index $i$ will be a part of the resul
salvadordali
NORMAL
2023-10-15T04:07:37.006743+00:00
2023-10-16T23:07:24.634075+00:00
168
false
# Intuition\n\nLets look at some array $v_0, v_1, v_2, ... v_n$ and take a look at some position $v_i$. How can we tell that index $i$ will be a part of the result? For this to happen, there should be some position `j <= i - diff_i` for which `|nums[j] - nums[i]| >= diff_v`.\n\nTo not check for every index, we can just store the indexes of minimum and maximum value so far and check against them. So all we need is to check every position i in array and:\n - update `min_i` if `nums[i - diff_i] < nums[min_i]`\n - update `max_i` if `nums[i - diff_i] > nums[max_i]`\n - return `i, min_i` if `nums[i] - nums[min_i] >= diff_v`\n - return `i, max_i` if `nums[max_i] - nums[i] >= diff_v`\n\nOtherwise we have not found it.\n\n# Complexity\n- Time complexity: $O(n)$\n- Space complexity: $O(1)$\n\n# Code\n```Go []\nfunc findIndices(nums []int, diff_i int, diff_v int) []int {\n min_i, max_i := 0, 0\n for i := diff_i; i < len(nums); i++ {\n if nums[i - diff_i] < nums[min_i] {\n min_i = i - diff_i\n }\n if nums[i - diff_i] > nums[max_i] {\n max_i = i - diff_i\n }\n\n if nums[i] - nums[min_i] >= diff_v {\n return []int{i, min_i}\n }\n\n if nums[max_i] - nums[i] >= diff_v {\n return []int{i, max_i}\n }\n }\n\n return []int{-1, -1}\n}\n```\n```python []\nclass Solution:\n def findIndices(self, nums: List[int], diff_i: int, diff_v: int) -> List[int]:\n min_i, max_i = 0, 0\n for i in range(diff_i, len(nums)):\n if nums[i - diff_i] < nums[min_i]:\n min_i = i - diff_i\n if nums[i - diff_i] > nums[max_i]:\n max_i = i - diff_i\n \n if nums[i] - nums[min_i] >= diff_v:\n return [min_i, i]\n if nums[max_i] - nums[i] >= diff_v:\n return [max_i, i]\n \n return [-1, -1]\n```\n```Rust []\nimpl Solution {\n pub fn find_indices(nums: Vec<i32>, diff_i: i32, diff_v: i32) -> Vec<i32> {\n let diff_i = diff_i as usize;\n let (mut min_i, mut max_i) = (0, 0);\n\n for i in diff_i .. nums.len() {\n if nums[i - diff_i] < nums[min_i] {\n min_i = i - diff_i;\n }\n if nums[i - diff_i] > nums[max_i] {\n max_i = i - diff_i;\n }\n\n if nums[i] - nums[min_i] >= diff_v {\n return vec![i as i32, min_i as i32];\n }\n if nums[max_i] - nums[i] >= diff_v {\n return vec![i as i32, max_i as i32];\n }\n }\n\n return vec![-1, -1];\n }\n}\n```\n
2
0
['Go', 'Python3', 'Rust']
0
find-indices-with-index-and-value-difference-ii
[c++] one pass - O(N) time O(1) space
c-one-pass-on-time-o1-space-by-akshay4gu-tfxx
Intuition\n Describe your first thoughts on how to solve this problem. \nyou just need the min or max value till i - indexDifference\n\n# Approach\n Describe yo
Akshay4Gupta
NORMAL
2023-10-15T04:06:08.014607+00:00
2023-10-15T04:06:34.723566+00:00
149
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nyou just need the min or max value till `i - indexDifference`\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- for each i\n - keep finding the min and max for `i - indexDifference`\n - and check if abs difference between the element and min / max `>= valueDifference`\n\n\n# Complexity\n- Time complexity: `O(n)`\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: `O(1)`\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> findIndices(vector<int>& nums, int indexDifference, int valueDifference) {\n int leftMin = 0, leftMax = 0;\n for(int i = indexDifference; i < nums.size(); i++) {\n if (nums[leftMin] > nums[i - indexDifference]) leftMin = i - indexDifference;\n else if (nums[leftMax] < nums[i - indexDifference]) leftMax = i - indexDifference;\n \n if (abs(nums[i] - nums[leftMin]) >= valueDifference) return {leftMin, i};\n if (abs(nums[i] - nums[leftMax]) >= valueDifference) return {leftMax, i};\n }\n return {-1, -1};\n }\n};\n```
2
0
['C++']
0
find-indices-with-index-and-value-difference-ii
Beats 100% | Python 3
beats-100-python-3-by-alpha2404-7o81
Please UpvoteCode
Alpha2404
NORMAL
2025-02-15T08:29:58.939559+00:00
2025-02-15T08:29:58.939559+00:00
35
false
# Please Upvote # Code ```python3 [] __import__("atexit").register(lambda: open("display_runtime.txt", "w").write("0")) class Solution: def findIndices(self, nums: List[int], indexDifference: int, valueDifference: int) -> List[int]: mn = mx = -1 for i, x in enumerate(nums): if i>= indexDifference: if mn==-1 or nums[i-indexDifference] < nums[mn]: mn = i-indexDifference if mx == -1 or nums[i-indexDifference]>nums[mx]: mx=i-indexDifference if x-nums[mn] >= valueDifference: return [mn,i] if nums[mx] - x >= valueDifference: return [mx,i] return [-1,-1] ```
1
0
['Python3']
0
find-indices-with-index-and-value-difference-ii
python solution
python-solution-by-ayoublaar-phyi
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
AyoubLaar
NORMAL
2024-09-07T18:30:50.517488+00:00
2024-09-07T18:30:50.517523+00:00
15
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n^2)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n# Code\n```python3 []\nclass Solution:\n def findIndices(self, nums: List[int], indexDifference: int, valueDifference: int) -> List[int]:\n i = 0\n while i < len(nums): \n while i < len(nums) and nums[i] < valueDifference:\n i+=1\n if i == len(nums):\n break\n j = 0\n while j <= i - indexDifference:\n if abs(nums[i] - nums[j]) >= valueDifference:\n return [i,j]\n j+=1\n j = i + indexDifference\n while j < len(nums):\n if abs(nums[i] - nums[j]) >= valueDifference:\n return [i,j]\n j+=1\n i+=1\n return [-1,-1]\n```
1
0
['Python3']
0
find-indices-with-index-and-value-difference-ii
Detailed Explanation
detailed-explanation-by-rengubareva-rbkw
Intuition\n1. For i-th element check elements with indexes j: abs(j-i) >= indexDifference\n2. If there is elements which is: abs(nums[i] - nums[j]) >= valueDiff
rengubareva
NORMAL
2024-06-25T13:09:29.602797+00:00
2024-06-25T13:09:29.602821+00:00
134
false
# Intuition\n1. For i-th element check elements with indexes j: ```abs(j-i) >= indexDifference```\n2. If there is elements which is: ```abs(nums[i] - nums[j]) >= valueDifference``` ```return {i, j}```, otherwise continue to check each element till the end of the array.\n3. if there is no such elements, ```return {-1, -1}```\n\n```\nint n = nums.length;\nfor (int i = 0; i < n; i++){\n int j = i + indexDifference;\n while (j < n){\n if(Math.abs(j - i) >= indexDifference \n & Math.abs(nums[i] - nums[j]) >= valueDifference){\n return new int[]{i, j};\n }\n j++;\n }\n}\nreturn new int[]{-1, -1};\n```\nTime complexity: ```O(n^2)```\n\n# Approach\n\n1. The main idea to reduce complexity is to maintain a window of size indexDifference and slides it across the array. This way we don\'t need to check indexDifference condition. \n2. Tracking minimum and maximum values within this sliding window. \n3. Compare current value with maximum and minimum to determine if the value difference condition is met. \n\n# Complexity\n- Time complexity: ```O(n)```\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: ```O(1)```\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int[] findIndices(int[] nums, int indexDifference, int valueDifference) {\n\n int n = nums.length;\n int minIndex = 0;\n int maxIndex = 0;\n \n\n for (int i = indexDifference; i < n; i++){\n if (nums[i - indexDifference] < nums[minIndex]) {\n minIndex = i - indexDifference;\n }\n if (nums[i - indexDifference] > nums[maxIndex]) {\n maxIndex = i - indexDifference;\n }\n \n \n if (Math.abs(nums[i] - nums[minIndex]) >= valueDifference) {\n return new int[]{i, minIndex};\n }\n if (Math.abs(nums[i] - nums[maxIndex]) >= valueDifference) {\n return new int[]{i, maxIndex};\n }\n }\n return new int[]{-1, -1};\n }\n}\n```
1
0
['Sliding Window', 'Java']
1
find-indices-with-index-and-value-difference-ii
Python | O(nlogn) | Priority Queue
python-onlogn-priority-queue-by-mandeepg-nz0i
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
mandeepgoyal
NORMAL
2023-10-24T16:03:16.447839+00:00
2023-10-24T16:03:16.447866+00:00
22
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(NlogN)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n\n- Space complexity: O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def findIndices(self, nums: List[int], indexDifference: int, valueDifference: int) -> List[int]:\n \n H1=[(nums[i],i) for i in range(indexDifference,len(nums))] # it will give me the smallest to largest (min heap)\n H2=[(-1*nums[i],i) for i in range(indexDifference,len(nums))] # it will give me the largest to smallest (max heap)\n heapq.heapify(H1)\n heapq.heapify(H2)\n for i in range(len(nums)-indexDifference):\n while abs(H1[0][1]-i)<indexDifference:\n heapq.heappop(H1)\n while abs(H2[0][1]-i)<indexDifference:\n heapq.heappop(H2)\n if abs(H1[0][0]-nums[i])>=valueDifference:\n return [i,H1[0][1]]\n if abs(-1*H2[0][0]-nums[i])>=valueDifference:\n return [i,H2[0][1]]\n return [-1,-1]\n```
1
0
['Heap (Priority Queue)', 'Python3']
0
find-indices-with-index-and-value-difference-ii
Find Indices With Index and Value Difference II - Easy Java Solution
find-indices-with-index-and-value-differ-4pva
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
whopiyushanand
NORMAL
2023-10-18T07:59:01.775956+00:00
2023-10-18T07:59:01.775978+00:00
54
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int[] findIndices(int[] nums, int indexDifference, int valueDifference) {\n int n = nums.length;\n List<Pair> maxs = new ArrayList<>();\n List<Pair> mins = new ArrayList<>();\n \n for(int i=0; i<n; i++){\n maxs.add(new Pair(nums[i], i));\n mins.add(new Pair(nums[i], i));\n }\n for(int i=n-2; i>=0; i--){\n maxs.set(i, max(maxs.get(i), maxs.get(i+1)));\n mins.set(i, min(mins.get(i), mins.get(i+1)));\n }\n \n for(int i=0; i<n-indexDifference; i++){\n Pair maxPair = maxs.get(i + indexDifference);\n int val = maxPair.key;\n int idx = maxPair.value;\n \n if(Math.abs(val - nums[i]) >= valueDifference){\n return new int[]{i, idx};\n }\n \n Pair minPair = mins.get(i+indexDifference);\n val = minPair.key;\n idx = minPair.value;\n if(Math.abs(val - nums[i]) >= valueDifference){\n return new int[]{i, idx};\n }\n }\n return new int[]{-1, -1};\n \n }\n private Pair max(Pair p1, Pair p2){\n if(p1.key> p2.key){\n return p1;\n }else{\n return p2;\n }\n }\n private Pair min(Pair p1, Pair p2){\n if(p1.key < p2.key){\n return p1;\n }else{\n return p2;\n }\n }\n}\nclass Pair{\n int key;\n int value;\n \n public Pair(int key, int value){\n this.key = key;\n this.value = value;\n }\n}\n\n```
1
0
['Array', 'Java']
0
find-indices-with-index-and-value-difference-ii
Same as problem 2903 | java O(n) | Prefix sum
same-as-problem-2903-java-on-prefix-sum-e6x0s
Intuition\nSee\uFF1A https://leetcode.com/problems/find-indices-with-index-and-value-difference-i/solutions/4170252/java-o-n-prefix-sum-100/\n Describe your fir
ly2015cntj
NORMAL
2023-10-17T03:07:57.302927+00:00
2023-10-17T03:08:47.943094+00:00
21
false
# Intuition\nSee\uFF1A https://leetcode.com/problems/find-indices-with-index-and-value-difference-i/solutions/4170252/java-o-n-prefix-sum-100/\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n- O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n- O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n// AC: Runtime Details 29ms Beats 38.97%of users with Java\n// Memory Details 60.83MB Beats 19.59%of users with Java\n// Prefix sum: same as leetcode2903 @see: https://leetcode.com/problems/find-indices-with-index-and-value-difference-i/description/\n// T:O(n), S:O(1)\n// \nclass Solution {\n public int[] findIndices(int[] nums, int indexDifference, int valueDifference) {\n int[] ret = new int[]{-1, -1};\n int len = nums.length;\n if (len == 1) {\n // side case\n if (indexDifference == 0 && valueDifference == 0) {\n ret = new int[]{0, 0};\n }\n return ret;\n }\n HashMap<Integer, Integer> valueToIndex = new HashMap<>();\n int[] suffixMin = new int[len], suffixMax = new int[len];\n for (int i = len - 1; i >= 0; i--) {\n if (i == len - 1) {\n suffixMin[i] = nums[i];\n suffixMax[i] = nums[i];\n } else {\n suffixMin[i] = Math.min(nums[i], suffixMin[i + 1]);\n suffixMax[i] = Math.max(nums[i], suffixMax[i + 1]);\n }\n valueToIndex.putIfAbsent(nums[i], i);\n }\n// System.out.println(Arrays.toString(suffixMin));\n// System.out.println(Arrays.toString(suffixMax));\n// System.out.println(valueToIndex);\n\n for (int i = 0; i + indexDifference < len; i++) {\n int suffixMinVal = suffixMin[i + indexDifference], suffixMaxVal = suffixMax[i + indexDifference];\n if (Math.abs(nums[i] - suffixMinVal) >= valueDifference) {\n ret[0] = i;\n ret[1] = valueToIndex.get(suffixMinVal);\n// System.out.println("1" + Arrays.toString(ret));\n return ret;\n }\n if (Math.abs(nums[i] - suffixMaxVal) >= valueDifference) {\n ret[0] = i;\n ret[1] = valueToIndex.get(suffixMaxVal);\n System.out.println("2" + Arrays.toString(ret));\n return ret;\n }\n }\n\n return ret;\n }\n}\n\n```
1
0
['Java']
0
find-indices-with-index-and-value-difference-ii
Simple and easy || min-max || O(n)
simple-and-easy-min-max-on-by-spats7-lbkz
```\nclass Solution {\n public int[] findIndices(int[] nums, int indexDifference, int valueDifference) {\n int n = nums.length;\n int[][] minMa
spats7
NORMAL
2023-10-16T21:26:09.227671+00:00
2023-10-16T21:26:09.227695+00:00
299
false
```\nclass Solution {\n public int[] findIndices(int[] nums, int indexDifference, int valueDifference) {\n int n = nums.length;\n int[][] minMax = new int[n][4];\n \n minMax[n-1][0] = nums[n-1];\n minMax[n-1][1] = n-1;\n \n minMax[n-1][2] = nums[n-1];\n minMax[n-1][3] = n-1;\n \n for(int i=n-2; i>=0; i--){\n minMax[i][0] = nums[i];\n minMax[i][1] = i;\n\n minMax[i][2] = nums[i];\n minMax[i][3] = i;\n \n if(nums[i] < minMax[i+1][0]){\n minMax[i][0] = minMax[i+1][0];\n minMax[i][1] = minMax[i+1][1];\n }\n if(nums[i] > minMax[i+1][2]){\n minMax[i][2] = minMax[i+1][2];\n minMax[i][3] = minMax[i+1][3];\n }\n }\n for(int i=0; i<n-indexDifference; i++){\n int diff = Math.abs(nums[i] - minMax[i+indexDifference][0]);\n if(diff >= valueDifference)\n return new int[]{i, minMax[i+indexDifference][1]};\n \n diff = Math.abs(nums[i] - minMax[i+indexDifference][2]);\n if(diff >= valueDifference)\n return new int[]{i, minMax[i+indexDifference][3]};\n }\n return new int[]{-1, -1};\n }\n}
1
0
['Array', 'Java']
0
find-indices-with-index-and-value-difference-ii
C#: O(n)
c-on-by-igor0-5kmy
Intuition\nGo from the end to the begin of the array nums. Keep the min and max.\n\n# Approach\nGo from the end to the indexDifference position of the array num
igor0
NORMAL
2023-10-16T16:16:40.169338+00:00
2023-10-16T16:16:40.169365+00:00
19
false
# Intuition\nGo from the end to the begin of the array `nums`. Keep the min and max.\n\n# Approach\nGo from the end to the `indexDifference` position of the array `nums`\n```\nfor (int i = nums.Length - 1; i >= indexDifference; i--)\n{\n```\nBy each iteration change the min and max:\n```\n min = Math.Min(min, nums[i]);\n max = Math.Max(max, nums[i]);\n```\nCalculate the second index if the first index is found:\n```\nif (Math.Abs(nums[i - indexDifference] - min) >= valueDifference)\n{\n for (int j = i; j < nums.Length; j++)\n {\n if (Math.Abs(nums[i - indexDifference] - nums[j]) >= valueDifference)\n {\n return new[]{i - indexDifference, j};\n }\n }\n}\n```\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\npublic class Solution {\n public int[] FindIndices(int[] nums, int indexDifference, int valueDifference) {\n var min = nums[nums.Length - 1];\n var max = nums[nums.Length - 1];\n for (int i = nums.Length - 1; i >= indexDifference; i--)\n {\n min = Math.Min(min, nums[i]);\n max = Math.Max(max, nums[i]);\n if (Math.Abs(nums[i - indexDifference] - min) >= valueDifference)\n {\n for (int j = i; j < nums.Length; j++)\n {\n if (Math.Abs(nums[i - indexDifference] - nums[j]) >= valueDifference)\n {\n return new[]{i - indexDifference, j};\n }\n }\n }\n if (Math.Abs(nums[i - indexDifference] - max) >= valueDifference)\n {\n for (int j = i; j < nums.Length; j++)\n {\n if (Math.Abs(nums[i - indexDifference] - nums[j]) >= valueDifference)\n {\n return new[]{i - indexDifference, j};\n }\n }\n }\n }\n return new[]{-1, -1};\n }\n}\n```
1
0
['Prefix Sum', 'C#']
0
find-indices-with-index-and-value-difference-ii
C++ || Two Pointer || without set or heap
c-two-pointer-without-set-or-heap-by-moh-8j1m
Intuition\nMaintaining minimum and maximum element in range [0 i-indexDifference]\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(1)\n# Code
mohaldarprakash
NORMAL
2023-10-15T10:13:57.643193+00:00
2023-10-15T10:13:57.643225+00:00
277
false
# Intuition\nMaintaining minimum and maximum element in range [0 i-indexDifference]\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(1)\n# Code\n```\nfunc abs(n int) int {\n if n < 0 {\n return -n\n }\n return n\n}\n\nfunc findIndices(nums []int, indexDifference int, valueDifference int) []int {\n j1, j2, i := 0, 0, indexDifference\n\n\n ans := make([]int, 2)\n ans[0] = -1\n ans[1] = -1\n\n for i<len(nums) {\n curr := i - indexDifference\n\n if nums[curr] >= nums[j2] {\n j2 = curr\n }\n if nums[curr] <= nums[j1] {\n j1 = curr\n }\n\n if abs(nums[i] - nums[j1]) >= valueDifference { \n ans[0] = i\n ans[1] = j1\n break\n }\n if abs(nums[i] - nums[j2]) >= valueDifference { \n ans[0] = i\n ans[1] = j2\n break\n }\n i++\n }\n return ans\n}\n```
1
0
['Two Pointers', 'Go']
0