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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
snakes-and-ladders | C++ || BFS || Easy To Understand || Beginner Friendly | c-bfs-easy-to-understand-beginner-friend-d4yz | \nclass Solution {\npublic:\n int snakesAndLadders(vector<vector<int>>& board) {\n int n = board.size();\n \n // store the position of e | Tyfoon | NORMAL | 2023-01-24T03:53:47.470321+00:00 | 2023-01-24T03:53:47.470350+00:00 | 451 | false | ```\nclass Solution {\npublic:\n int snakesAndLadders(vector<vector<int>>& board) {\n int n = board.size();\n \n // store the position of each cell in a map\n map<int,pair<int,int>> mp;\n int goal = 1;\n int t = 1;\n for(int i=n-1; i>= 0; i--){\n if(t == 0){\n for(int j=n-1 ; j>=0 ; j--){\n mp[goal++] = {i, j};\n }\n }\n else{\n for(int j=0; j< n; j++){\n mp[goal++] = {i, j};\n }\n }\n \n t ^= 1;\n }\n \n // Visited Array to mark the cell we have already visited\n vector<int> vis(n*n + 1 , 0);\n queue<int> q;\n q.push(1);\n \n goal = (n*n);\n int move = 0;\n \n while(q.size()){\n int sz = q.size();\n \n while(sz--){\n int cur = q.front(); q.pop();\n \n if(cur == goal ) return move; // Goal is Reached then return the number of moves\n \n vis[cur] = 1;\n \n \n \n for(int next = cur + 1 ; next <= min(cur + 6,goal) ; next++ ){\n \n \n auto pos = mp[next];\n \n \n // Case : The Cell has a Ladder or Snake\n if(board[pos.first][pos.second] != -1){\n int nxx = board[pos.first][pos.second];\n if(!vis[nxx]){\n q.push(nxx);\n vis[nxx] = 1;\n }\n }\n \n // Case : The Cell doesn\'t have any Ladder or Snake\n else{\n if(!vis[next]){\n q.push(next);\n vis[next] = 1;\n }\n }\n }\n \n \n }\n \n move++;\n }\n \n return -1;\n }\n};\n```\n**Time Complexity: O ( N^2 )**\n**Auxiliary Space: O(N^2)**\n\n\n | 3 | 0 | ['Breadth-First Search', 'C++'] | 0 |
snakes-and-ladders | C++ | BFS | video solution | c-bfs-video-solution-by-alien35-fype | Intuition & Approach\nhttps://youtu.be/2borKYoRgJw\n\n# Code\n\nclass Solution {\npublic:\n int snakesAndLadders(vector<vector<int>>& board) {\n int n | Alien35 | NORMAL | 2023-01-24T02:25:29.356970+00:00 | 2023-01-24T02:25:29.357002+00:00 | 1,539 | false | # Intuition & Approach\nhttps://youtu.be/2borKYoRgJw\n\n# Code\n```\nclass Solution {\npublic:\n int snakesAndLadders(vector<vector<int>>& board) {\n int n = board.size();\n \n vector<pair<int, int>> idxs(n * n + 1);\n int idx = 1;\n \n vector<int> cols(n);\n iota(cols.begin(), cols.end(), 0);\n \n for (int row = n - 1; row >= 0; --row) {\n for (auto col : cols)\n idxs[idx++] = {row, col};\n \n reverse(cols.begin(), cols.end());\n }\n\n return BFS(n, idxs, board);\n }\n\n int BFS(int n, vector<pair<int, int>> &idxs, vector<vector<int>> &board) {\n vector<int> dis(n * n + 1, -1);\n\n queue<int> qu;\n dis[1] = 0;\n qu.push(1);\n\n while (!qu.empty()) {\n int cur = qu.front();\n qu.pop();\n\n int m = min(cur + 6, n * n);\n for (int cell = cur + 1; cell <= m; ++cell) {\n auto [row, col] = idxs[cell];\n int nxt = board[row][col] != -1 ? board[row][col] : cell;\n\n if (dis[nxt] == -1) {\n dis[nxt] = dis[cur] + 1;\n qu.push(nxt);\n }\n }\n }\n\n return dis[n * n];\n }\n};\n``` | 3 | 0 | ['C++'] | 0 |
snakes-and-ladders | BFS SOLUTION JAVA :) ! | bfs-solution-java-by-mutablestringz-w4kv | Since constraints are low, just simulate this process with a bfs and you will come to your answer in the minimum number of moves possible! Quite a lot of code, | MutableStringz | NORMAL | 2023-01-24T01:26:19.404432+00:00 | 2023-01-24T01:26:19.404461+00:00 | 746 | false | Since constraints are low, just simulate this process with a bfs and you will come to your answer in the minimum number of moves possible! Quite a lot of code, but not a hard concept. See below for implementation and upvote if you liked!\n\n# Code\n```\nclass Solution {\n public int snakesAndLadders(int[][] board) {\n int n = board.length;\n int d = n*n;\n HashMap<Integer,Integer> map = new HashMap<>();\n Queue<Pair> q = new ArrayDeque<>();\n Set<Integer> visited = new HashSet<>();\n int square = 1;\n boolean r = true;\n //read board in, since we have to go back and forth\n for(int i = n - 1; i >= 0; i--){\n if(r){\n int j = 0;\n while(j < n){\n if(board[i][j] != -1){\n map.put(square,board[i][j]);\n }\n square++;\n j++;\n }\n r = false;\n }else{\n int j = n-1;\n while(j >= 0){\n if(board[i][j] != -1){\n map.put(square,board[i][j]);\n }\n square++;\n j--;\n }\n r = true;\n }\n }\n //keep track of the distance we have to each square\n q.offer(new Pair(1,0));\n visited.add(1);\n while(!q.isEmpty()){\n Pair p = q.poll();\n int sq = p.val;\n int moves = p.dist;\n System.out.println(sq + " " + moves);\n if(sq == n*n) return moves;\n //simulate the dice roll here, only add if we \n // haven\'t been here before and are in the bounds\n for(int i = 1; i <= 6; i++){\n int ns = sq + i;\n if(map.containsKey(ns)){\n ns = map.get(ns);\n }\n if(ns <= n*n && !visited.contains(ns)){\n q.offer(new Pair(ns,moves+1));\n visited.add(ns);\n }\n }\n }\n return -1;\n }\n //neat way to handle pairs in java that is not a pain\n static class Pair{\n int val;\n int dist;\n public Pair(int v, int d){\n this.val = v;\n this.dist = d;\n }\n }\n}\n\n\n\n\n``` | 3 | 0 | ['Java'] | 1 |
snakes-and-ladders | C++ Solution || Easy || BFS || Unordered Map | c-solution-easy-bfs-unordered-map-by-inr-xp1b | \n# Code\n\nclass Solution {\npublic:\n int snakesAndLadders(vector<vector<int>>& board) {\n int n = board.size();\n unordered_map<int,int> mp; | inrittik | NORMAL | 2022-12-24T06:17:04.707861+00:00 | 2022-12-24T06:17:04.707909+00:00 | 115 | false | \n# Code\n```\nclass Solution {\npublic:\n int snakesAndLadders(vector<vector<int>>& board) {\n int n = board.size();\n unordered_map<int,int> mp; // map box number to the value it holds\n int steps = 1, dir=0;\n for(int i=n-1; i>=0; --i){\n for(int j=0; j<n && dir==0; ++j){\n mp[steps] = board[i][j];\n steps++;\n }\n for(int j=n-1; j>=0 && dir==1; --j){\n mp[steps] = board[i][j];\n steps++;\n }\n dir = !dir;\n }\n steps = 0;\n // Simple BFS implementation\n queue<int> q;\n vector<int> vis(n*n);\n q.push(1);\n while(!q.empty()){\n int sz = q.size();\n steps++;\n while(sz--){\n int curr = q.front(); q.pop();\n if(vis[curr-1]) continue;\n if(curr==n*n) return steps-1;\n for(int i=1; i<=min(6,n*n); ++i){\n if(mp[curr+i]==-1) q.push(curr+i);\n else q.push(mp[curr+i]);\n }\n vis[curr-1]=1;\n }\n }\n return -1;\n }\n};\n``` | 3 | 0 | ['C++'] | 1 |
snakes-and-ladders | Easy to understand JavaScript solution (BFS) | easy-to-understand-javascript-solution-b-up2e | \nvar snakesAndLadders = function(board) {\n const { length: n } = board;\n const DESTINATION = n * n;\n const visited = new Set();\n const queue = | tzuyi0817 | NORMAL | 2022-12-03T08:56:16.089907+00:00 | 2023-01-28T07:46:24.186402+00:00 | 419 | false | ```\nvar snakesAndLadders = function(board) {\n const { length: n } = board;\n const DESTINATION = n * n;\n const visited = new Set();\n const queue = [1];\n let result = 0;\n\n while (queue.length) {\n const size = queue.length;\n\n for (let index = 0; index < size; index++) {\n const square = queue.shift();\n if (square === DESTINATION) return result;\n \n for (let decide = 1; decide <= 6; decide++) {\n const moveTo = square + decide;\n if (moveTo > DESTINATION) break;\n const { row, col } = getPosition(moveTo);\n const nextSquare = board[row][col] === -1 ? moveTo : board[row][col];\n if (visited.has(nextSquare)) continue;\n\n queue.push(nextSquare);\n visited.add(nextSquare);\n }\n }\n result += 1;\n }\n return -1;\n\n function getPosition(square) {\n const row = (square - 1) / n | 0;\n const col = (square - 1) % n;\n\n return {\n row: n - row - 1,\n col: row % 2 ? n - col - 1 : col,\n };\n }\n};\n``` | 3 | 0 | ['JavaScript'] | 1 |
snakes-and-ladders | Why can't be this done using DFS with dp optimization | why-cant-be-this-done-using-dfs-with-dp-nwzph | I was trying to go for the DFS approach and I can\'t figure out why is it not working\n\nclass Solution {\npublic:\n int func(vector<int>&linear,int index,ve | Suyash07 | NORMAL | 2022-11-08T20:12:18.122537+00:00 | 2022-11-08T20:12:18.122582+00:00 | 922 | false | I was trying to go for the DFS approach and I can\'t figure out why is it not working\n```\nclass Solution {\npublic:\n int func(vector<int>&linear,int index,vector<int>&dp)\n {\n if(index>=linear.size()-1)return 0;\n if(index<0 )return 100000;\n \n \n if(linear[index]==-2)return 100000;\n \n if(linear[index]!=-1)\n { \n int jump;jump=linear[index]-1;\n int prev;prev=linear[index];\n linear[index]=-2;\n int g=func(linear,jump,dp);\n linear[index]=prev;\n return dp[index]=g;\n \n }\n int mini;mini=100000;\n for(int i=1;i<=6;i++)\n { \n int x=func(linear,index+i,dp)+1;\n mini=min(x,mini);\n }\n \n return dp[index]=mini;\n \n }\n int snakesAndLadders(vector<vector<int>>& board) {\n \n \n vector<int>linear;\n int cnt;cnt=0;\n if(board[0][0]!=-1)return -1;\n for(int i=0;i<board.size();i++)\n { if(cnt==0){\n for(int j=0;j<board[0].size();j++)\n {\n linear.push_back(board[i][j]);\n }\n cnt=1;\n }\n else if(cnt==1)\n {\n for(int j=board[0].size()-1;j>=0;j--)\n {\n linear.push_back(board[i][j]);\n }\n cnt=0;\n }\n \n }\n \n reverse(linear.begin(),linear.end());\n vector<int>dp(linear.size(),-1);\n return func(linear,0,dp);\n return 0;\n }\n};\n```\nI have used the DFS backtracking and it is giving qrong answer for the test-case\n[[-1,-1,2,21,-1],[16,-1,24,-1,4],[2,3,-1,-1,-1],[-1,11,23,18,-1],[-1,-1,-1,23,-1]]\nCorrect Answer: 2\nCode Output: 3 | 3 | 0 | ['Dynamic Programming', 'Depth-First Search', 'Graph'] | 3 |
snakes-and-ladders | Standard BFS approach || C++ Solution | standard-bfs-approach-c-solution-by-agra-jx4y | This a standard bfs problem. The only tricky part about this question is to get cell coordinates (row,col) from the cell value. To get cell coordinates, i\'ve m | agraj_23 | NORMAL | 2022-06-14T12:53:01.269506+00:00 | 2022-06-15T08:54:43.765184+00:00 | 259 | false | This a standard bfs problem. The only tricky part about this question is to get cell coordinates (row,col) from the cell value. To get cell coordinates, i\'ve made a separate function which will clearly demonstrate how to get the coordinates. You can look at the rest of the code, you will not find any difference compared to the textbook bfs code.\n\nDo upvote, if it helps you!\n\n**C++ code :**\n\n\n\n```\nclass Solution {\npublic:\n vector<int> findCoordinates(int n,int position) { // function to get cell coordinates\n vector<int> ans(2);\n int r= n-(position-1)/n-1;\n int c=(position-1)%n;\n if(r%2==n%2) { // since there is a reversal in cell position after every row,\n c=n-c-1; // this check will take care of that\n }\n ans[0]=r;\n ans[1]=c;\n return ans;\n}\n\n\nint snakesAndLadders(vector<vector<int> >& board) {\n int n=board.size();\n vector<vector<bool> > visited(n,vector<bool>(n,false));\n queue<pair<int,int> > q;\n q.push(make_pair(1,0));\n visited[n-1][0]=true;\n while(!q.empty()) {\n\t\t\t\tint currPos=q.front().first;\n int steps=q.front().second;\n q.pop();\n if(currPos==n*n) {\n return steps;\n }\n\n for(int i=1;i<=6;i++) {\n int nextPos=currPos+i;\n if(nextPos>n*n) break;\n vector<int> temp= findCoordinates(n,nextPos);\n int r=temp[0];\n int c=temp[1];\n if(!visited[r][c]) {\n visited[r][c]=true;\n if(board[r][c]!=-1) {\n q.push(make_pair(board[r][c],steps+1));\n }\n else {\n q.push(make_pair(nextPos,steps+1));\n }\n }\n\n }\n \n \n }\n return -1;\n \n \n\t}\n\n};\n```\n | 3 | 0 | ['Breadth-First Search', 'C'] | 0 |
snakes-and-ladders | neetcode video translation | neetcode-video-translation-by-jeancalgar-3hin | \nclass Solution { \npublic:\n int snakesAndLadders(vector<vector<int>>& board) {\n int length = board.size();\n reverse(board.begin(), boar | jeancalgary | NORMAL | 2022-01-09T00:06:23.756308+00:00 | 2022-01-09T00:06:23.756347+00:00 | 117 | false | ```\nclass Solution { \npublic:\n int snakesAndLadders(vector<vector<int>>& board) {\n int length = board.size();\n reverse(board.begin(), board.end());\n function<pair<int,int>(int)> intToPos = [&](int square) {\n square -= 1;\n int r = square / length;\n int c = square % length;\n if(r % 2)\n c = length - 1 - c;\n return make_pair(r, c);\n };\n \n queue<pair<int,int>> q;\n q.push(make_pair(1, 0));\n unordered_set<int> visit{1};\n \n while(!q.empty()){\n auto q_e = q.front();\n int square = q_e.first;\n int moves = q_e.second;\n q.pop();\n \n for(int i = 1; i <= 6; ++i){\n int nextSquare = square + i;\n auto n_e = intToPos(nextSquare);\n int r = n_e.first;\n int c = n_e.second;\n if(board[r][c] != -1)\n nextSquare = board[r][c];\n if(nextSquare == length*length)\n return moves+1;\n if(!visit.count(nextSquare)){\n visit.insert(nextSquare);\n q.push(make_pair(nextSquare, moves+1));\n }\n } \n }\n \n return -1;\n }\n};\n``` | 3 | 0 | [] | 0 |
snakes-and-ladders | BFS || Queue and Visited || Java || Easy | bfs-queue-and-visited-java-easy-by-akhil-qh00 | If you like this please upvote and like\nSuggest me some more ways to do this question\n\nclass Solution {\npublic int snakesAndLadders(int[][] board) {\n | AkhilSharma24 | NORMAL | 2021-10-19T04:21:06.645533+00:00 | 2021-10-19T04:21:06.645567+00:00 | 339 | false | **If you like this please upvote and like**\n**Suggest me some more ways to do this question**\n```\nclass Solution {\npublic int snakesAndLadders(int[][] board) {\n int n = board.length;\n int steps = 0;\n Queue<Integer> q = new LinkedList<Integer>();\n boolean visited[][] = new boolean[n][n];\n q.add(1);\n visited[n-1][0] = true;\n while(!q.isEmpty()){\n int size = q.size();\n \n for(int i =0; i <size; i++){\n int x = q.poll();\n if(x == n*n) return steps;\n for(int k=1; k <=6; k++){\n if(k+x > n*n) break;\n int pos[] = findCoordinates(k+x, n);\n int r = pos[0];\n int c = pos[1];\n if(visited[r][c] == true) continue;\n visited[r][c] = true;\n if(board[r][c] == -1){\n q.add(k+x);\n }else{\n q.add(board[r][c]);\n }\n }\n }\n \n steps++;\n \n } \n return -1;\n }\n \n public int[] findCoordinates(int curr, int n) {\n int r = n - (curr - 1) / n -1;\n int c = (curr - 1) % n;\n if (r % 2 == n % 2) {\n return new int[]{r, n - 1 - c};\n } else {\n return new int[]{r, c};\n }\n }\n}\n``` | 3 | 0 | [] | 1 |
snakes-and-ladders | [Python] BFS with detailed comments | python-bfs-with-detailed-comments-by-hid-qfim | \nclass Solution:\n def snakesAndLadders(self, board: List[List[int]]) -> int:\n queue = collections.deque()\n n = len(board)\n queue.ap | hideinsea | NORMAL | 2021-10-10T05:00:27.859637+00:00 | 2021-10-10T05:00:50.934402+00:00 | 531 | false | ```\nclass Solution:\n def snakesAndLadders(self, board: List[List[int]]) -> int:\n queue = collections.deque()\n n = len(board)\n queue.append((1, 0)) # (label, path_len)\n visited = set()\n \n def square_to_idx(val):\n row_idx = n - 1 - (val - 1) // n\n revert = True if (n - 1 - row_idx) % 2 == 1 else False\n col_idx = (val - 1) % n\n col_idx = n - 1 - col_idx if revert else col_idx\n return row_idx, col_idx\n \n while queue:\n cur_val, path_len = queue.popleft()\n visited.add(cur_val)\n cur_row, cur_col = square_to_idx(cur_val)\n # see a ladder/snake and move\n # note this doesn\'t take an extra step\n # so no need to add to the queue\n if board[cur_row][cur_col] != -1:\n cur_val = board[cur_row][cur_col]\n # game ends\n # note: cannot use cur_row = row_col == 0 \n # as the first row might be reverted\n if cur_val == n ** 2:\n return path_len\n # next move\n max_move = min(cur_val + 6, n ** 2)\n for dest_val in range(cur_val + 1, max_move + 1):\n if dest_val not in visited:\n dest_row, dest_col = square_to_idx(dest_val)\n queue.append((dest_val, path_len + 1))\n\n return -1\n``` | 3 | 0 | ['Breadth-First Search', 'Python'] | 1 |
snakes-and-ladders | Easy C++ BFS solution || commented | easy-c-bfs-solution-commented-by-saiteja-trlv | \nclass Solution {\npublic:\n int snakesAndLadders(vector<vector<int>>& board) {\n \n //get the top right value\n \n int n=board. | saiteja_balla0413 | NORMAL | 2021-07-27T13:47:51.594375+00:00 | 2021-07-27T13:47:51.594419+00:00 | 552 | false | ```\nclass Solution {\npublic:\n int snakesAndLadders(vector<vector<int>>& board) {\n \n //get the top right value\n \n int n=board.size();\n int toReach=n*n;\n \n \n \n //to store ht values which are visited\n unordered_set<int> s;\n queue<int> q;\n //q stores the value which you are at \n q.push(1);\n \n int moves=0;\n s.insert(1);\n while(!q.empty())\n {\n int l=q.size();\n for(int j=0;j<l;j++)\n {\n //for every value in q try the next 6 possible places\n int val=q.front();\n q.pop();\n \n //for the next 6 places\n int next;\n for(int k=1;k<=6;k++)\n {\n next=val+k;\n next=min(next,toReach);\n int row=(n-1)- (next-1)/n;\n int col=(next-1)%n;\n if((n-1-row) %2)\n {\n //if the diff between curr row and last row is even \n //then the row values gets flipped\n col= n-1-col;\n }\n \n \n //there can be ladder or snake\n if(board[row][col]!=-1)\n next=board[row][col];\n if(next==toReach){\n return moves+1;\n }\n if(s.count(next))\n continue;\n s.insert(next);\n q.push(next);\n }\n }\n moves++;\n }\n return -1;\n \n }\n};\n```\n**Upvote if this helps you :)** | 3 | 0 | ['C'] | 1 |
snakes-and-ladders | [c++] using BFS | c-using-bfs-by-anandbarnwal-u9jg | \nint snakesAndLadders(vector<vector<int>>& board) {\n int R = board.size();\n int C = board[0].size(); \n int dest = R * C;\n | anandbarnwal | NORMAL | 2021-07-22T21:56:15.332527+00:00 | 2021-07-22T21:56:15.332562+00:00 | 211 | false | ```\nint snakesAndLadders(vector<vector<int>>& board) {\n int R = board.size();\n int C = board[0].size(); \n int dest = R * C;\n queue<pair<int, int>> q;\n bool *visited = new bool[R*C + 1]{false};\n \n q.push({1, 0});\n visited[1] = true;\n \n while (!q.empty()) {\n int index = q.front().first;\n int dist = q.front().second;\n q.pop();\n \n if (index == dest) {\n return dist;\n }\n \n for (int it = 1; it <= 6; it++) {\n int nextIndex = index + it;\n if (nextIndex > R*C) {\n break;\n }\n \n // calculate row and col\n int row = (nextIndex - 1) / R; // this will give row from top\n row = R - 1 - row; // To get row from bottom\n \n int rightToLeft = (R - 1 - row) & 1;\n int col;\n \n if (rightToLeft) {\n col = C - 1 - (nextIndex - 1) % C;\n }\n else {\n col = (nextIndex - 1) % C;\n }\n\n // push in queue if not visited\n int boardIndex = board[row][col] == -1 ? nextIndex : board[row][col];\n if (!visited[boardIndex]) {\n q.push({boardIndex, dist + 1});\n visited[boardIndex] = true;\n }\n \n }\n }\n \n return -1;\n }\n``` | 3 | 0 | [] | 0 |
snakes-and-ladders | [C++] BFS solution with comments | c-bfs-solution-with-comments-by-ankitsha-etui | \n\nclass Solution {\npublic:\n array<int, 2> getCoordinates(int s, int n) {\n int row = n-1-(s-1)/n; //we divide the number by board size and su | ankitsharma99 | NORMAL | 2021-06-29T11:17:13.508236+00:00 | 2021-06-29T11:17:13.508266+00:00 | 350 | false | \n```\nclass Solution {\npublic:\n array<int, 2> getCoordinates(int s, int n) {\n int row = n-1-(s-1)/n; //we divide the number by board size and subtract with board size and 1 (as it is 0 indexed)\n int col = (s-1)%n;\n if((n%2 == 0 and row%2 == 0) or (n%2 == 1 and row%2 == 1) ) //simple condition for changing the direction \n col = n-col-1;;\n return {row, col};\n \n }\n int snakesAndLadders(vector<vector<int>>& board) {\n int n = board.size();\n int count_steps = 0;\n int target = n*n;\n vector<vector<bool>> visited(n, vector<bool> (n, false));\n \n queue<int> q;\n q.push(1);\n visited[n-1][0] = true; //the first cell, i.e \'1\', which has the index n-1,0 is now marked as visited\n \n while(q.size() > 0) {\n int size = q.size();\n \n for(int i = 0; i<size; i++) {\n int curr_value = q.front();\n \n if(curr_value == target) return count_steps;\n q.pop();\n //run loop from 1 to 6 and check for each dice possibility\n for(int dice_value = 1; dice_value<= 6; dice_value++) {\n if(curr_value + dice_value > target) break;\n \n //get the coordinates to check if its a ladder or snake\n array<int, 2> cord = getCoordinates(curr_value + dice_value, n);\n \n //visited check\n if(visited[cord[0]][cord[1]]) continue;\n visited[cord[0]][cord[1]] = true;\n \n if(board[cord[0]][cord[1]] != -1)\n q.push(board[cord[0]][cord[1]]);\n else \n q.push(curr_value + dice_value);\n }\n }\n count_steps++;\n }\n return -1;\n }\n};\n``` | 3 | 0 | [] | 0 |
snakes-and-ladders | c++ BFS, Convert 2D array into 1D array then solve | c-bfs-convert-2d-array-into-1d-array-the-ijcr | \n\nclass Solution {\npublic:\n int snakesAndLadders(vector<vector<int>>& board) {\n int n=board.size();\n int size=n*n;\n //cout<<size; | hemu22 | NORMAL | 2021-06-04T08:42:33.014243+00:00 | 2021-06-04T08:42:33.014271+00:00 | 295 | false | ```\n\nclass Solution {\npublic:\n int snakesAndLadders(vector<vector<int>>& board) {\n int n=board.size();\n int size=n*n;\n //cout<<size;\n vector<int>sl(size+1,-1);\n vector<bool>visited(size+1,0);\n int temp=1;\n bool toggle=1;\n for(int i=n-1;i>=0;i--){\n if(toggle){\n for(int j=0;j<n;j++){\n sl[temp++]=board[i][j];\n }toggle=0;}else{\n for(int j=n-1;j>=0;j--){\n sl[temp++]=board[i][j];\n }toggle=1;\n \n }\n } \n \n queue<pair<int,int>> q;\n \n q.push({1,0});\n visited[1] = 1;\n \n while(!q.empty()){\n pair<int,int> p = q.front();\n q.pop();\n \n if(p.first == n*n){\n return p.second;\n }\n \n for(int i=p.first+1;i<=p.first+6&& i<=n*n ;i++){\n pair<int,int> p1;\n if(!visited[i]){\n visited[i] = 1;\n p1.second = p.second + 1;\n if(sl[i]!=-1){\n p1.first = sl[i];\n }else{\n p1.first = i;\n }\n q.push(p1);\n }\n }\n }\n return -1;\n }\n};\n\n// int n=board.size();\n// int size=n*n;\n// //cout<<size;\n// vector<int>sl(size+1,-1);\n// vector<bool>visited(size+1,0);\n// int temp=1;\n// bool toggle=1;\n// for(int i=n-1;i>=0;i--){\n// if(toggle){\n// for(int j=0;j<n;j++){\n// sl[temp++]=board[i][j];\n// }toggle=0;}else{\n// for(int j=n-1;j>=0;j--){\n// sl[temp++]=board[i][j];\n// }toggle=1;\n \n// }\n// } \n// // for(auto i:sl)cout<<i<<" ";\n// queue<pair<int,int>>q;\n// q.push(make_pair(1,0));\n// visited[1]=1;\n// while(!q.empty()){\n\n// pair<int,int>temp=q.front();q.pop();\n// if(temp.first==size)return temp.second;\n// for(int i=temp.first+1;i<=temp.first+6;i++){\n\n// if(i<=size){ if(!visited[i]){\n\n// visited[i]=1;\n// pair<int,int>flag;\n// flag.second=temp.second+1;\n// if(sl[i]!=-1){\n// flag.first=sl[i];\n// }else flag.first=i;\n// q.push(flag);\n\n\n// }}\n// }\n\n\n\n\n// }\n// return -1;\n \n\n\n\n\n``` | 3 | 0 | [] | 0 |
snakes-and-ladders | [Java] BFS solution | java-bfs-solution-by-roka-9rht | \nclass Solution {\n public int snakesAndLadders(int[][] board) {\n int n = board.length;\n boolean[] visited = new boolean[n * n + 1];\n | roka | NORMAL | 2020-09-25T19:22:09.807182+00:00 | 2020-09-25T19:22:09.807216+00:00 | 175 | false | ```\nclass Solution {\n public int snakesAndLadders(int[][] board) {\n int n = board.length;\n boolean[] visited = new boolean[n * n + 1];\n Queue<Integer> queue = new LinkedList<>();\n \n queue.add(1);\n visited[1] = true;\n \n for (int counter = 0; !queue.isEmpty(); counter++) {\n int size = queue.size();\n \n for (int i = 0; i < size; i++) {\n int cur = queue.poll();\n \n if (cur == n * n) {\n return counter;\n }\n \n for (int l = 1; cur + l <= n * n && l <= 6; l++) {\n int next = cur + l;\n \n if (getValue(board, next) != -1) {\n next = getValue(board, next);\n }\n\n if (!visited[next]) {\n visited[next] = true;\n queue.add(next);\n }\n }\n }\n }\n \n return -1;\n }\n \n private int getValue(int[][] board, int x) {\n int n = board.length;\n x--;\n \n int row = x / n;\n int column = row % 2 == 0 ? x % n : (n - x % n - 1);\n return board[n - row - 1][column];\n }\n}\n``` | 3 | 0 | [] | 0 |
snakes-and-ladders | Python 3 - faster than 98%, supposedly... | python-3-faster-than-98-supposedly-by-ke-zmx2 | get all the "portals" (snakes, ladders) -- no headache of jumping around the grid when a "position" tracker works just as well\n2. BFS for each dice roll on eac | kehaarable | NORMAL | 2020-04-20T23:51:30.164674+00:00 | 2020-04-20T23:51:30.164709+00:00 | 793 | false | 1. get all the "portals" (snakes, ladders) -- no headache of jumping around the grid when a "position" tracker works just as well\n2. BFS for each dice roll on each turn.\n\n```from collections import deque\n\nclass Solution:\n def snakesAndLadders(self, board: List[List[int]]) -> int:\n # makes the everything easier - store all snakes/ladders in a dict\n # screw you and your lowsy input schema!\n portals = {}\n \n current_position = 0\n direction = 1\n for row in board[::-1]:\n for val in row[::direction]:\n current_position += 1\n if val > -1:\n portals[current_position] = val\n direction = -direction\n \n # the last square is a snek!!!\n if current_position in portals:\n return -1\n \n queue = deque()\n # posistion, turn number\n queue.append((1, 0))\n visited = set()\n while queue:\n pos, turn = queue.popleft()\n for roll in range(1,7):\n new_pos = pos + roll\n \n if new_pos not in visited:\n visited.add(new_pos)\n new_pos = portals.get(new_pos, new_pos)\n queue.append((new_pos, turn + 1))\n \n if new_pos == current_position:\n return turn + 1 \n return -1\n | 3 | 0 | ['Python3'] | 1 |
snakes-and-ladders | Dijkstra | dijkstra-by-sean72kimo-dfdt | Dijkstra\n\n\nclass Solution_dijkstra(object):\n\n def snakesAndLadders(self, board):\n """\n :type board: List[List[int]]\n :rtype: int | sean72kimo | NORMAL | 2019-07-05T23:25:57.944328+00:00 | 2019-07-05T23:25:57.944382+00:00 | 444 | false | Dijkstra\n\n```\nclass Solution_dijkstra(object):\n\n def snakesAndLadders(self, board):\n """\n :type board: List[List[int]]\n :rtype: int\n """\n if len(board) == 0:\n return 0\n n = len(board)\n nn = n * n\n arr = [0]\n for i, row in enumerate(board[::-1]):\n arr += row[::-1] if i % 2 else row\n\n que = [(0,1)]\n vst = {}\n\n while que:\n dist, curr = heapq.heappop(que)\n\n if curr in vst and dist >= vst[curr]:\n continue\n\n if curr == nn:\n return dist\n\n vst[curr] = dist\n\n for i in range(1, 7):\n nx = curr + i\n\n if not (1 <= nx <= nn):\n continue\n\n if arr[nx] == -1:\n heapq.heappush(que, (dist + 1, nx))\n\n else:\n ladder = arr[nx]\n heapq.heappush(que, (dist + 1, ladder))\n\n return -1\n``` | 3 | 0 | [] | 1 |
snakes-and-ladders | ✅✅ Using BFS || Beginner Friendly || Easy Solution | using-bfs-beginner-friendly-easy-solutio-8rki | IntuitionThis problem is a variation of the shortest path problem in an unweighted graph. We can think of each cell in the board as a node, and moving from one | Karan_Aggarwal | NORMAL | 2025-03-06T12:49:15.539402+00:00 | 2025-03-06T12:49:15.539402+00:00 | 156 | false | ## Intuition
This problem is a variation of the **shortest path problem** in an **unweighted graph**. We can think of each cell in the board as a **node**, and moving from one cell to another (by rolling the dice) as an **edge**.
We need to find the **minimum number of moves** required to reach the last cell **(n × n)** from the first cell **(1)** while considering snakes and ladders.
## Approach
1. **Modeling the Board as a Graph**
- The board is **1-based**, meaning the first cell is numbered `1`, and the last cell is `n * n`.
- We need to **map** each step number to its corresponding **row and column** in the board.
- If a ladder exists at a position, it directly moves the player to another position.
- If a snake exists, it sends the player backward.
2. **Finding Coordinates for a Given Step**
- Since the board is a **snake-like grid**, the mapping from step numbers to `(row, col)` is tricky:
- The **bottom row** starts from the **left** (1st cell).
- The next row starts from the **right** (zig-zag pattern).
- The process alternates for every row.
- The formula for finding `(row, col)`:
- `row = n - 1 - (step - 1) / n`
- `col = (step - 1) % n`
- If `row` is moving in reverse (odd/even pattern), reverse `col`.
3. **Breadth-First Search (BFS) Traversal**
- BFS is used because it finds the **shortest path** in an unweighted graph.
- We maintain a `queue<int>` to explore all possible dice rolls (`1 to 6`).
- A `visited` array is used to avoid revisiting cells.
4. **Processing BFS**
- Start from `1` (first cell) and explore all possible moves (`1 to 6` steps forward).
- If we reach `n × n`, return the number of steps taken.
- If we land on a **ladder**, move to its destination directly.
- If we land on a **snake**, move to its tail directly.
- If the position is already visited, skip it.
## Complexity Analysis
- **Time Complexity**: \(O(n^2)\), since we explore at most `n × n` cells.
- **Space Complexity**: \(O(n^2)\), for the visited array and queue storage.
## Code
```cpp []
class Solution {
public:
int n;
// Function to find the (row, col) coordinates for a given step number
pair<int, int> getCoordinate(int step) {
int row = n - 1 - (step - 1) / n;
int col = (step - 1) % n;
// If the row follows a reversed order (zig-zag pattern)
if ((row % 2 == 0 && n % 2 == 0) || (row % 2 != 0 && n % 2 != 0)) {
col = n - 1 - col;
}
return {row, col};
}
int snakesAndLadders(vector<vector<int>>& board) {
n = board.size();
int steps = 0;
vector<vector<bool>> visited(n, vector<bool>(n, false));
queue<int> q;
// Start BFS from cell 1
q.push(1);
visited[n - 1][0] = true;
while (!q.empty()) {
int N = q.size();
while (N--) {
int currPosition = q.front();
q.pop();
// If we reach the last cell, return the steps taken
if (currPosition == n * n) return steps;
// Try all possible dice rolls (1 to 6)
for (int k = 1; k <= 6; k++) {
int nextPosition = currPosition + k;
// Stop if beyond the board
if (nextPosition > n * n) break;
auto [r, c] = getCoordinate(nextPosition);
// If already visited, skip
if (visited[r][c]) continue;
visited[r][c] = true;
// If there's a ladder or a snake, move to its destination
if (board[r][c] == -1) {
q.push(nextPosition);
} else {
q.push(board[r][c]);
}
}
}
steps++;
}
// If we exhaust all possibilities and never reach the last cell, return -1
return -1;
}
};
```
# Have a Good Day 😊 UpVote? | 2 | 0 | ['Array', 'Breadth-First Search', 'Matrix', 'C++'] | 0 |
snakes-and-ladders | Simple BFS | Python | simple-bfs-python-by-ov8cfej3su-gg94 | A nice optimization we can apply is to "unroll" the board into a
one dimensional array, indexed according to the board's square numbers. That way the square num | Ov8CfeJ3Su | NORMAL | 2025-03-04T03:29:55.177376+00:00 | 2025-03-04T03:29:55.177376+00:00 | 348 | false | 
A nice optimization we can apply is to "unroll" the board into a
one dimensional array, indexed according to the board's square numbers. That way the square numbers are easy to translate into board indices - you just subtract one.
```python3 []
from collections import deque
class Solution:
def snakesAndLadders(self, board: List[List[int]]) -> int:
# Apply BFS - unroll the board first for simplicity.
n = len(board)
assert n == len(board[0])
n2 = n*n
cells = []
rev = False
for idx in range(n - 1, -1, -1):
cells.extend(reversed(board[idx]) if rev else board[idx])
rev = not rev
# Now the square mapping is simple, the values are simply
# the one-index of the final destination of the snake/ladder
dist = [-1] * n2
dist[0] = 0
frontier = deque([1])
while len(frontier):
cur = frontier.popleft()
d = dist[cur - 1]
assert d != -1
if cur == n2:
return d
for nxt in range(cur + 1, min(cur + 6, n2) + 1):
if cells[nxt - 1] != -1:
nxt = cells[nxt - 1] # follow the snake or ladder
if dist[nxt - 1] == -1:
dist[nxt - 1] = d + 1
frontier.append(nxt)
return -1
``` | 2 | 0 | ['Breadth-First Search', 'Python3'] | 0 |
snakes-and-ladders | 100% beats using BFS traversal | 100-beats-using-bfs-traversal-by-tarunsi-nreo | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | tarunsingh04 | NORMAL | 2025-02-09T16:48:01.802240+00:00 | 2025-02-09T16:48:01.802240+00:00 | 234 | 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
```cpp []
class Solution {
pair<int,int> pos(int x,int n){
int r=(x-1)/n;
int c=(x-1)%n;
if(r&1){
c=(n-1)-c;
}
r=(n-1)-r;
return{r,c};
}
public:
int snakesAndLadders(vector<vector<int>>& board) {
int n=board.size();
vector<int>dist(n*n+1,-1);
dist[1]=0;
queue<int>q;
q.push(1);
while(!q.empty()){
int x=q.front();
q.pop();
for(int i=x+1;i<=min(x+6,n*n);i++){
pair<int,int> v=pos(i,n);
int distination= (board[v.first][v.second])!=-1 ? board[v.first][v.second] : i;
if(dist[distination]==-1){
dist[distination]=dist[x]+1;
q.push(distination);
}
}
}
return dist[n*n];
}
};
``` | 2 | 0 | ['C++'] | 1 |
snakes-and-ladders | Java | clean code | BFS | Beats 92.40% | java-clean-code-bfs-beats-9240-by-user16-md06 | IntuitionApproach
step-1: flatten board
step-2: bfs (level order maintain distance from root)
step-3: return distance on reaching n^2
Complexity
Time complexity | Any_ | NORMAL | 2025-01-04T10:49:17.210783+00:00 | 2025-01-04T10:49:17.210783+00:00 | 437 | false | 
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
- step-1: flatten board
- step-2: bfs (level order maintain distance from root)
- step-3: return distance on reaching n^2
# Complexity
- Time complexity: O(n^2)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(n^2)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public int snakesAndLadders(int[][] board2D) {
// init
int n = board2D.length;
int m = n*n;
// flatten
int[] board1D = new int[m+1];
int k = 1;
for (int i = n-1; i >= 0; i--) {
for (int j = 0; j < n; j++) board1D[k++] = board2D[i][j];
// left right // if (--i<0) break;
if (i>0) i--;
else break;
for (int j = n-1; j >= 0; j--) board1D[k++] = board2D[i][j];
}
// bfs init
boolean[] vis = new boolean[m+1];
Queue<Integer> q = new LinkedList<>();
int dis; // distance from root
int u = 1;
vis[u] = true;
q.add(u);
dis = 0;
// bfs
while (!q.isEmpty()) {
int level = q.size();
for (int i = 0; i < level; i++) {
u = q.poll();
if (u==m) return dis;
for (int j = 1; j <= 6; j++) {
if (u+j>m) break;
int v = u+j;
if (!vis[v]) {
vis[v] = true;
if (board1D[v]==-1) {
q.add(v);
} else {
q.add(board1D[v]);
}
}
}
}
dis++;
}
return -1;
}
}
``` | 2 | 0 | ['Array', 'Breadth-First Search', 'Matrix', 'Java'] | 0 |
snakes-and-ladders | Python BFS beats 99% | python-bfs-beats-99-by-darthvaper00-kt3a | Code\n```\nclass Solution:\n def snakesAndLadders(self, board: List[List[int]]) -> int:\n \n def calculate_position(r, c, n):\n maxN | darthvaper00 | NORMAL | 2024-03-18T06:00:55.930092+00:00 | 2024-03-18T06:00:55.930127+00:00 | 515 | false | # Code\n```\nclass Solution:\n def snakesAndLadders(self, board: List[List[int]]) -> int:\n \n def calculate_position(r, c, n):\n maxNumber = n**2 - r*n\n row = n - r - 1\n\n if row % 2 == 0: #ascending\n position = maxNumber - (n - c - 1)\n else: #descending\n position = maxNumber - c\n return position \n\n snakesladders = defaultdict(int)\n n = len(board)\n\n for r in range(n):\n for c in range(n):\n if board[r][c] != -1:\n position = calculate_position(r, c, n)\n destination = board[r][c]\n snakesladders[position] = destination\n\n queue = deque([(1,0)])\n visited = set([1])\n\n while queue:\n curr, count = queue.popleft()\n if curr >= n**2:\n return count \n\n for next_move in range(curr + 1, min(curr + 7, n**2 + 1)):\n # Check if next_move leads to a snake or ladder.\n if next_move in snakesladders:\n next_move = snakesladders[next_move]\n\n if next_move not in visited:\n visited.add(next_move)\n queue.append((next_move, count + 1))\n\n return -1\n\n | 2 | 0 | ['Python3'] | 2 |
snakes-and-ladders | BFS Solution | Explained | bfs-solution-explained-by-singhsauravsk-wcyq | Intuition\nThe main idea behind the solution is to model the board as a graph, where each square is a node, and an edge between two nodes indicates a possible m | singhsauravsk | NORMAL | 2024-02-10T14:14:26.634789+00:00 | 2024-02-10T14:14:26.634821+00:00 | 236 | false | # Intuition\nThe main idea behind the solution is to model the board as a graph, where each square is a node, and an edge between two nodes indicates a possible move. The BFS algorithm is used to find the shortest path from the first square to the last square.\n\n# Key Points\n* **Graph Representation**: The game board is effectively treated as a graph, which is a common approach for path finding problems.\n* **BFS for Shortest Path**: BFS is chosen because it guarantees the shortest path in unweighted graphs (or boards, in this context), which aligns with finding the minimum number of moves.\n* **Handling Board Layout**: The findPosition method is crucial for translating between the 1D representation (useful for BFS) and the actual 2D coordinates, taking into account the board\'s zigzag numbering.\n* **Efficiency**: This approach is efficient in terms of both time and space complexity, suitable for boards of reasonable size.\n\n# Approach\n* **Initialization**: Convert the 2D board into a 1D array (moves) to simplify the handling of squares. The array moves is initialized with -1, indicating that a square hasn\'t been reached yet, except for the first square, which is set to 0 moves.\n* **BFS Queue**: A queue is used to store the squares to visit, starting with square 1.\n* **Exploration**:\n * For each square taken from the queue, the algorithm considers all possible next moves (rolling the dice to get a number from 1 to 6). For each possible move, it calculates which square it would land on.\n * It uses the findPosition method to convert the linear square number to its corresponding 2D board coordinates. This method accounts for the zigzag pattern of the board numbers.\n * If landing on a square with a ladder or a snake (board[pos[0]][pos[1]] not equal to -1), the player moves to the destination square indicated by the board. Otherwise, the player moves to the directly reached square.\n* **Updating Moves**:\n * If the destination square hasn\'t been reached before (moves[destination] == -1), the number of moves to reach this square is updated to be one more than the current square\'s moves.\n * The destination square is then added to the queue for further exploration.\n* **Termination**:\n * The process repeats until either the last square is reached (in which case the total number of moves to reach it is returned) or the queue becomes empty (indicating that the last square is unreachable under the game rules, though this condition is implicitly handled by returning the moves to the last square, which would remain -1).\n\n# Complexity\n- Time complexity: **O(n^2)**, where n is the dimension of the square board.\n\n\n- Space complexity: **O(n^2)**, primarily due to the storage of moves for each square and the queue used in BFS.\n\n# Code\n```\nclass Solution {\n public int snakesAndLadders(int[][] board) {\n int n = board.length;\n int totalSquares = n * n;\n\n // -1 indicates the square has not been reached yet.\n int[] moves = new int[totalSquares + 1];\n Arrays.fill(moves, -1);\n\n Queue<Integer> queue = new LinkedList<>();\n queue.offer(1); // Start from square 1.\n moves[1] = 0; // Number of moves to reach square 1 is 0.\n\n while (!queue.isEmpty()) {\n int current = queue.poll();\n \n // Reached the last square.\n if (current == totalSquares) {\n return moves[current];\n }\n\n for (int next = current + 1; next <= Math.min(current + 6, totalSquares); next++) {\n int[] pos = findPosition(next, n);\n int destination = board[pos[0]][pos[1]] == -1 ? next : board[pos[0]][pos[1]];\n\n if (moves[destination] == -1) {\n moves[destination] = moves[current] + 1;\n queue.offer(destination);\n }\n }\n }\n\n // Return -1 if the last square is unreachable.\n return moves[totalSquares];\n }\n\n // Converts the 1D square number to 2D board coordinates.\n private int[] findPosition(int square, int n) {\n int row = (square - 1) / n;\n int col = (square - 1) % n;\n \n // Reverse the column order for odd rows (from the bottom).\n if (row % 2 == 1) {\n col = n - 1 - col;\n }\n row = n - 1 - row; // Convert row to 0-indexed from the bottom.\n \n return new int[]{row, col};\n }\n}\n\n``` | 2 | 0 | ['Breadth-First Search', 'Java'] | 0 |
snakes-and-ladders | Easy Bfs Approach 10 ms solution | easy-bfs-approach-10-ms-solution-by-sand-g6ac | 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 | SandeepIlla | NORMAL | 2024-02-04T10:36:06.849564+00:00 | 2024-02-04T10:36:06.849607+00:00 | 205 | 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 pair<int,int> coor(int num,int n){\n int tr=(num-1)/n;\n int rb=(n-1)-tr;\n int rc=0;\n if(n%2==0){\n rc=(num-1)%n;\n //cout<<rc<<" ";\n if(n%2==0 and rb%2==0){\n //cout<<1<<" ";\n rc=(n-1)-rc;\n }\n }\n else{\n rc=(num-1)%n;\n if(n%2 and rb%2){\n rc=(n-1)-rc;\n }\n }\n return {rb,rc};\n }\n int snakesAndLadders(vector<vector<int>>& board) {\n int n=board.size();\n queue<int>q;\n q.push(1);\n vector<vector<int>>vis(n,vector<int>(n,0));\n vis[n-1][0]=1;\n int c=0;\n pair<int,int>p;\n p=coor(19,5);\n cout<<p.first<<" "<<p.second<<" ";\n while(!q.empty()){\n int ns=q.size();\n while(ns--){\n int node=q.front();\n q.pop();\n if(node==n*n){\n return c;\n }\n for(int i=1;i<=6;i++){\n int x=node+i;\n if(x>n*n){\n break;\n }\n pair<int,int>p=coor(x,n);\n int row=p.first;\n int col=p.second;\n if(vis[row][col]==1){\n continue;\n }\n if(board[row][col]==-1){\n q.push(x);\n }\n else {\n //cout<<board[row][col]<<" ";\n q.push(board[row][col]);\n }\n vis[row][col]=1;\n }\n }\n c+=1;\n }\n return -1;\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
snakes-and-ladders | C++ BFS with queue simple solution -- beats 98,2 % | c-bfs-with-queue-simple-solution-beats-9-yh84 | Intuition\nThe problem asks for the minimum moves to reach the end, suggesting the use of a BFS algorithm\n\n# Approach\nThere are only 2 particularities:\n - c | rpunet | NORMAL | 2023-12-24T18:31:22.139914+00:00 | 2023-12-24T18:31:22.139945+00:00 | 124 | false | # Intuition\nThe problem asks for the minimum moves to reach the end, suggesting the use of a BFS algorithm\n\n# Approach\nThere are only 2 particularities:\n - convert the Boustrophedon matrix into a sequence array (g), in which we store the destination of the snake/ladder or -1, ie: g[3] = 23, meaning that in cell 3 there is a ladder to cell 23.\n - during the processing of the queue, in case we find a ladder/snake, we move to its destination without incrementing the moves number.\n# Complexity\n- Time complexity:\nO(n^2) (traversing the whole matrix = n^2 + processing the queue = n^2; since the processing in each iteration is time constant, total is n^2)\n- Space complexity:\nsimilarly, n^2 for each the vector to transform the matrix, the seen vector and the queue are all n^2, resulting in O(n^2)\n\n# Code\n```\nclass Solution {\npublic:\n int snakesAndLadders(vector<vector<int>>& board) {\n int n = board.size();\n vector<int> g(n * n + 1);\n int count = 1;\n int rev = n % 2 == 0 ? 1 : 0;\n\n for (int i=n-1; i>=0; i--) {\n if (i % 2 == rev) {\n for (int j=0; j<n; j++)\n g[count++] = board[i][j];\n }\n else {\n for (int j=n-1; j>=0; j--)\n g[count++] = board[i][j];\n }\n }\n queue<pair<int,int>> q;\n q.push({1, 0});\n vector<bool> seen(n * n + 1, false);\n seen[1] = true;\n while (!q.empty()) {\n auto[curr, moves] = q.front();\n q.pop();\n if (g[curr] != -1)\n curr = g[curr];\n if (curr == n*n)\n return moves;\n for (int i=1; i<=6; i++) {\n if (curr + i <= n*n && seen[curr+i] == false) {\n q.push({curr + i, moves + 1});\n seen[curr + i] = true;\n }\n }\n }\n return -1;\n }\n};\n``` | 2 | 0 | ['Breadth-First Search', 'Queue', 'C++'] | 1 |
snakes-and-ladders | C++ Simple solution || BFS || Queue | c-simple-solution-bfs-queue-by-samarpan2-f0p1 | Intuition\n Describe your first thoughts on how to solve this problem. \nUsing BFS algorithm to find smallest path\n# Approach\n Describe your approach to solvi | Samarpan27 | NORMAL | 2023-08-09T11:10:21.742381+00:00 | 2023-08-09T11:10:21.742405+00:00 | 24 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUsing BFS algorithm to find smallest path\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe use box no. to access each index of matrix. We used an vis boolean array which shows whether that index is visited or not.\nWe push 1st box (i.e. board[n-1][0]) in the queue and for all possible 6 moves, if new box is not visited, we push it in the queue and check if its last box or not. If its last box we return ans which is being incremented at every level or move.\nFor each box , if board[nr][nc] (nr = new row, nc = new column) is not -1, it means it is ladder or snake so we go to its corresponding final box and push in queue. If any box is already visited, it means it is possible to visit that box in less or equal number of steps so we not consider it for currently pushing in queue. \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(n^2)\n# Code\n```\nclass Solution {\npublic:\n int snakesAndLadders(vector<vector<int>>& board) {\n int n = board.size();\n vector<bool> vis(n*n + 1,false);\n queue<int> q;\n q.push(1);\n vis[1]=true;\n int ans = 0;\n while(q.empty()==false)\n {\n int size = q.size();\n ans++;\n\n for(int sz=0;sz<size;sz++)\n {\n int box = q.front();\n q.pop();\n\n for(int k=1;k<=6;k++)\n {\n int newbox = box + k;\n int nr = n-1-((newbox-1)/n);\n int nc = ((newbox-1)/n)%2==0?(newbox-1)%n:n-1-(newbox-1)%n;\n\n if(board[nr][nc] != -1)\n {\n newbox = board[nr][nc];\n nr = n-1-((newbox-1)/n);\n nc = ((newbox-1)/n)%2==0?(newbox-1)%n:n-1-(newbox-1)%n;\n }\n\n if(!vis[newbox])\n {\n vis[newbox]=true;\n q.push(newbox);\n\n if(newbox==n*n)\n return ans;\n }\n }\n }\n }\n return -1;\n }\n};\n```\nPlease upvote my solution if you like it!!! | 2 | 0 | ['Breadth-First Search', 'Queue', 'Matrix', 'C++'] | 0 |
snakes-and-ladders | Python BFS | python-bfs-by-ayushgx-h1y7 | \nclass Solution:\n def snakesAndLadders(self, board: List[List[int]]) -> int:\n n = len(board)\n jumps, target = {}, n * n\n\n board.re | ayushgx | NORMAL | 2023-07-19T22:08:17.320613+00:00 | 2023-07-19T22:08:17.320669+00:00 | 285 | false | ```\nclass Solution:\n def snakesAndLadders(self, board: List[List[int]]) -> int:\n n = len(board)\n jumps, target = {}, n * n\n\n board.reverse()\n for i in range(n): board[i].reverse() if i % 2 else None\n\n c = 0\n for i in board:\n for j in i:\n c += 1\n if j == -1: continue\n jumps[c] = j\n \n q, seen = deque([(1, 0)]), set([1])\n\n while q:\n i, moves = q.popleft()\n if i == target: return moves\n for j in range(i+1, i+7):\n if j > target: break\n if j in seen: continue\n seen.add(j)\n if j in jumps: j = jumps[j]\n q.append((j, moves + 1))\n\n return -1\n\n``` | 2 | 0 | ['Array', 'Breadth-First Search', 'Matrix', 'Python3'] | 0 |
snakes-and-ladders | 🐍 python, simple BFS solution with explanation; O(n) | python-simple-bfs-solution-with-explanat-egcc | Intuition\nIt is a a bit messy BFS problem. \n\n# Approach\n1) As you can see the board is 2D but the the order of the cells can be a represented as a one-dimen | smvthirteen | NORMAL | 2023-07-16T01:32:45.164347+00:00 | 2023-07-16T20:31:36.871816+00:00 | 163 | false | # Intuition\nIt is a a bit messy BFS problem. \n\n# Approach\n1) As you can see the board is 2D but the the order of the cells can be a represented as a one-dimensional array. Also, the columns reverse every other row and the cells start at 1 not zero. Considering all of that, we need a mapping array: `array[i]=(row_i, col_i)`\n\n2) We need an array that contains the minimum number of turns it takes to get to that array. \n\n3) BFS: we start at cell 1 and we have 6 options. We check of the cells has a snake or ladder and if yes we move the end of it. Then we check if the cell has visited before. \n\nNote: We check for ladder first and then checking if visited before. Otherwise, we will have problem when a cell i is end of a ladder for cell j and beginning of a ladder for cell k. \n\n# Complexity\n- Time complexity: O(N^2)\n\n- Space complexity:O(N^2)\n\n# Code\n```\nfrom collections import deque\nclass Solution:\n def snakesAndLadders(self, board: List[List[int]]) -> int:\n n = len(board)\n\n # mapping the ordered cells to row and columns on the board\n cells = [None] * (n**2 + 1)\n label = 1\n columns = list(range(0, n))\n for row in range(n - 1, -1, -1):\n for column in columns:\n cells[label] = (row, column)\n label += 1\n columns.reverse()\n\n dist = [-1] * (n**2 + 1)\n q = deque([1])\n dist[1] = 0\n while q:\n curr = q.popleft()\n for next in range(curr + 1, min(curr + 6, n**2) + 1):\n row, column = cells[next]\n if board[row][column] != -1:\n next = board[row][column]\n\n if dist[next] == -1:\n dist[next] = dist[curr] + 1\n q.append(next)\n return dist[n * n]\n``` | 2 | 0 | ['Array', 'Breadth-First Search', 'Graph', 'Matrix', 'Python3'] | 0 |
snakes-and-ladders | Explained python3 BFS solution | explained-python3-bfs-solution-by-shrish-3yie | Intuition\n Describe your first thoughts on how to solve this problem. \nUse BFS\n\n# Approach\n Describe your approach to solving the problem. \nThe conversion | shrishtikarkera | NORMAL | 2023-07-15T17:43:01.202412+00:00 | 2023-07-15T17:43:01.202452+00:00 | 57 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUse BFS\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe conversion from the position of the board in cell number to the actual coordinate in the board array is an important one. Identifying the row is easy --> pos-1 / length but for the col, an extra step is needed that is reversing the col when the row number is odd. \nAfter defining the pos to coord function, we need to write the BFS implementation --> introduce a queue and a visit set as usual. Now while popping from the queue, add the 6 possible steps to it, check if its the last position of the board, if it is, then return the number of moves+1, else convert the pos to coord, to check if the board has a snake or a ladder in that coord, if it does, then assign the pos accordingly and append it to the queue. \nFinally, return -1 if this exits the loop and does not return any moves. \n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def snakesAndLadders(self, board: List[List[int]]) -> int:\n length = len(board)\n board.reverse()\n\n def postocord(pos):\n r = (pos-1) // length\n c = (pos-1) % length\n if r % 2 == 1:\n c = length-1-c\n return [r, c]\n\n q = deque()\n # pos, moves --> cord, moves\n q.append([1, 0])\n visit = set()\n while(q):\n pos, moves = q.popleft()\n for i in range(1, 7):\n nextpos = pos + i\n r, c = postocord(nextpos)\n if board[r][c] != -1:\n nextpos = board[r][c]\n if nextpos == length * length:\n return moves+1\n if nextpos not in visit:\n visit.add(nextpos)\n q.append([nextpos, moves+1])\n return -1\n``` | 2 | 0 | ['Python3'] | 0 |
snakes-and-ladders | Reason why DFS won't work in some testcases. | reason-why-dfs-wont-work-in-some-testcas-haxr | \n# Approach\nIn this article, I will explain the reason behind DFS (with DP optimization) approach not working.\n\n# Reason\nDFS Approach would work perfectly | brickcommander | NORMAL | 2023-01-25T15:14:39.018018+00:00 | 2023-01-25T15:14:39.018065+00:00 | 249 | false | \n# Approach\nIn this article, I will explain the reason behind DFS (with DP optimization) approach not working.\n\n# Reason\nDFS Approach would work perfectly fine if the graph is acylic but here the graph could be cyclic as well.\nExample of cyclic graph:\n\nIn the above testcase, there are multiple cycles:\n-> 24 -> 21 -> 24\n-> 24 -> 21 -> 23 -> 24\n-> 24 -> 21 -> 22 -> 24\n-> 24 -> 21 -> 22 -> 23 -> 24\n\n# Not Working Code (DFS + DP optimization)\n```\nclass Solution {\npublic:\n int snakesAndLadders(vector<vector<int>>& board) {\n int n = board.size();\n vector<int> dp(n*n, -1);\n\n function<int(int)> recursion; // lambda function\n\n int X, Y;\n auto findCoordinates = [&](int Idx) { // lambda function\n X = n-1 - (Idx/n);\n Y = (Idx%n);\n if((n-1-X)%2) {\n Y = n-1-Y;\n }\n return;\n };\n\n recursion = [&](int currIdx) {\n if(currIdx >= n*n) return (int)1e9;\n if(currIdx == n*n-1) return 0;\n\n int &ans = dp[currIdx];\n if(ans != -1) return ans;\n\n ans = 1e9;\n \n for(int add=1; add<=6; add++) {\n int Idx = currIdx + add;\n if(Idx < n*n) {\n findCoordinates(Idx);\n if(board[X][Y] != -1) {\n Idx = board[X][Y]-1;\n }\n ans = min(ans, recursion(Idx)+1);\n }\n }\n\n return ans;\n };\n\n return recursion(0) == (int)1e9 ? -1 : recursion(0);\n }\n};\n```\n\nBelow is the Working Code for your Reference\n# Working Code (Dijkstra Algorithm)\n```\n#define pii pair<int,int>\nclass Solution {\npublic:\n int snakesAndLadders(vector<vector<int>>& board) {\n int n = board.size();\n\n int X, Y;\n auto findCoordinates = [&](int Idx) {\n X = n-1 - (Idx/n);\n Y = (Idx%n);\n if((n-1-X)%2) {\n Y = n-1-Y;\n }\n return;\n };\n\n priority_queue<pii, vector<pii>, greater<pii> > pq;\n pq.push({0, 0});\n vector<int> dist(n*n, 1e9);\n dist[0] = 0;\n\n while(!pq.empty()) {\n auto [d, node] = pq.top(); pq.pop();\n if(d > dist[node]) continue;\n for(int i=1; i <= 6; i++) {\n int n_node = node + i;\n if(n_node >= n*n) break;\n findCoordinates(n_node);\n if(board[X][Y] != -1) n_node = board[X][Y]-1;\n if(dist[n_node] > d + 1) {\n dist[n_node] = d + 1;\n pq.push({dist[n_node], n_node});\n }\n }\n }\n\n return dist[n*n-1] == (int)1e9 ? -1 : dist[n*n-1];\n }\n};\n``` | 2 | 0 | ['Dynamic Programming', 'Depth-First Search', 'C++'] | 1 |
snakes-and-ladders | Java | BFS | java-bfs-by-judgementdey-hvfk | Intuition\n Describe your first thoughts on how to solve this problem. \nUse BFS to calculate all possible moves beginning position 1. Keep track of all visited | judgementdey | NORMAL | 2023-01-24T23:24:33.433817+00:00 | 2023-01-24T23:53:14.695002+00:00 | 48 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUse BFS to calculate all possible moves beginning position 1. Keep track of all visited positions, so as to not repeat them. Return the count when the final position is reached.\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 private int[] getCoordinates(int val, int n) {\n int x = n - 1 - val / n;\n int mod = (n - 1) % 2;\n int y = x % 2 == mod ? val % n : n - 1 - (val % n);\n \n return new int[] {x, y};\n }\n\n public int snakesAndLadders(int[][] board) {\n int n = board.length;\n int dest = n*n - 1;\n int cnt = 0;\n boolean[] visited = new boolean[dest + 1];\n Queue<Integer> queue = new ArrayDeque<>();\n\n queue.offer(0);\n\n while (!queue.isEmpty()) {\n for (int i = queue.size(); i > 0; i--) {\n int val = queue.poll();\n\n if (val == dest)\n return cnt;\n\n for (int j=1; j <= 6 && val + j <= dest; j++) {\n int[] grid = getCoordinates(val + j, n);\n int nextVal = board[grid[0]][grid[1]] == -1 ? val + j : board[grid[0]][grid[1]] - 1;\n\n if (!visited[nextVal]) queue.offer(nextVal);\n visited[nextVal] = true;\n }\n }\n cnt++;\n }\n return -1;\n }\n}\n``` | 2 | 0 | ['Breadth-First Search', 'Queue', 'Java'] | 0 |
check-distances-between-same-letters | Track First vs. Check Second | track-first-vs-check-second-by-votrubac-nud0 | Track First Position\nC++\ncpp\nbool checkDistances(string s, vector<int>& distance) {\n int pos[26] = {};\n for (int i = 0; i < s.size(); ++i) {\n | votrubac | NORMAL | 2022-09-04T04:00:59.601138+00:00 | 2022-09-04T21:00:34.106887+00:00 | 3,708 | false | #### Track First Position\n**C++**\n```cpp\nbool checkDistances(string s, vector<int>& distance) {\n int pos[26] = {};\n for (int i = 0; i < s.size(); ++i) {\n int n = s[i] - \'a\';\n if (pos[n] > 0 && distance[n] != i - pos[n])\n return false;\n pos[n] = i + 1;\n }\n return true;\n}\n```\n\n#### Check Second Position\nThanks [SunnyvaleCA](https://leetcode.com/SunnyvaleCA/) for the idea. The approach above would not work if we change the problem to allow a single letter.\n\nInstead, when we encounter `s[i]` letter for the first time, we can check that `s[i] == s[i + d + 1]`, where `d` is the distance for that letter.\n\nAfter that, we set the distance to `-1`, so it would work for the second letter (it will be checked against itself). \n\n**Java**\n```java\npublic boolean checkDistances(String s, int[] dist) {\n for (int i = 0; i < s.length(); ++i) {\n int d = dist[s.charAt(i) - \'a\'];\n if (i + d + 1 >= s.length() || s.charAt(i + d + 1) != s.charAt(i))\n return false;\n dist[s.charAt(i) - \'a\'] = -1;\n }\n return true; \n}\n```\n**C++**\n```cpp\nbool checkDistances(string s, vector<int>& dist) {\n for (int i = 0; i < s.size(); ++i) {\n int d = dist[s[i] - \'a\'];\n if (i + d + 1 >= s.size() || s[i + d + 1] != s[i])\n return false;\n dist[s[i] - \'a\'] = -1;\n }\n return true;\n}\n``` | 42 | 0 | ['C', 'Java'] | 2 |
check-distances-between-same-letters | Python3 || 4 lines, dict, enumerate || T/S: 95% / 100% | python3-4-lines-dict-enumerate-ts-95-100-dbb8 | \nclass Solution:\n def checkDistances(self, s: str, distance: List[int]) -> bool:\n \n d = defaultdict(list)\n\n for i, ch in enumerate | Spaulding_ | NORMAL | 2024-03-05T18:33:05.999904+00:00 | 2024-06-14T16:17:48.385974+00:00 | 559 | false | ```\nclass Solution:\n def checkDistances(self, s: str, distance: List[int]) -> bool:\n \n d = defaultdict(list)\n\n for i, ch in enumerate(s):\n d[ch].append(i)\n\n return all(b-a-1 == distance[ord(ch)-97] for ch, (a,b) in d.items()\n```\n[https://leetcode.com/problems/check-distances-between-same-letters/submissions/791498560/](https://leetcode.com/problems/check-distances-between-same-letters/submissions/791498560/)\n\n\nI could be wrong, but I think that time complexity is *O*(*N*) and space complexity is *O*(*N*), in which *N* ~ `len(s)`. | 16 | 0 | ['Python3'] | 0 |
check-distances-between-same-letters | ⭐ HashMap || Explained || Beginner Friendly | hashmap-explained-beginner-friendly-by-c-yekc | \n/*\nUse map to store the character and the index of its first occurance\nAnd when the second occurance found, count the elemnets in between\nand check in dist | coder481 | NORMAL | 2022-09-04T04:01:48.642025+00:00 | 2022-09-04T04:01:48.642058+00:00 | 1,305 | false | ```\n/*\nUse map to store the character and the index of its first occurance\nAnd when the second occurance found, count the elemnets in between\nand check in distance[] whether the distance at the place is correct or not\n*/\nclass Solution {\n public boolean checkDistances(String s, int[] distance) {\n \n Map<Character,Integer> map = new HashMap<>();\n char[] arr = s.toCharArray();\n int len = arr.length;\n \n for(int i=0; i<len; i++){\n if(map.containsKey(arr[i])){\n int start = map.get(arr[i]);\n int diff = i - start - 1;\n if(distance[arr[i]-\'a\'] != diff) return false;\n }\n else map.put(arr[i], i);\n }\n return true;\n }\n}\n``` | 14 | 1 | ['Java'] | 1 |
check-distances-between-same-letters | Last position [C++/Java] | last-position-cjava-by-xxvvpp-yh9g | null | xxvvpp | NORMAL | 2022-09-04T04:02:53.804875+00:00 | 2022-09-04T04:48:33.153339+00:00 | 1,924 | false | <iframe src="https://leetcode.com/playground/CRM7QX8D/shared" frameBorder="0" width="800" height="300"></iframe> | 10 | 0 | ['C', 'Java'] | 1 |
check-distances-between-same-letters | ✅ C++ | | Map || Easy to understand | c-map-easy-to-understand-by-indresh149-ey07 | \nclass Solution {\npublic:\n bool checkDistances(string s, vector<int>& distance) {\n map<char, vector<int>> mpp;\n\n for (int i = 0; i < s.si | indresh149 | NORMAL | 2022-09-04T04:01:21.391891+00:00 | 2022-09-04T04:01:21.391943+00:00 | 1,353 | false | ```\nclass Solution {\npublic:\n bool checkDistances(string s, vector<int>& distance) {\n map<char, vector<int>> mpp;\n\n for (int i = 0; i < s.size(); i++){\n mpp[s[i]].push_back(i);\n }\n\n for (auto it : mpp)\n { \n if (it.second[1] - it.second[0] - 1 != distance[it.first - \'a\']){\n return false;\n }\n }\n return true;\n }\n};\n```\n**Don\'t forget to Upvote the post, if it\'s been any help to you** | 10 | 1 | ['C'] | 2 |
check-distances-between-same-letters | Python | 98% Faster | Easy Solution✅ | python-98-faster-easy-solution-by-gmanay-4xw0 | \ndef checkDistances(self, s: str, distance: List[int]) -> bool:\n unique = set(s)\n for letter in unique:\n index = s.index(letter) # | gmanayath | NORMAL | 2022-09-07T12:28:32.129060+00:00 | 2022-12-22T16:44:29.538597+00:00 | 1,343 | false | ```\ndef checkDistances(self, s: str, distance: List[int]) -> bool:\n unique = set(s)\n for letter in unique:\n index = s.index(letter) # get the first index of the letter\n dis = distance[ord(letter)-97]\n if index+dis+1 > len(s)-1 or s[index+dis+1] != letter:\n return False\n return True\n```\n\n | 9 | 0 | ['Python', 'Python3'] | 1 |
check-distances-between-same-letters | Easy Java Solution || Map | easy-java-solution-map-by-devkd-uxc7 | Check Distances Between Same Letters\n\nApproach:\n1.) We iterate over the String and create a hashmap\n2.) While iterating if the character is not in hashmap, | DevKD | NORMAL | 2022-09-04T04:12:40.729170+00:00 | 2022-09-04T04:12:40.729221+00:00 | 854 | false | # **Check Distances Between Same Letters**\n\n**Approach:**\n1.) We iterate over the String and create a hashmap\n2.) While iterating if the character is not in hashmap, we put it in hashmap\n3.) If character is in hashmap we compute the number of letter between the two occurences by cuurIndex-ma.get(char)-1 and check if this matche with distance provided in the array\n\n**Time Complexity: O(n)**\n\n```\nclass Solution {\n public boolean checkDistances(String s, int[] distance) {\n //Creating a HashMap\n HashMap<Character,Integer> map=new HashMap<Character,Integer>();\n //Iterating over the String\n for(int i=0;i<s.length();i++){\n //If map doesn\'t conatins Key then putting it in hashMap\n if(!map.containsKey(s.charAt(i))){\n map.put(s.charAt(i),i);\n }\n //If it contains Key then updating diatnce between the current and previous occurence\n else{\n int prev=map.get(s.charAt(i));\n int index=s.charAt(i)-\'a\';\n //Checking is the computed distance matches with the provided distance\n if(distance[index]!=i-prev-1){\n return false;\n }\n \n }\n }\n return true;\n }\n}\n``` | 7 | 0 | ['Java'] | 0 |
check-distances-between-same-letters | ✅ C++ | Easy | Self Explanatory | BruteForce | c-easy-self-explanatory-bruteforce-by-ra-rkv8 | Do UPVOTE if it helps :)\n\nbool checkDistances(string s, vector<int>& distance) {\n int n =s.length();\n for(int i=0;i<n;i++)\n for(in | raunak__pandey | NORMAL | 2022-09-04T04:00:35.542872+00:00 | 2022-09-04T05:06:59.708832+00:00 | 795 | false | **Do UPVOTE if it helps :)**\n```\nbool checkDistances(string s, vector<int>& distance) {\n int n =s.length();\n for(int i=0;i<n;i++)\n for(int j=i+1;j<n;j++)\n if(s[i]==s[j])\n if(j-i-1 != distance[s[i]-\'a\']) return false;\n return true;\n }\n``` | 7 | 1 | ['C', 'C++'] | 1 |
check-distances-between-same-letters | Easy Brute force approach in C++ | easy-brute-force-approach-in-c-by-krishn-mqch | Intuition\n Describe your first thoughts on how to solve this problem. \nOverall, this solution has a time complexity of O(n^2), where n is the length of the in | Krishnaroy7 | NORMAL | 2023-04-11T20:17:09.401829+00:00 | 2023-04-11T20:17:33.101711+00:00 | 691 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nOverall, this solution has a time complexity of O(n^2), where n is the length of the input string. This may not be efficient for very large input strings, but it is a straightforward approach to solve this problem.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe approach taken in this solution is a simple brute-force algorithm where we check every pair of characters in the string s. If we find two characters that are equal, we calculate the distance between them by subtracting their indices and subtracting 1. If the calculated distance does not match the corresponding value in the vector distance for that character, we return false because it means we cannot replace that character to get the desired distances.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n^2) as we are using two loops and traversing the whole string each time.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1) is a constant time \n\n# Code\n```\nclass Solution {\npublic:\n \t bool checkDistances(string s, vector<int>& distance) {\n\t\tint n=s.size();\n\n\t\tfor(int i=0;i<n;i++){\n\t\t\tfor(int j=i+1;j<n;j++){\n\t\t\t\tif(s[i]==s[j]){\n\t\t\t\t\tif(j-i-1 != distance[s[i]-\'a\']){//(s[i]-\'a\' helps to access the particular character)\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n};\n``` | 6 | 0 | ['C++'] | 1 |
check-distances-between-same-letters | Beginner friendly [Java/JavaScript/Python] Solution | beginner-friendly-javajavascriptpython-s-nn5b | Time Complexity : O(n)\nJava\n\nclass Solution {\n public boolean checkDistances(String s, int[] distance) {\n int[] arr = new int[26];\n for(i | HimanshuBhoir | NORMAL | 2022-09-10T02:08:21.061912+00:00 | 2022-09-10T02:13:57.442580+00:00 | 1,309 | false | **Time Complexity : O(n)**\n**Java**\n```\nclass Solution {\n public boolean checkDistances(String s, int[] distance) {\n int[] arr = new int[26];\n for(int i=0; i<s.length(); i++){\n if(arr[s.charAt(i) - \'a\'] != 0 && i - arr[s.charAt(i) - \'a\'] != distance[s.charAt(i) - \'a\']) \n return false;\n arr[s.charAt(i) - \'a\'] = i+1;\n }\n return true;\n }\n}\n```\n**JavaScript**\n```\nvar checkDistances = function(s, distance) {\n let arr = Array(26).fill(0)\n for(let i=0; i<s.length; i++){\n if(arr[s.charCodeAt(i) - 97] != 0 && i - arr[s.charCodeAt(i) - 97] != distance[s.charCodeAt(i) - 97]) \n return false\n arr[s.charCodeAt(i) - 97] = i+1\n }\n return true\n};\n```\n**Python**\n```\nclass Solution(object):\n def checkDistances(self, s, distance):\n arr = [0]*26\n for i in range(len(s)):\n if arr[ord(s[i]) - 97] != 0 and i - arr[ord(s[i]) - 97] != distance[ord(s[i]) - 97]:\n return False\n arr[ord(s[i]) - 97] = i+1\n return True\n``` | 6 | 0 | ['Python', 'Java', 'JavaScript'] | 2 |
check-distances-between-same-letters | Python Dictionary || Easy to understand | python-dictionary-easy-to-understand-by-q42ol | \nclass Solution:\n def checkDistances(self, s: str, distance: List[int]) -> bool: \n hashmap = {}\n for i in range(len(s)):\n | fight2023 | NORMAL | 2022-09-04T04:49:08.630264+00:00 | 2022-09-05T01:16:47.441180+00:00 | 1,105 | false | ```\nclass Solution:\n def checkDistances(self, s: str, distance: List[int]) -> bool: \n hashmap = {}\n for i in range(len(s)):\n if s[i] in hashmap and i - hashmap[s[i]] - 1 != distance[ord(s[i]) - ord(\'a\')]:\n return False\n hashmap[s[i]] = i \n return True\n```\n\t\t\nTime Complexitiey: O(n)\nSpace Complexitiey: O(n)\n \n | 6 | 0 | ['Python', 'Python3'] | 0 |
check-distances-between-same-letters | Beginner O(N^2) and Linear solution with explanation | beginner-on2-and-linear-solution-with-ex-nnxe | O(N^2) Approach: For each character s[i], check for all other characters s[j] where j ranges from i+1 to n. Compare the distance when i th and j th character is | shubhamsth | NORMAL | 2022-09-04T04:48:20.523668+00:00 | 2022-09-04T05:12:25.521289+00:00 | 521 | false | **O(N^2) Approach:** For each character `s[i]`, check for all other characters `s[j]` where `j` ranges from `i+1` to `n`. Compare the distance when `i th` and `j th` character is same.\n```\nbool checkDistances(string s, vector<int>& dist) {\n\tint n = s.size();\n\tfor(int i=0; i<n-1; i++)\n\t\tfor(int j=i+1; j<n; j++)\n\t\t\tif(s[i] == s[j] && j-i-1 != dist[s[i]-\'a\'])\n\t\t\t\treturn false;\n\treturn true;\n}\n```\n**O(N) Approach:** Keep the index of the first occurrence of the element and compare the distance when we come across it the second time.\n```\nbool checkDistances(string s, vector<int>& dist) {\n int n = s.size();\n vector<int> v(26, -1);\n for(int i=0; i<n; i++){\n if(v[s[i]-\'a\'] == -1) v[s[i]-\'a\'] = i;\n else if(i-v[s[i]-\'a\']-1 != dist[s[i]-\'a\']) return false;\n }\n return true;\n }\n``` | 6 | 0 | ['C'] | 0 |
check-distances-between-same-letters | CPP | Easy | cpp-easy-by-amirkpatna-0a06 | \nclass Solution {\npublic:\n bool checkDistances(string s, vector<int>& distance) {\n vector<int> v(26);\n int i=0;\n for(char c:s){\n | amirkpatna | NORMAL | 2022-09-04T04:08:26.272057+00:00 | 2022-09-04T04:08:26.272081+00:00 | 648 | false | ```\nclass Solution {\npublic:\n bool checkDistances(string s, vector<int>& distance) {\n vector<int> v(26);\n int i=0;\n for(char c:s){\n if(v[c-\'a\'] && distance[c-\'a\']!=i-v[c-\'a\'])return false;\n v[c-\'a\']=++i;\n }\n return true;\n }\n};\n``` | 6 | 0 | ['C++'] | 0 |
check-distances-between-same-letters | Simple java solution | simple-java-solution-by-siddhant_1602-qpsk | ```\nclass Solution {\n public boolean checkDistances(String s, int[] d) {\n for(int i=0;i<26;i++)\n {\n char c = (char)(\'a\'+i);\n | Siddhant_1602 | NORMAL | 2022-09-04T04:01:09.632620+00:00 | 2022-09-04T04:01:09.632660+00:00 | 597 | false | ```\nclass Solution {\n public boolean checkDistances(String s, int[] d) {\n for(int i=0;i<26;i++)\n {\n char c = (char)(\'a\'+i);\n if(s.contains(String.valueOf(c)))\n {\n int k = s.indexOf(c);\n int p = s.lastIndexOf(c);\n if(p-k-1!=d[i])\n return false;\n }\n }\n return true;\n }\n} | 6 | 1 | ['String', 'Java'] | 0 |
check-distances-between-same-letters | C++ | two-pointers | c-two-pointers-by-parwez01-ydf9 | if you get the both position,\n1. calculate distance\n2. check if distance is equal in distance array.\n3. if not return false\n4. if yes mark as those elements | parwez01 | NORMAL | 2022-09-04T04:06:43.518491+00:00 | 2022-09-04T04:06:43.518526+00:00 | 81 | false | if you get the both position,\n1. calculate distance\n2. check if distance is equal in distance array.\n3. if not return false\n4. if yes mark as those elements are visited.\n\nsimple intitutioin behind this questin.\n\n```\nclass Solution {\npublic:\n bool checkDistances(string s, vector<int>& distance) {\n for(int i = 0; i < s.size()-1; i++)\n {\n if(s[i] == \'#\')\n continue;\n int ct = 0;\n for(int j = i+1; j < s.size(); j++)\n {\n \n if(s[i] == s[j])\n {\n s[j] = \'#\';\n break;\n }\n else\n ct++;\n }\n if(distance[s[i]-\'a\'] != ct)\n return false;\n s[i] = \'#\';\n \n }\n \n return true;\n }\n};\n`` | 5 | 0 | ['Two Pointers', 'C'] | 0 |
check-distances-between-same-letters | ✅3 Method's || C++ || JAVA || PYTHON || Beginner Friendly🔥🔥🔥 | 3-methods-c-java-python-beginner-friendl-ha9v | Intuition\n Describe your first thoughts on how to solve this problem. \nThe "Check Distances Between Same Letters" problem involves validating if the distance | datpham0412 | NORMAL | 2024-04-21T04:46:22.903939+00:00 | 2024-04-21T04:46:22.903964+00:00 | 307 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe "Check Distances Between Same Letters" problem involves validating if the distance between each pair of identical letters in a string matches a specified value. This problem tests our ability to efficiently track positions and calculate distances in a string, with the additional challenge of ensuring every character aligns with given criteria. Given the constraints that each character appears exactly twice, this problem allows for multiple efficient solutions, each leveraging different data structures to manage and check character positions.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n## 1. Brute Force\nThe brute force method involves a nested loop where the outer loop picks each character as a potential start of a pair, and the inner loop searches for the second occurrence of the same character. The distance is then calculated and immediately checked against the provided **distance** array.\n1. Iterate over each character in the string.\n2. Use another loop starting from the next character to find the second occurrence.\n3. Calculate the distance between occurrences and check it against the expected distance.\n4. Return false upon finding any mismatch.\n\n## 2. Hashmap\nUsing a hashmap offers an efficient way to track the first occurrence of each character. Once the second occurrence is found, the distance is calculated and compared to the expected value immediately.\n1. Map each character to its first occurrence index using a hashmap.\n2. For each character found in the string, check if it has been seen before.\n3. If seen, calculate the distance to its first occurrence and verify against the **distance** array.\n4. Return false if any calculated distance doesn\'t match the expected distance.\n## 3. Array\nThis approach utilizes an array to directly store the first occurrence of each character, leveraging the fact that there are only 26 possible lowercase English letters. This method avoids the overhead of hash computation in a hashmap.\n\n1. Initialize an array of size 26 to -1, representing the index of the first occurrence of each letter.\n2. As you traverse the string, record the first occurrence of each letter.\n3. On encountering the second occurrence, calculate the distance to the first and compare it to the expected distance.\n4. Return false if there\'s a discrepancy.\n\n\n---\n\nThese approaches offer different trade-offs between simplicity and computational efficiency, making them suitable for different scenarios based on the size of the input and the specific requirements of the environment in which they are executed. The Hashmap and Array methods, in particular, provide optimal performance and are well-suited to situations requiring quick checks and minimal memory usage.\n\n# Complexity\n## 1. Brute Force\n- Time Complexity: O(n^2)\n- Space Complexity: O(1)\n## 2. Hashmap\n- Time Complexity: O(n)\n- Space Complexity: O(1)\n## 3. Array\n- Time Complexity: O(n)\n- Space Complexity: O(1)\n# Code\n## 1. Brute Force\n```C++ []\nclass Solution {\npublic:\n bool checkDistances(string s, vector<int>& distance) {\n for (int i = 0; i < s.length(); i++) {\n char current = s[i]; \n for (int j = i + 1; j < s.length(); j++) {\n if (current == s[j]) { // Ensuring \'current\' is the same as \'s[j]\'\n int distBetween = j - i - 1; \n if (distBetween != distance[current - \'a\']) { // Direct comparison\n return false; // Return false immediately if the distance doesn\'t match\n }\n }\n }\n }\n return true; // Return true if no mismatches are found\n }\n};\n\n```\n```Java []\nclass Solution {\n public boolean checkDistances(String s, int[] distance) {\n for (int i = 0; i < s.length(); i++) {\n char current = s.charAt(i);\n for (int j = i + 1; j < s.length(); j++) {\n if (current == s.charAt(j)) {\n int distBetween = j - i - 1;\n if (distBetween != distance[current - \'a\']) {\n return false; // Return false if the distance does not match\n }\n }\n }\n }\n return true; // Return true if all characters match the distances\n }\n}\n\n```\n```Python3 []\nclass Solution:\n def checkDistances(self, s: str, distance: List[int]) -> bool:\n for i in range(len(s)):\n current = s[i]\n for j in range(i + 1, len(s)):\n if current == s[j]:\n distBetween = j - i - 1\n if distBetween != distance[ord(current) - ord(\'a\')]:\n return False # Return false if the distance doesn\'t match\n return True # Return true if all distances are correct\n\n```\n\n## 2. Hashmap\n```C++ []\nclass Solution {\npublic:\n bool checkDistances(string s, vector<int>& distance) {\n unordered_map <char,int> seen;\n for (int i = 0; i < s.size(); i++){\n if(seen.count(s[i])){\n if (distance[s[i] - \'a\'] != i - seen[s[i]] - 1){\n return false;\n }\n }\n seen[s[i]] = i;\n }\n return true;\n }\n};\n```\n```Java []\nclass Solution {\n public boolean checkDistances(String s, int[] distance) {\n HashMap<Character, Integer> seen = new HashMap<>();\n for (int i = 0; i < s.length(); i++) {\n char ch = s.charAt(i);\n if (seen.containsKey(ch)) {\n if (distance[ch - \'a\'] != i - seen.get(ch) - 1) {\n return false; // Return false if the distance doesn\'t match\n }\n } else {\n seen.put(ch, i);\n }\n }\n return true; // Return true if all characters match the distances\n }\n}\n\n```\n```Python3 []\nclass Solution:\n def checkDistances(self, s: str, distance: list[int]) -> bool:\n seen = {}\n for i, ch in enumerate(s):\n if ch in seen:\n if distance[ord(ch) - ord(\'a\')] != i - seen[ch] - 1:\n return False # Return false if the distance doesn\'t match\n else:\n seen[ch] = i\n return True # Return true if all distances are correct\n\n```\n\n## 3. Array\n```C++ []\nclass Solution {\npublic:\n bool checkDistances(string s, vector<int>& distance) {\n vector<int> firstIndex(26, -1); // Initialize all indices to -1\n \n for (int i = 0; i < s.size(); i++) {\n int index = s[i] - \'a\'; // Convert character to index\n if (firstIndex[index] == -1) {\n firstIndex[index] = i; // Store the first occurrence\n } else {\n // Calculate the distance and check\n if (i - firstIndex[index] - 1 != distance[index]) {\n return false; // Return false if distances do not match\n }\n }\n }\n \n return true; // Return true if all checked distances are correct\n }\n};\n\n```\n```Java []\nclass Solution {\n public boolean checkDistances(String s, int[] distance) {\n int[] firstIndex = new int[26]; // Initialize array to store first occurrences\n java.util.Arrays.fill(firstIndex, -1); // Set all indices to -1\n\n for (int i = 0; i < s.length(); i++) {\n int index = s.charAt(i) - \'a\';\n if (firstIndex[index] == -1) {\n firstIndex[index] = i; // Store the first occurrence\n } else {\n // Calculate the distance and check against provided distance\n if (i - firstIndex[index] - 1 != distance[index]) {\n return false; // Return false if distances do not match\n }\n }\n }\n\n return true; // Return true if all distances are correct\n }\n}\n```\n```Python3 []\nclass Solution:\n def checkDistances(self, s: str, distance: list[int]) -> bool:\n firstIndex = [-1] * 26 # Initialize list to store first occurrences\n\n for i, char in enumerate(s):\n index = ord(char) - ord(\'a\')\n if firstIndex[index] == -1:\n firstIndex[index] = i # Store the first occurrence\n else:\n # Calculate the distance and check against provided distance\n if i - firstIndex[index] - 1 != distance[index]:\n return False # Return false if distances do not match\n\n return True # Return true if all distances are correct\n\n```\n\n\n\n### If you found my solution useful, I\'d truly appreciate your upvote. Your support encourages me to keep sharing more solutions. Thank you!!!\n\n\n | 4 | 0 | ['Array', 'Hash Table', 'C++', 'Java', 'Python3'] | 1 |
check-distances-between-same-letters | Easy and Simple Python Solution | easy-and-simple-python-solution-by-sanga-z85b | \nclass Solution:\n def checkDistances(self, s: str, distance: List[int]) -> bool:\n dic={}\n letter=97\n for i in distance:\n | sangam92 | NORMAL | 2022-10-06T06:02:23.417625+00:00 | 2022-10-06T06:03:06.551234+00:00 | 861 | false | ```\nclass Solution:\n def checkDistances(self, s: str, distance: List[int]) -> bool:\n dic={}\n letter=97\n for i in distance:\n dic[chr(letter)]=i\n letter+=1\n\n for i in set(s):\n first=s.index(i)\n last=s.rindex(i)\n diff=last-first-1\n if dic[i]!=diff:\n return False\n return True\n``` | 4 | 0 | ['Python'] | 0 |
check-distances-between-same-letters | c++ solution||constant space | c-solutionconstant-space-by-anvitha1221-l6mz | \n\nclass Solution {\npublic:\n bool checkDistances(string s, vector<int>& distance) {\n int n=s.length();\n for(int i=0;i<n;i++){\n if(dist | anvitha1221 | NORMAL | 2022-09-04T05:02:36.992460+00:00 | 2022-09-04T05:04:05.716778+00:00 | 161 | false | ```\n\nclass Solution {\npublic:\n bool checkDistances(string s, vector<int>& distance) {\n int n=s.length();\n for(int i=0;i<n;i++){\n if(distance[s[i]-\'a\']==-1){\n\t\t//marked as not valid in the previous visit so return false \n return false;\n }\n \n \n int next=distance[s[i]-\'a\']+1+i;\n if(next<n&&s[next]==s[i]){\n //do nothing because another occurance present at next \n }\n else{\n distance[s[i]-\'a\']=-1;\n\t\t\t\t//second visit or next occurance not present \n\t\t\t\t//next time if accessed again return false;\n }\n \n\n }\n return true;\n }\n};\n``` | 4 | 0 | ['C'] | 0 |
check-distances-between-same-letters | please read the note mentioned in test case 1 ho jayega easy hee hai kar har maidan fateh !!! :D | please-read-the-note-mentioned-in-test-c-a9r2 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | yesyesem | NORMAL | 2024-09-01T19:30:06.334670+00:00 | 2024-09-01T19:30:06.334695+00:00 | 30 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n bool checkDistances(string s, vector<int>& distance) {\n vector<int>arr(26,-1);\n\n for(int i=0;i<s.length()-1;i++)\n {\n for(int j=i+1;j<s.length();j++)\n {\n if(s[i]==s[j])\n {\n arr[s[i]-97]=j-i-1;\n }\n }\n }\n for(int i=0;i<arr.size();i++)\n {\n if(arr[i]!=-1)\n {\n if(distance[i]!=arr[i])\n return false;\n }\n\n }\n return true;\n }\n};\n``` | 3 | 0 | ['C++'] | 0 |
check-distances-between-same-letters | Rust | O(n) | 1ms | rust-on-1ms-by-user7454af-ftl0 | Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(1)\n\n# Code\n\nimpl Solution {\n pub fn check_distances(s: String, mut distance: Vec<i32>) -> b | user7454af | NORMAL | 2024-06-23T21:28:25.323517+00:00 | 2024-06-23T21:28:25.323548+00:00 | 11 | false | # Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(1)$$\n\n# Code\n```\nimpl Solution {\n pub fn check_distances(s: String, mut distance: Vec<i32>) -> bool {\n let sb = s.into_bytes();\n for (i, &b) in sb.iter().enumerate() {\n match distance[(b-b\'a\') as usize] {\n -1 => continue,\n d @ _ => {\n let idx = i + d as usize + 1;\n if idx >= sb.len() || sb[idx] != b {return false};\n distance[(b-b\'a\') as usize] = -1;\n }\n }\n }\n true\n }\n}\n``` | 3 | 0 | ['Rust'] | 0 |
check-distances-between-same-letters | ✔✔✔💯% beats in runtime. Beginner friendly solution. | beats-in-runtime-beginner-friendly-solut-cubs | 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 | hikmatulloanvarbekov001 | NORMAL | 2023-07-20T15:21:39.275862+00:00 | 2023-07-20T15:21:39.275883+00:00 | 184 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public boolean checkDistances(String s, int[] distance) {\n HashSet<Character> set = new HashSet<>();\n for(int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n int ind = 0;\n if(set.contains(c)) {\n continue;\n }\n for(int j = i+1; j < s.length(); j++){ \n if(s.charAt(j) == c) {\n ind = j;\n }\n }\n set.add(c);\n if(ind-i-1 != distance[c - \'a\']){ \n return false;\n }\n }\n return true;\n // if it is helpful, pls upvote it.\n }\n}\n``` | 3 | 0 | ['Java'] | 2 |
check-distances-between-same-letters | ✅✅✅100% faster python solution. | 100-faster-python-solution-by-najmiddin1-j6i4 | \n\n- In the loop, we need to find and divide the index of the next letter of the letter s[i], and if the difference between these two values is not equal to ea | Najmiddin1 | NORMAL | 2022-12-17T09:10:44.414489+00:00 | 2022-12-17T09:10:44.414531+00:00 | 704 | false | \n\n- In the loop, we need to find and divide the index of the next letter of the letter `s[i]`, and if the difference between these two values is not equal to each other, then we just set the result as `False`. If there is no `False` result, then the answer is `True`. Inside the loop I used `try` and `except` because inside s a letter is repeated twice or 0 times, so when we get a letter the second time it comes and no similar letter comes after it, we have index an error occurs because we use the function.\n# Code\n```\nclass Solution:\n def checkDistances(self, s: str, distance: List[int]) -> bool:\n for i in range(len(s)):\n try:\n if s[i+1:].index(s[i])!=distance[ord(s[i])-97]: return False\n except: pass\n return True\n``` | 3 | 0 | ['Python', 'Python3'] | 0 |
check-distances-between-same-letters | C++ || keep an index of the first occurrence || clean code || easy to understand || fast (0ms) | c-keep-an-index-of-the-first-occurrence-r6jhx | Solution 1: keep an index of the first occurrence\n\nWe actually keep track of the first occurrence plus one, with that we can just initialize the index with ze | heder | NORMAL | 2022-09-04T14:40:51.425438+00:00 | 2022-09-04T14:40:51.425476+00:00 | 227 | false | ### Solution 1: keep an index of the first occurrence\n\nWe actually keep track of the first occurrence plus one, with that we can just initialize the index with zeros and we would need to substract this one when checking the distance anyway. We are using an ```array<>``` here as it has less overhead than ```vector```. A ```vector``` would have the benefit that we could conveniently initialize with -1s, for the ```array<int, 26>``` we would need to call ```fill(begin(pos), end(pos), -1)```. \n\n```\n bool checkDistances(const string& s, const vector<int>& distance) {\n array<int, 26> pos = {};\n for (int i = 0; i < size(s); ++i) {\n const char ch = s[i] - \'a\';\n if (pos[ch]) {\n if (i - pos[ch] != distance[ch]) return false;\n } else {\n pos[ch] = i + 1;\n }\n }\n return true;\n }\n```\t\n\n**Complexity Analysis**\n * Time Complexity: O(size(s)), we need to look at each charter once\n * Space Complexity: O(1), the ```pos``` is always of size 26 * sizeof(int) regardless of the size of the input. | 3 | 0 | ['C'] | 0 |
check-distances-between-same-letters | Easy solution using string functions | easy-solution-using-string-functions-by-djimz | class Solution {\npublic:\n bool checkDistances(string s, vector& v) {\n \n int n=26;\n for(int i=0;i<26;i++)\n {\n in | aryanshsingla | NORMAL | 2022-09-04T12:23:43.506687+00:00 | 2022-09-04T12:24:53.389672+00:00 | 101 | false | class Solution {\npublic:\n bool checkDistances(string s, vector<int>& v) {\n \n int n=26;\n for(int i=0;i<26;i++)\n {\n int t=97+i;\n char ch=t;\n int x=s.find(t);\n int y=s.rfind(t);\n if(y==-1)continue;\n if((y-x-1)!=v[i])return false;\n }\n return true;\n \n }\n}; | 3 | 0 | ['C'] | 0 |
check-distances-between-same-letters | c++ | Faster than 100% | Two Approaches | c-faster-than-100-two-approaches-by-theo-7z4v | To get index of distance for current string element, we need to substract \n\t\tcurr element from \'a\'.\n\t\t cur = a, it\'s corresponding distance index == a | theomkumar | NORMAL | 2022-09-04T05:09:31.491308+00:00 | 2022-09-04T05:09:31.491344+00:00 | 587 | false | To get index of distance for current string element, we need to substract \n\t\tcurr element from \'a\'.\n\t\t* cur = a, it\'s corresponding distance index == a - a = 0\n\t\t* cur = b, b - a = 1\n\t\t* cur = c, c - a = 2\n\nApproach 1: SC -> O(1)\n\t \n ```\nbool checkDistances(string s, vector<int>& distance) {\n for (int i = 0; i < s.size(); i++)\n {\n char cur = s[i];\n for (int j = i+1; j < s.size(); j++)\n {\n if (s[i] == s[j])\n {\n int dist = j - i - 1; \n if (distance[cur - \'a\'] != dist)\n return false;\n }\n }\n }\n```\n\nApproach 2: using map , SC -> O(n)\n\n```\nbool checkDistances(string s, vector<int>& distance) {\n map<char,bool> marked;\n for (int i = 0; i < s.size(); i++)\n {\n if (marked[s[i]] == 0)\n {\n marked[s[i]] = 1;\n char curr = s[i];\n int cnt = 0;\n for (int j = i+1; (s[j] != s[i]) && j < s.size(); j++)\n {\n cnt++;\n }\n if (distance[curr - \'a\'] != cnt)\n return false;\n }\n }\n return true;\n }\n```\n | 3 | 0 | ['C', 'C++'] | 0 |
check-distances-between-same-letters | ✅ JavaScript | Map | TC O(n) | SC O(n) | javascript-map-tc-on-sc-on-by-thakurball-29gb | \n/**\n * @param {string} s\n * @param {number[]} distance\n * @return {boolean}\n */\nvar checkDistances = function(s, distance) {\n const map = {};\n \n | thakurballary | NORMAL | 2022-09-04T04:02:56.169189+00:00 | 2022-09-04T04:02:56.169238+00:00 | 348 | false | ```\n/**\n * @param {string} s\n * @param {number[]} distance\n * @return {boolean}\n */\nvar checkDistances = function(s, distance) {\n const map = {};\n \n for (let i = 0; i < s.length; i++) {\n if (map[s[i]] !== undefined) {\n const diff = i - map[s[i]] - 1;\n const charCode = s[i].charCodeAt() - 97;\n if (distance[charCode] !== diff) {\n return false;\n }\n } else {\n map[s[i]] = i;\n }\n }\n \n return true;\n};\n``` | 3 | 0 | ['JavaScript'] | 1 |
check-distances-between-same-letters | Find left and right index | Explained | find-left-and-right-index-explained-by-n-67wi | We know that there are only 2 occurences of the same character in S if it exists.\nAnd it must be distanced distance[char] from each other.\n\nWe can find the i | nadaralp | NORMAL | 2022-09-04T04:01:13.260232+00:00 | 2022-09-04T04:01:13.260272+00:00 | 434 | false | We know that there are only 2 occurences of the same character in S if it exists.\nAnd it must be distanced distance[char] from each other.\n\nWe can find the index on the left and right side and check whether the distance is distance[char].\nIf the character doesn\'t exist we ignore.\n\n```\nclass Solution:\n def checkDistances(self, s: str, distance: List[int]) -> bool:\n for char in range(26):\n c = chr(char + ord(\'a\'))\n left = s.find(c)\n right = s.rfind(c)\n \n # Ignore if character doesn\'t exist\n if left == -1: continue\n\n if right - left - 1 != distance[char]:\n return False\n \n return True\n``` | 3 | 0 | ['Python'] | 0 |
check-distances-between-same-letters | Java solution || Beats 99% || easy explanation | java-solution-beats-99-easy-explanation-d59ui | \n# Approach\n Describe your approach to solving the problem. \n\n\n1. It initializes a HashMap called map to keep track of the last index at which each charact | akanksha41 | NORMAL | 2023-10-20T12:20:10.209158+00:00 | 2023-10-20T12:20:10.209176+00:00 | 185 | false | \n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n\n1. It initializes a `HashMap` called `map` to keep track of the last index at which each character appears in the string.\n\n2. It iterates through each character in the input string `s` using a for loop.\n\n3. For each character `ch`, it checks whether `ch` is already in the `map` (i.e., it has been encountered before in the string).\n\n a. If `ch` is in the `map`, it calculates the distance `space` between the current index `i` and the last index at which `ch` appeared (stored in `index`). Then, it checks if the calculated `space` is equal to the corresponding value in the `distance` array for that character. If it\'s not equal, the method returns `false`, indicating that the distance constraint is not satisfied.\n\n b. If `ch` is not in the `map`, it adds the character `ch` to the `map` with its current index `i`.\n\n4. If the method has iterated through the entire string without encountering any violations of the distance constraints, it returns `true`, indicating that all characters in the string satisfy the given distance constraints.\n\n\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public boolean checkDistances(String s, int[] distance) {\n \n HashMap<Character,Integer> map =new HashMap<>();\n\n for(int i=0; i<s.length(); i++) {\n char ch = s.charAt(i);\n\n if(map.containsKey(ch)) {\n int index = map.get(ch);\n int space = i-index-1;\n if(distance[ch-\'a\'] != space) {\n return false;\n }\n }\n else {\n map.put(ch,i);\n }\n }\n return true;\n }\n}\n``` | 2 | 0 | ['Array', 'Hash Table', 'String', 'Java'] | 0 |
check-distances-between-same-letters | Check Distance Between Same Letters | check-distance-between-same-letters-by-a-srfm | \n\n# Code\n\nclass Solution {\npublic:\n bool checkDistances(string s, vector<int>& distance) {\n int val=0;\n for(int i=0;i<s.size();i++)\n | AbhayDabral17 | NORMAL | 2023-06-20T20:24:31.918216+00:00 | 2023-06-20T20:24:31.918239+00:00 | 71 | false | \n\n# Code\n```\nclass Solution {\npublic:\n bool checkDistances(string s, vector<int>& distance) {\n int val=0;\n for(int i=0;i<s.size();i++)\n {\n for(int j=i+1;j<s.size();j++)\n {\n if(s[j]==s[i])\n {\n val=(int)s[i]-97;\n if((j-i-1)!=distance[val])\n return false;\n }\n }\n }\n return true;\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
check-distances-between-same-letters | [Java] Simple O(n) solution | java-simple-on-solution-by-ytchouar-isrk | java\nclass Solution {\n public boolean checkDistances(String s, int[] distance) {\n int[] range = new int[distance.length];\n Arrays.fill(rang | YTchouar | NORMAL | 2023-05-02T22:24:45.664530+00:00 | 2023-05-02T22:24:45.664566+00:00 | 581 | false | ```java\nclass Solution {\n public boolean checkDistances(String s, int[] distance) {\n int[] range = new int[distance.length];\n Arrays.fill(range, -1);\n\n for(int i = 0; i < s.length(); ++i) {\n int index = s.charAt(i) - \'a\';\n\n if(range[index] != -1 && Math.abs(range[index] - i) != distance[index] + 1)\n return false;\n\n range[index] = i;\n }\n\n return true;\n }\n}\n``` | 2 | 0 | ['Java'] | 1 |
check-distances-between-same-letters | Easy C++ Solution using hashmaps | easy-c-solution-using-hashmaps-by-reehan-8fof | Intuition\nOur goal is to check if the given string s is well-spaced according to the given distances. We will iterate through the string and record the first a | Reehan9 | NORMAL | 2023-04-04T05:31:44.244682+00:00 | 2023-04-04T05:31:44.244712+00:00 | 470 | false | # Intuition\nOur goal is to check if the given string s is well-spaced according to the given distances. We will iterate through the string and record the first and second occurrences of each character. Then, we will compare the recorded distances to the given distance vector to determine if the string is well-spaced.\n\n# Approach\n- Initialize an unordered_map check to store the first and second occurrences of each character in the string. Set initial values to -1.\n- Iterate through the string, and for each character, update its first and second occurrence in check.\n- Iterate through the check unordered_map and compare the recorded distances for each character to the given distance vector. If any character\'s distance does not match, return false.\n- If all characters have matching distances, return true.\n\n\n# Complexity\n- Time complexity:\nTime complexity: O(n), where n is the length of the string s. We iterate through the string once to update occurrences and once more to check distances.\n\n- Space complexity:\nSpace complexity: O(1), as we are using a fixed-size unordered_map for the 26 lowercase English letters.\n\n# Code\n```\nclass Solution {\npublic:\n bool checkDistances(string s, vector<int>& distance) {\n unordered_map<char, pair<int, int>> check;\n for (char c = \'a\'; c <= \'z\'; ++c) \n check[c] = make_pair(-1, -1);\n for(int i = 0 ; i < s.size() ; i++){\n if(check[s[i]].first==-1){\n check[s[i]].first = i;\n }\n else if(check[s[i]].second==-1){\n check[s[i]].second = i;\n }\n }\n for(auto p : check) {\n if(distance[p.first-\'a\']!=p.second.second-p.second.first-1 && p.second.first!=-1) \n return false;\n } \n return true;\n }\n};\n```\n\nPlease upvote if you find this helpful | 2 | 0 | ['C++'] | 2 |
check-distances-between-same-letters | Python3 easy solution | python3-easy-solution-by-amitpandit03-6jbh | \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 | amitpandit03 | NORMAL | 2023-03-10T22:34:48.741129+00:00 | 2023-03-10T22:34:48.741162+00:00 | 322 | false | \n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def checkDistances(self, s: str, dis: List[int]) -> bool:\n d = {}\n for i in range(len(s)):\n if s[i] not in d:\n d[s[i]] = i + 1\n else:\n if dis[ord(s[i])-ord(\'a\')] != i - d[s[i]]:\n return False\n return True\n\n``` | 2 | 0 | ['Array', 'Hash Table', 'String', 'Python3'] | 0 |
check-distances-between-same-letters | JS very easy solution with O(n) | js-very-easy-solution-with-on-by-kunkka1-in4g | Code\n\n/**\n * @param {string} s\n * @param {number[]} distance\n * @return {boolean}\n */\nvar checkDistances = function(s, distance) {\n const hashmap = n | kunkka1996 | NORMAL | 2022-11-04T07:18:06.651131+00:00 | 2022-11-04T07:18:06.651198+00:00 | 543 | false | # Code\n```\n/**\n * @param {string} s\n * @param {number[]} distance\n * @return {boolean}\n */\nvar checkDistances = function(s, distance) {\n const hashmap = new Map();\n\n for (let i = 0; i < s.length; i++) {\n const character = s[i];\n if (hashmap.has(character)) {\n if (i - hashmap.get(character) - 1 !== distance[s.charCodeAt(i) - 97]) return false;\n } else {\n hashmap.set(character, i);\n }\n }\n\n return true;\n};\n``` | 2 | 0 | ['Hash Table', 'JavaScript'] | 0 |
check-distances-between-same-letters | [JAVA] 6 liner easy solution | java-6-liner-easy-solution-by-jugantar20-e6n6 | \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 | Jugantar2020 | NORMAL | 2022-11-04T06:15:23.378962+00:00 | 2022-11-04T06:15:23.379011+00:00 | 629 | false | \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 boolean checkDistances(String s, int[] distance) {\n HashMap<Character, Integer> map = new HashMap<>();\n for(int i = 0; i < s.length(); i ++) {\n if(! map.containsKey(s.charAt(i)))\n map.put(s.charAt(i), i + 1);\n\n else if(distance[s.charAt(i)-\'a\'] != i-map.get(s.charAt(i)))\n return false; \n }\n return true; \n }\n}\n``` | 2 | 0 | ['Java'] | 0 |
check-distances-between-same-letters | Easiest C++ Solution || O(n) solution || O(1) space | easiest-c-solution-on-solution-o1-space-kfnmx | \n# Code\n\nclass Solution {\npublic:\n bool checkDistances(string s, vector<int>& distance) {\n for(int i=0;i<s.length();i++){\n if(distan | Shristha | NORMAL | 2022-10-20T03:51:09.963944+00:00 | 2022-10-20T03:51:09.963984+00:00 | 901 | false | \n# Code\n```\nclass Solution {\npublic:\n bool checkDistances(string s, vector<int>& distance) {\n for(int i=0;i<s.length();i++){\n if(distance[s[i]-97]!=-1){\n int next=i+(distance[s[i]-97]+1);\n\n if((next>=s.length())||(next<s.length() && s[next]!=s[i])){\n return false;\n }\n distance[s[i]-97]=-1;\n }\n\n }\n return true;\n\n \n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
check-distances-between-same-letters | C++ Solution | Easy to understand | c-solution-easy-to-understand-by-shivi_0-6qms | \t**Please Upvote if you like my solution !!!! :)****\n\t\n\t unordered_mapmp;\n\t\t \n for(int i=0;i<s.size();i++)\n {\n \n if(mp. | shivi_071996 | NORMAL | 2022-10-06T07:12:39.079470+00:00 | 2022-10-20T03:35:05.227437+00:00 | 132 | false | \t******Please Upvote if you like my solution !!!! :)******\n\t\n\t unordered_map<int,int>mp;\n\t\t \n for(int i=0;i<s.size();i++)\n {\n \n if(mp.find(s[i]-\'a\')==mp.end())\n {\n mp[(s[i]-\'a\')]=i;\n }\n else\n {\n int dist=(i-mp[(s[i]-\'a\')])-1;\n if(dist!=distance[(s[i]-\'a\')])\n return false;\n }\n \n }\n return true;\n\t\t\n\t\t\n\t\tWe need to keep track of first occurence of the letter in the map ,\n\t\tthen if we come across the same letter while iterating over the string , \n\t\twe calculate the distance between the current and the same letter in the map\n\t\tas (currIndex-indexInMap)-1 , this gives the number of characters in between . \n\t\tIf this distance is not equal to the value in distance array we return false else true.\n | 2 | 0 | [] | 0 |
check-distances-between-same-letters | Tracking first occurrences | tracking-first-occurrences-by-fllght-0463 | Java\njava\npublic boolean checkDistances(String s, int[] distance) {\n int[] firstOccurrences = new int[26];\n Arrays.fill(firstOccurrences, -1); | FLlGHT | NORMAL | 2022-10-05T14:34:56.946290+00:00 | 2022-10-05T14:35:11.226057+00:00 | 484 | false | ##### Java\n```java\npublic boolean checkDistances(String s, int[] distance) {\n int[] firstOccurrences = new int[26];\n Arrays.fill(firstOccurrences, -1);\n\n for (int i = 0; i < s.length(); ++i) {\n int letterNumber = s.charAt(i) - \'a\';\n if (firstOccurrences[letterNumber] == -1)\n firstOccurrences[letterNumber] = i;\n else\n if (distance[letterNumber] != i - firstOccurrences[letterNumber] - 1)\n return false;\n }\n return true;\n }\n```\n\n##### C++\n```c++\npublic:\n bool checkDistances(string s, vector<int> &distance) {\n vector<int> firstOccurrences(26, -1);\n\n for (int i = 0; i < s.size(); ++i) {\n int letterNumber = s[i] - \'a\';\n if (firstOccurrences[letterNumber] == -1)\n firstOccurrences[letterNumber] = i;\n else\n if (distance[letterNumber] != i - firstOccurrences[letterNumber] - 1)\n return false;\n }\n\n return true;\n }\n``` | 2 | 0 | ['C', 'Java'] | 0 |
check-distances-between-same-letters | Java using indexOf with comments | java-using-indexof-with-comments-by-pete-78l0 | \nclass Solution {\n public boolean checkDistances(String s, int[] distance) {\n // for each char in s to char array\n for (char c : s.toCharAr | peterTorres | NORMAL | 2022-10-01T18:29:45.049854+00:00 | 2022-10-01T18:29:45.049894+00:00 | 151 | false | ```\nclass Solution {\n public boolean checkDistances(String s, int[] distance) {\n // for each char in s to char array\n for (char c : s.toCharArray()) {\n // init first to s index of char\n int first = s.indexOf(c);\n // init second to s last index of char\n int second = s.lastIndexOf(c);\n\n // if distance at char - \'a\' is not equal to second minus first minus 1\n if (distance[c - \'a\'] != second - first - 1) {\n // return false\n return false;\n }\n }\n \n // return true\n return true;\n }\n}\n``` | 2 | 0 | ['Java'] | 0 |
check-distances-between-same-letters | C++ || Brute Force + Optimised Solution | c-brute-force-optimised-solution-by-kuma-8khf | Optimised Solution -:\nTime Complexity -> O(n)\nSpace Complexity -> O(1)\n\n\tbool checkDistances(string s, vector& distance) {\n\n\t\tunordered_map mpp;\n | kumarpawansahh | NORMAL | 2022-09-30T13:28:57.530141+00:00 | 2022-09-30T13:28:57.530176+00:00 | 297 | false | Optimised Solution -:\nTime Complexity -> O(n)\nSpace Complexity -> O(1)\n\n\tbool checkDistances(string s, vector<int>& distance) {\n\n\t\tunordered_map<char,int> mpp;\n \n for(int i=0;i<s.size();i++){\n if(mpp[s[i]]==0){\n mpp[s[i]]=i+1;\n }\n else{\n if(distance[s[i]-\'a\'] != i-mpp[s[i]]){\n return false;\n }\n }\n }\n return true;\n }\n\t\n\t\n\n Brute Solution:-\n Time Complexity -> O(n^2)\n Space Complexity -> O(1)\n\t\n \n\t\t bool checkDistances(string s, vector<int>& distance) {\n\t\t\tint n=s.size();\n\n\t\t\tfor(int i=0;i<n;i++){\n\t\t\t\tfor(int j=i+1;j<n;j++){\n\t\t\t\t\tif(s[i]==s[j]){\n\t\t\t\t\t\tif(j-i-1 != distance[s[i]-\'a\']){\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t} | 2 | 0 | ['Array', 'String'] | 1 |
check-distances-between-same-letters | Simple Python Solution | simple-python-solution-by-mediocre-coder-b1fq | \nclass Solution:\n def checkDistances(self, s: str, distance: List[int]) -> bool:\n visited = ""\n \n for alpha in s:\n if a | mediocre-coder | NORMAL | 2022-09-06T20:55:00.571899+00:00 | 2022-09-06T20:55:00.571938+00:00 | 105 | false | ```\nclass Solution:\n def checkDistances(self, s: str, distance: List[int]) -> bool:\n visited = ""\n \n for alpha in s:\n if alpha not in visited:\n visited += alpha\n if s.rindex(alpha) - s.index(alpha) - 1 != distance[ord(alpha) - 97]:\n return False\n \n return True\n``` | 2 | 0 | ['Python'] | 0 |
check-distances-between-same-letters | ✅ [TypeScript] 100%, one-pass & in-place solution (with detailed comments) | typescript-100-one-pass-in-place-solutio-5rum | This solution checks the correctness of distances in one pass by performing in-place operations. It demonstrated 59 ms runtime (100.00%) and used 45.1 MB memory | stanislav-iablokov | NORMAL | 2022-09-06T13:36:20.989460+00:00 | 2022-10-23T13:01:00.400729+00:00 | 45 | false | This [solution](https://leetcode.com/submissions/detail/793015446/) checks the correctness of distances in one pass by performing in-place operations. It demonstrated **59 ms runtime (100.00%)** and used **45.1 MB memory (70.59%)**. Detailed comments are provided.\n\n**IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE.**\n```\n// [1] we will not allocate additional storage for indices, but\n// rather use \'distance\' in a clever way\nfunction checkDistances(s: string, distance: number[]): boolean \n{\n let letter: number;\n const a = \'a\'.charCodeAt(0);\n for (let pos = 0; pos < s.length; pos++)\n {\n letter = s[pos].charCodeAt(0) - a;\n\n // [2] provided that elements in \'distance\' are initially >= 0, \n // we can manage two states for first and second occurences of each letter;\n // this will allow us to ensure that, for correct distances, the following holds:\n // \'second\' - \'first\' + 1 - \'distance\' = 0\n if (distance[letter] >= 0)\n {\n // [3] state 1: first occurence of the letter;\n // we put \'-1\' to guarantee that distance[letter] < 0 for correct distance\n // (namely, the state will be switched to \'letter was encountered once\')\n distance[letter] = - distance[letter] - pos - 1;\n }\n else\n {\n // [4] state 2: second occurence of the letter\n // if we\'d put \'+1\' here (instead of \'-1\' in the previous block) \n // then the algorithm will fail changing the state for distance[letter] = pos = 0\n distance[letter] += pos;\n\n // [5] once wrong distance is found, return false\n if (distance[letter] != 0) return false;\n }\n }\n\n // [6] if no wrong distance was found, return true\n return true;\n};\n``` | 2 | 0 | ['TypeScript'] | 1 |
check-distances-between-same-letters | Simple solution keeps track of first and last position! | simple-solution-keeps-track-of-first-and-6b18 | Time complexity: O(N) length of the string\nSpace complexity: O(1) hashmap with constant length 26\n\nclass Solution {\npublic:\n bool checkDistances(string | YixingChen | NORMAL | 2022-09-04T22:00:10.230158+00:00 | 2022-09-04T22:00:10.230186+00:00 | 84 | false | Time complexity: O(N) length of the string\nSpace complexity: O(1) hashmap with constant length 26\n```\nclass Solution {\npublic:\n bool checkDistances(string s, vector<int>& distance) {\n unordered_map<int, vector<int>> hash(26);\n for (int i = 0; i < s.size(); ++ i) hash[s[i] - \'a\'].emplace_back(i);\n for (int i = 0; i < 26; ++ i) {\n if (hash.count(i)) {\n int d = hash[i][1] - hash[i][0] - 1;\n if (distance[i] != d) return false;\n }\n }\n return true;\n }\n};\n``` | 2 | 0 | [] | 0 |
check-distances-between-same-letters | C++ || Unordered Map || Easy Solution | c-unordered-map-easy-solution-by-vibrant-r1fx | \nbool checkDistances(string s, vector<int>& distance) {\n unordered_map<char,int>m;\n for(int i=0;i<s.length();i++){\n int j=s[i]-\'a\ | vibrant_CoDeR | NORMAL | 2022-09-04T11:57:56.929293+00:00 | 2022-09-04T11:57:56.929339+00:00 | 52 | false | ```\nbool checkDistances(string s, vector<int>& distance) {\n unordered_map<char,int>m;\n for(int i=0;i<s.length();i++){\n int j=s[i]-\'a\';\n if(m.find(s[i])==m.end())\n m.insert({s[i],i});\n else if(i-m[s[i]]-1!=distance[j])\n return false;\n }\n return true;\n }\n```\t | 2 | 0 | [] | 0 |
check-distances-between-same-letters | Python || iterative || Easy | python-iterative-easy-by-1md3nd-c840 | Simple approch\n## Time -> O(n^2) {n <= 32}\n## Space -> O(1)\n\nclass Solution:\n def checkDistances(self, s: str, distance: List[int]) -> bool:\n | 1md3nd | NORMAL | 2022-09-04T10:28:34.985648+00:00 | 2022-09-04T10:28:34.985693+00:00 | 203 | false | # Simple approch\n## Time -> O(n^2) {n <= 32}\n## Space -> O(1)\n```\nclass Solution:\n def checkDistances(self, s: str, distance: List[int]) -> bool:\n n = len(s)\n for i in range(n-1):\n for j in range(i+1,n):\n if s[i] == s[j]:\n if distance[ord(s[i]) - 97] != (j - i - 1):\n return False\n else:\n break\n return True\n```\n\n### \uD83D\uDE02 Random Dev Meme\n<img src="https://random-memer.herokuapp.com/" width="400px"/>\n | 2 | 0 | ['Iterator', 'Python', 'Python3'] | 0 |
check-distances-between-same-letters | Swift O(n) solution using HashMap | swift-on-solution-using-hashmap-by-andre-ng3p | \nclass Solution {\n func checkDistances(_ s: String, _ distance: [Int]) -> Bool {\n var lettersMap: [Character: Int] = [:]\n for (i, c) in s.e | AndreevIVdev | NORMAL | 2022-09-04T09:11:02.089345+00:00 | 2022-09-04T09:11:02.089386+00:00 | 56 | false | ```\nclass Solution {\n func checkDistances(_ s: String, _ distance: [Int]) -> Bool {\n var lettersMap: [Character: Int] = [:]\n for (i, c) in s.enumerated() {\n if let letter = lettersMap[c] {\n lettersMap[c] = i - letter - 1\n } else {\n lettersMap[c] = i\n }\n }\n \n for letter in lettersMap {\n if letter.value != distance[Int(letter.key.asciiValue! - Character("a").asciiValue!)] {\n return false\n }\n }\n \n return true\n }\n}\n``` | 2 | 0 | ['Swift'] | 0 |
check-distances-between-same-letters | Java || Easy || Set || Linear Time Fast Solution | java-easy-set-linear-time-fast-solution-20ie4 | \nclass Solution {\n public boolean checkDistances(String s, int[] distance) {\n char[] str = s.toCharArray();\n boolean set[] = new boolean[26 | Lil_ToeTurtle | NORMAL | 2022-09-04T06:26:51.879252+00:00 | 2022-09-04T06:26:51.879298+00:00 | 297 | false | ```\nclass Solution {\n public boolean checkDistances(String s, int[] distance) {\n char[] str = s.toCharArray();\n boolean set[] = new boolean[26];\n Integer start[] = new Integer[26],end[] = new Integer[26];\n int i,j,res,n=str.length,ind;\n for(i=0;i<n;i++){\n ind = str[i]-\'a\';\n if(start[ind]==null) start[ind]=i;\n else end[ind]=i;\n set[ind]=true;\n }\n for(i=0;i<26;i++){\n if(set[i] && distance[i]!=(end[i]-start[i]-1)) return false;\n }\n return true;\n }\n}\n``` | 2 | 0 | ['Java'] | 1 |
check-distances-between-same-letters | C++ | Track Position | Very Easy Code | c-track-position-very-easy-code-by-ankit-g1yc | Please Upvote :)\n\n\nclass Solution {\npublic:\n bool checkDistances(string s, vector<int>& distance) {\n vector<int> a(26,-1);\n for(int i=0; | ankit4601 | NORMAL | 2022-09-04T06:16:32.563065+00:00 | 2022-09-04T06:16:32.563109+00:00 | 221 | false | Please Upvote :)\n\n```\nclass Solution {\npublic:\n bool checkDistances(string s, vector<int>& distance) {\n vector<int> a(26,-1);\n for(int i=0;i<s.length();i++)\n {\n int t=a[s[i]-\'a\'];\n if(t==-1)\n a[s[i]-\'a\']=i;\n else\n {\n t=i-t-1;\n if(distance[s[i]-\'a\']!=t)\n return 0;\n }\n }\n return 1;\n }\n};\n``` | 2 | 0 | ['C', 'C++'] | 0 |
check-distances-between-same-letters | ✅✅Faster || Easy To Understand || C++ Code | faster-easy-to-understand-c-code-by-__kr-unob | Using Hashmap\n\n Time Complexity :- O(N * Constant)\n\n Space Complexity :- O(Constant)\n\n\nclass Solution {\npublic:\n bool checkDistances(string str, vec | __KR_SHANU_IITG | NORMAL | 2022-09-04T05:07:47.976302+00:00 | 2022-09-04T05:07:47.976344+00:00 | 251 | false | * ***Using Hashmap***\n\n* ***Time Complexity :- O(N * Constant)***\n\n* ***Space Complexity :- O(Constant)***\n\n```\nclass Solution {\npublic:\n bool checkDistances(string str, vector<int>& distance) {\n \n int n = str.size();\n \n vector<int> dist(26, 0);\n \n for(char ch = \'a\'; ch <= \'z\'; ch++)\n {\n int first = -1;\n \n int second = -1;\n \n // find the first and last index of ch\n \n for(int i = 0; i < n; i++)\n {\n if(str[i] == ch && first == -1)\n {\n first = i;\n }\n else if(str[i] == ch && first != -1)\n {\n second = i;\n }\n }\n \n if(first != -1 && second != -1)\n {\n dist[ch - \'a\'] = abs(second - first) - 1;\n \n if(dist[ch - \'a\'] != distance[ch - \'a\'])\n return false;\n }\n }\n \n return true;\n }\n};\n``` | 2 | 0 | ['C', 'C++'] | 0 |
check-distances-between-same-letters | Two C++ Solutions | Linear Complexity | two-c-solutions-linear-complexity-by-tra-zyag | O(n) time, O(n) space, n = s.length\ncpp\nclass Solution {\npublic:\n bool checkDistances(string &s, vector<int> &dist) {\n unordered_map<char, vector | travanj05 | NORMAL | 2022-09-04T04:56:02.892537+00:00 | 2022-09-04T04:56:02.892571+00:00 | 140 | false | 1. O(n) time, O(n) space, n = s.length\n```cpp\nclass Solution {\npublic:\n bool checkDistances(string &s, vector<int> &dist) {\n unordered_map<char, vector<int>> mp;\n for (int i = 0; i < s.size(); i++) {\n mp[s[i]].push_back(i);\n }\n for (auto &[key, val] : mp) {\n if (dist[key - \'a\'] != abs(val[1] - val[0] - 1)) {\n return false;\n }\n }\n return true;\n }\n};\n```\n\n<br>\n\n2. O(n) time, O(1) space, n = s.length\n```cpp\nclass Solution {\npublic:\n bool checkDistances(string &s, vector<int> &dist) {\n int pos[26]{0};\n for (int i = 0; i < s.size(); ++i) {\n int n = s[i] - \'a\';\n if (pos[n] > 0 && dist[n] + pos[n] != i) {\n return false;\n }\n pos[n] = i + 1;\n }\n return true;\n }\n};\n```\n\nPlease do **upvote/share** if you like it. | 2 | 0 | ['Array', 'C', 'C++'] | 0 |
check-distances-between-same-letters | ✅C++ || ✅Easily Understandable || ✅Commented | c-easily-understandable-commented-by-may-f9y4 | \nclass Solution {\npublic:\n bool checkDistances(string s, vector<int>& distance) \n {\n int n = s.length();\n char tmp;\n \n | mayanksamadhiya12345 | NORMAL | 2022-09-04T04:00:35.653723+00:00 | 2022-09-04T04:06:08.959715+00:00 | 229 | false | ```\nclass Solution {\npublic:\n bool checkDistances(string s, vector<int>& distance) \n {\n int n = s.length();\n char tmp;\n \n for(int i=0;i<n;i++)\n {\n tmp = s[i]; // first occurance of letter\n for(int j=i+1;j<n;j++)\n {\n if(tmp==s[j]) // second occurance of letter\n {\n\t\t\t\t // if we don\'t have same diff then return false\n if((j-i-1)!=distance[tmp-\'a\']) return false;\n }\n }\n }\n return true;\n }\n};\n``` | 2 | 0 | [] | 0 |
check-distances-between-same-letters | Checking Distances Between Same Letters Using Hash Map | checking-distances-between-same-letters-4gro7 | IntuitionThe problem requires checking if the distance between the two occurrences of each letter in the string s matches the corresponding value in the distanc | x7Fg9_K2pLm4nQwR8sT3vYz5bDcE6h | NORMAL | 2025-03-13T12:36:04.848593+00:00 | 2025-03-13T12:36:04.848593+00:00 | 39 | false | # Intuition
The problem requires checking if the distance between the two occurrences of each letter in the string s matches the corresponding value in the distance array. My first thought was to use a hash map to store the indices of each letter in s and then compare the calculated distance with the given distance array.
# Approach
1. Store Indices of Letters: Use a hash map to store the indices of each letter in s. Since each letter appears exactly twice, the hash map will store a vector of two indices for each letter.
2. Calculate and Compare Distances: For each letter in the hash map, calculate the distance between its two occurrences and compare it with the corresponding value in the distance array.
3. Return Result: If all distances match, return true. Otherwise, return false.
# Complexity
- Time complexity: $$O(n)$$
- Space complexity: $$O(1)$$
# Code
```cpp []
class Solution {
public:
bool checkDistances(string s, vector<int>& distance) {
unordered_map <char,vector<int>> mp;
for (int i=0;i<s.size();i++){
mp[s[i]].push_back(i);
}
for (auto &it:mp){
if (distance[it.first-'a']!=it.second[1]-it.second[0]-1){
return false;
}
}
return true;
}
};
``` | 1 | 0 | ['C++'] | 0 |
check-distances-between-same-letters | 100% beats in c++ solution. | 100-beats-in-c-solution-by-jahidulcse15-26fs | IntuitionApproachComplexity
Time complexity:O(N)
Space complexity:O(N)
Code | jahidulcse15 | NORMAL | 2025-01-14T04:01:04.154203+00:00 | 2025-01-14T04:01:04.154203+00:00 | 83 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:O(N)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:O(N)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
bool checkDistances(string s, vector<int>& distance) {
map<char,int>cnt;
for(int i=s.size()-1;i>=0;i--){
cnt[s[i]]=i;
}
for(int i=0;i<s.size();i++){
if(cnt[s[i]]!=i){
int x=s[i]-97;
if(i-cnt[s[i]]-1!=distance[x]){
return false;
}
}
}
return true;
}
};
``` | 1 | 0 | ['C++'] | 0 |
check-distances-between-same-letters | c++ 100% beats solution. | c-100-beats-solution-by-jahidulcse15-f68e | IntuitionApproachComplexity
Time complexity:)(N*N)
Space complexity:O(1)
Code | jahidulcse15 | NORMAL | 2025-01-14T03:57:08.960839+00:00 | 2025-01-14T03:57:08.960839+00:00 | 55 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:)(N*N)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:O(1)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
bool checkDistances(string s, vector<int>& distance) {
for(int i=0;i<s.size();i++){
for(int j=i+1;j<s.size();j++){
if(s[i]==s[j]){
int x=s[i]-97;
if(j-i-1!=distance[x]){
return false;
}
else{
break;
}
}
}
}
return true;
}
};
``` | 1 | 0 | ['C++'] | 0 |
check-distances-between-same-letters | leetcodedaybyday - Beats 100% with C++ and Beats 100% with Python3 | leetcodedaybyday-beats-100-with-c-and-be-haqt | IntuitionThe problem requires checking if the distances between the first and second occurrences of each character in a string match the values provided in an a | tuanlong1106 | NORMAL | 2025-01-09T08:06:04.091536+00:00 | 2025-01-09T08:06:04.091536+00:00 | 75 | false | # Intuition
The problem requires checking if the distances between the first and second occurrences of each character in a string match the values provided in an array. By storing the index of the first occurrence and calculating the distance when encountering the character again, we can efficiently validate the condition.
# Approach
1. **Index Storage**:
- Use an array `idx` of size 26 (for each letter of the alphabet) initialized to `-1`.
- This array keeps track of the first occurrence of each character in the string.
2. **Iterate Through the String**:
- For each character in the string, compute its index relative to `'a'` to map it to the `idx` array.
- If the character's index in `idx` is `-1`, record its position.
- If it has already been recorded, calculate the distance between its first occurrence and the current position. Compare it with the corresponding value in the `distance` array.
3. **Return Result**:
- If all characters meet the required conditions, return `True`.
- If any character's distance does not match, return `False`.
# Complexity
- **Time Complexity**:
\(O(n)\), where \(n\) is the length of the string `s`. Each character is processed once.
- **Space Complexity**:
\(O(1)\), as the `idx` array is of fixed size (26) and no other significant data structures are used.
---
# Code
```cpp []
class Solution {
public:
bool checkDistances(string s, vector<int>& distance) {
vector<int> idx(26, -1);
for (int i = 0; i < s.length(); i++){
int chr = s[i] - 'a';
if (idx[chr] == -1){
idx[chr] = i;
} else {
int dist = i - idx[chr] - 1;
if (dist != distance[chr]){
return false;
}
}
}
return true;
}
};
```
```python3 []
class Solution:
def checkDistances(self, s: str, distance: List[int]) -> bool:
idx = [-1] * 26
for i in range(len(s)):
char = ord(s[i]) - ord('a')
if idx[char] == -1:
idx[char] = i
else :
dist = i - idx[char] - 1
if dist != distance[char]:
return False
return True
```
| 1 | 0 | ['Array', 'Hash Table', 'String', 'C++', 'Python3'] | 0 |
check-distances-between-same-letters | Simple solution using hashmap | simple-solution-using-hashmap-by-cs_2201-czzf | Complexity
Time complexity:O(n)
Space complexity:O(n)
Code | CS_2201640100153 | NORMAL | 2024-12-31T17:03:31.713682+00:00 | 2024-12-31T17:03:31.713682+00:00 | 93 | false | # Complexity
- Time complexity:O(n)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:O(n)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python3 []
class Solution:
def checkDistances(self, s: str, distance: List[int]) -> bool:
d={}
for i in range(len(s)):
if s[i] in d:
di=i-d[s[i]]-1
d[s[i]]=di
else:
d[s[i]]=i
for i,j in d.items():
if distance[ord(i)-97]!=j:
return False
return True
``` | 1 | 0 | ['Array', 'Hash Table', 'String', 'Python3'] | 0 |
check-distances-between-same-letters | Easy JAVA solution🔥🔥 || Using HashMap || Beginner friendly | easy-java-solution-using-hashmap-beginne-4hm2 | 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 | parthsitoot | NORMAL | 2024-10-17T13:40:24.000584+00:00 | 2024-10-17T13:40:24.000708+00:00 | 66 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public boolean checkDistances(String s, int[] distance) {\n Map<Character, Integer> map = new HashMap<>();\n Map<Integer, Character> ch = new HashMap<>();\n for(int i=0; i<s.length()-1; i++){\n int gap = 0;\n if(!map.containsKey(s.charAt(i))){\n for(int j=i+1; j<s.length(); j++){\n if(s.charAt(i) == s.charAt(j)){\n map.put(s.charAt(i), gap);\n break;\n }\n gap++;\n }\n }\n }\n \n int index = 0;\n for(char i=\'a\'; i<=\'z\'; i++){\n ch.put(index++, i);\n }\n System.out.println(ch);\n System.out.println(map);\n for(int i=0; i<distance.length; i++){\n if(distance[i] != map.getOrDefault(ch.get(i), distance[i])){\n return false; \n }\n }\n\n return true;\n }\n}\n``` | 1 | 0 | ['Java'] | 1 |
check-distances-between-same-letters | Easy Solution🔥🔥Beat 100% || Detailed Explanation✌️✌️ | easy-solutionbeat-100-detailed-explanati-v2bg | Intuition\nWe simply need to keep a track of the distance between the two occurrences of each character and then check if the string is a well-spaced string.\n\ | anshika_coder467 | NORMAL | 2024-08-03T13:34:59.648709+00:00 | 2024-08-03T13:34:59.648758+00:00 | 160 | false | # Intuition\nWe simply need to keep a track of the distance between the two occurrences of each character and then check if the string is a **well-spaced string**.\n\n# Approach\nHere, an unordered map is used to store the distance between the two occurrences of each character.\n\n- ***First For loop***\nWe store the index value of the character if it did not exist in the map.\nOtherwise, calculate the **distance** of the character from its previous index as --\n`D = Current_Index - Previous_Index - 1`\n- ***Second For loop***\nNow, we iterate through the map and check if the distance we calculated is equal to the corresponding value in the **distance** array for each character. \n\n **Concept of calculating index (0 - 25) for (\'a\' - \'z\')**\n - To calculate the corresponding index for the character, subtract \'a\' from it.\n - It would simply give the difference between the ASCII values of the current character.\n\n- If at any point the distance calculated is not same as the distance given, return false. Otherwise, return True.\n\n# Complexity\n- Time complexity: $$O(N)$$\n\n- Space complexity: $$O(N)$$\n\n# Code\n```\nclass Solution {\npublic:\n bool checkDistances(string s, vector<int>& distance) {\n unordered_map<char, int> m;\n for(int i = 0; i < s.size(); i++) {\n if(m.find(s[i]) == m.end()) m[s[i]] = i;\n else m[s[i]] = i - m[s[i]] - 1;\n\n }\n for(auto it : m) {\n if(distance[it.first - \'a\'] != it.second) return false; \n }\n return true;\n }\n};\n``` | 1 | 0 | ['C++'] | 1 |
check-distances-between-same-letters | Beats 100% users with C++ | Using Unordered Map in O(n) time. | beats-100-users-with-c-using-unordered-m-l3q5 | Intuition\n Describe your first thoughts on how to solve this problem. \n> The problem requires us to verify if the distances between the repeated characters in | ilokeshmewari | NORMAL | 2024-07-22T08:43:37.269235+00:00 | 2024-07-22T08:43:37.269266+00:00 | 1 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n> The problem requires us to verify if the distances between the repeated characters in a string match the values specified in a given array. Each letter in the alphabet appears exactly twice in the string, and we need to ensure that the distance between these occurrences for each letter matches the corresponding entry in the distance array. By storing the index of the first occurrence of each character and calculating the distance when the character is encountered again, we can efficiently check if the string meets the well-spaced criteria.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Initialize Data Structures: Create an unordered map to store the index of the first occurrence of each character.\n2. Iterate Through the String: Loop through the string, and for each character:\n - If the character has been encountered before, calculate the distance between its current and first occurrence, and compare it to the corresponding entry in the distance array.\n - If the distances do not match, return false.\n ```\n if (distance[s[i] - \'a\'] != (i - firstOcc[s[i]] - 1)){\n return false;\n }\n - If the character has not been encountered before, store its index in the map.\n3. Return Result: If all characters satisfy their distance requirements, return true\n\n# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution {\npublic:\n bool checkDistances(string s, vector<int>& distance) {\n unordered_map<char, int> firstOcc;\n for(int i = 0; i<s.length(); i++){\n if(firstOcc.find(s[i]) != firstOcc.end()){\n if(distance[s[i]-\'a\'] != (i - firstOcc[s[i]] - 1)){\n return false;\n }\n }\n else firstOcc[s[i]] = i;\n }\n return true;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
check-distances-between-same-letters | EASY HASHMAP | easy-hashmap-by-801121-rkk8 | Intuition\nWe need two hashmaps for this problem - one to keep track of the distances corresponding with the alphabet, and the other to find the distances betwe | 801121 | NORMAL | 2024-05-24T12:58:05.621931+00:00 | 2024-07-08T11:29:21.838615+00:00 | 102 | false | # Intuition\nWe need two hashmaps for this problem - one to keep track of the distances corresponding with the alphabet, and the other to find the distances between same letters. \n\n# Approach\nWe will fill the distances hashmap by simply setting the corresponding alphabet letter to the element in distances. \n\nI will then loop through the string s. If an element is not yet in hmap, it is a first occurence and we set hmap[char] to index. If char is in hmap, we check if its distance from the previously stored index is valid. If yes, we set hmap[char] to the current index and continue. If not, we return False; after the loop, we return True by default. \n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n\n\n# Code\n```\nclass Solution:\n def checkDistances(self, s: str, distance: List[int]) -> bool:\n distances, hmap = {}, {}\n for letter, num in zip([chr(i) for i in range(ord(\'a\'), ord(\'z\') + 1)], distance): \n distances[letter] = num \n for index, char in enumerate(s): \n if char not in hmap: \n hmap[char] = index\n continue \n if index - hmap[char] - 1 == distances[char]:\n hmap[char] = index\n else: \n return False\n return True \n\n \n\n``` | 1 | 0 | ['Python3'] | 0 |
check-distances-between-same-letters | use reduce to resolve this problem - 57ms - beats 100% | use-reduce-to-resolve-this-problem-57ms-0ex1c | Code\n\nfunction checkDistances(s: string, distance: number[]): boolean {\n let letter: number;\n const a = \'a\'.charCodeAt(0);\n return s.split(\'\').reduc | soemxui195 | NORMAL | 2024-05-03T13:06:23.754734+00:00 | 2024-05-03T13:06:23.754768+00:00 | 8 | false | # Code\n```\nfunction checkDistances(s: string, distance: number[]): boolean {\n let letter: number;\n const a = \'a\'.charCodeAt(0);\n return s.split(\'\').reduce((isDistance, char, idx) => {\n letter = s[idx].charCodeAt(0) - a;\n if(distance[letter] >= 0) {\n distance[letter] = - distance[letter] - idx - 1;\n }else {\n distance[letter] += idx;\n if (distance[letter] != 0) return false;\n }\n return isDistance;\n }, true);\n}\n``` | 1 | 0 | ['TypeScript'] | 0 |
check-distances-between-same-letters | Beat 100% CPP solution | beat-100-cpp-solution-by-adityashahi206-774k | Intuition\n Describe your first thoughts on how to solve this problem. \nused Hashmap \n\n# Approach\n Describe your approach to solving the problem. \n 1. c | adityashahi206 | NORMAL | 2024-02-18T05:47:49.153884+00:00 | 2024-02-18T05:47:49.153906+00:00 | 338 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nused Hashmap \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n 1. create one map which will store first appearance of character\'s index\n 2. if char already exist in map then we will calculate distance between then and compare it with distance[Actual char index a0,b1...z25]\n 3. if not equal the return false;\n 4. else traverse whole string and return true\n\n# Complexity\n- Time complexity:\n1.The function iterates through each character of the string \u2022s \u2022 once in the "for\' loop, resulting in a time complexity of O(n), where n is the length of the string\n2.Inside the loop, the operations involving the unordered map (\'first\') take constant time on average (amortized 0(1)) for insertion, lookup, and modification.\n\u2022 Therefore, the overall time complexity of the function is $$O(n)$$, where n is the length of the string\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)$$ -->\n1. as string contains only lower laters and we are storing only unique values so maximum size=26\nwhich is constant so $$O(1)$$.\n \n# Code\n```\nclass Solution {\npublic:\n bool checkDistances(string s, vector<int>& distance) {\n unordered_map<char,int>first;\n for(int i=0;i<s.size();i++)\n {\n if(first.find(s[i])!=first.end())\n {\n int dis=i-first[s[i]]-1;\n if(distance[s[i]-\'a\']!=dis)\n {\n return false;\n }\n\n }\n else\n {\n first[s[i]]=i;\n }\n }\n return true;\n }\n};\n``` | 1 | 0 | ['Hash Table', 'C++'] | 1 |
check-distances-between-same-letters | Java || Easy To Understand || With Explaination | java-easy-to-understand-with-explainatio-3k06 | Explanation:\n Describe your first thoughts on how to solve this problem. \n\n\n1. Two arrays, arr1 and arr2, are initialized to store the last and second last | akash_kce | NORMAL | 2024-02-01T04:54:02.836036+00:00 | 2024-02-01T04:54:02.836068+00:00 | 220 | false | # Explanation:\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n\n1. Two arrays, `arr1` and `arr2`, are initialized to store the last and second last occurrence indices of each character. These arrays are used to keep track of the positions of characters in the string.\n\n2. The input string `s` is traversed character by character. For each character:\n - If the character is encountered for the first time (`arr1[s.charAt(i) - \'a\'] == -1`), its index is stored in `arr1`.\n - If the character is encountered again, its index is stored in `arr2`.\n\n3. After traversing the entire string, the code checks the conditions for each character:\n - If the character is present (`arr1[i] != -1`) and the distance condition is not satisfied, it returns false.\n - The distance condition is `(arr2[i] - arr1[i]) + 1 != distance[i]`.\n\n4. If all characters satisfy the conditions, the function returns true.\n\nIn summary, the code checks if the distances between consecutive occurrences of characters match the specified distances in the `distance` array. If all characters satisfy the conditions, the function returns true; otherwise, it returns false.\n\n# Code\n```\nimport java.util.Arrays;\n\nclass Solution {\n public boolean checkDistances(String s, int[] distance) {\n int arr1[] = new int[26];\n Arrays.fill(arr1, -1);\n\n int arr2[] = new int[26];\n Arrays.fill(arr2, -1);\n\n for (int i = 0; i < s.length(); i++) {\n if (arr1[s.charAt(i) - \'a\'] == -1) {\n arr1[s.charAt(i) - \'a\'] = i;\n } else {\n arr2[s.charAt(i) - \'a\'] = i;\n }\n }\n\n for (int i = 0; i < 26; i++) {\n if (arr1[i] != -1 && (arr2[i] - arr1[i]) -1 != distance[i]) {\n return false;\n }\n }\n return true;\n }\n}\n\n``` | 1 | 0 | ['Array', 'String', 'Java'] | 1 |
check-distances-between-same-letters | Easiest Approach - Java (100% Beats) | easiest-approach-java-100-beats-by-talha-b9pp | Code\n\nclass Solution{\n public boolean checkDistances(String s, int[] distance){\n int[] ar1 = new int[26];\n Arrays.fill(ar1, -1);\n | talhah20343 | NORMAL | 2023-08-03T09:33:44.376858+00:00 | 2023-08-03T09:33:44.376888+00:00 | 784 | false | # Code\n```\nclass Solution{\n public boolean checkDistances(String s, int[] distance){\n int[] ar1 = new int[26];\n Arrays.fill(ar1, -1);\n int[] ar2 = new int[26];\n Arrays.fill(ar2, -1);\n for(int i=0; i<s.length(); i++){\n if(ar1[s.charAt(i)-\'a\']!=-1) ar2[s.charAt(i)-\'a\'] = i;\n else ar1[s.charAt(i)-\'a\'] = i;\n }\n for(int i=0; i<26; i++){\n if(ar1[i]!=-1 && ar2[i]-ar1[i]-1!=distance[i]) return false;\n }\n return true;\n \n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
check-distances-between-same-letters | Simple Dictionary C# Solution and Self Explanatory | simple-dictionary-c-solution-and-self-ex-yyfo | \n# Code\n\npublic class Solution {\n public bool CheckDistances(string s, int[] distance) {\n Dictionary<char, int> dc = new Dictionary<char, int>(); | hbti_ankit1994 | NORMAL | 2023-07-29T20:33:25.997717+00:00 | 2023-07-29T20:33:25.997746+00:00 | 52 | false | \n# Code\n```\npublic class Solution {\n public bool CheckDistances(string s, int[] distance) {\n Dictionary<char, int> dc = new Dictionary<char, int>();\n for(int i = 0 ; i < s.Length ; i++)\n {\n if(!dc.ContainsKey(s[i]))\n dc.Add(s[i], i);\n else\n dc[s[i]] = i - dc[s[i]] - 1;\n }\n\n for(int i = 0; i < 26 ; i++)\n {\n if(s.Contains((char)(i + \'a\')))\n {\n if(dc[(char)(i + \'a\')] != distance[i])\n return false;\n }\n }\n return true;\n }\n}\n``` | 1 | 0 | ['C#'] | 1 |
check-distances-between-same-letters | ✔✔✔💯% beats in runtime. Easy solution using loops. | beats-in-runtime-easy-solution-using-loo-kzda | 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 | hikmatulloanvarbekov001 | NORMAL | 2023-07-20T15:20:01.083420+00:00 | 2023-07-20T15:20:01.083442+00:00 | 2 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public boolean checkDistances(String s, int[] distance) {\n HashSet<Character> set = new HashSet<>();\n for(int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n int ind = 0;\n if(set.contains(c)) {\n continue;\n }\n for(int j = i+1; j < s.length(); j++){ \n if(s.charAt(j) == c) {\n ind = j;\n }\n }\n set.add(c);\n if(ind-i-1 != distance[c - \'a\']){ \n return false;\n }\n }\n // if it is helpful, upvote it pls.\n return true;\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
check-distances-between-same-letters | Simple Solution | simple-solution-by-gauravbisht2709-p0gw | 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 | gauravbisht2709 | NORMAL | 2023-04-22T18:59:35.977553+00:00 | 2023-04-22T18:59:35.977598+00:00 | 698 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def checkDistances(self, s: str, distance: List[int]) -> bool:\n d = s[::-1]\n if len(s)%2!=0:\n return False\n else:\n for i in s:\n #print((len(s)-d.index(i))-s.index(i)-1)\n if (len(s)-d.index(i)-1)-s.index(i)-1 != distance[ord(i)-ord(\'a\')]:\n return False\n return True\n\n``` | 1 | 0 | ['Math', 'String', 'Python3'] | 0 |
check-distances-between-same-letters | Check Distances Between Same Letters Solution in C++ | check-distances-between-same-letters-sol-byk5 | 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 | The_Kunal_Singh | NORMAL | 2023-03-22T07:59:54.335527+00:00 | 2023-03-22T07:59:54.335559+00:00 | 30 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n^2)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n# Code\n```\nclass Solution {\npublic:\n bool checkDistances(string s, vector<int>& distance) {\n int i, j, d, flag=0, k;\n for(i=0 ; i<s.length() ; i++)\n {\n for(j=i+1 ; j<s.length() ; j++)\n {\n if(s[i]==s[j])\n {\n d = j-i-1;\n k = (int)s[i]-97;\n if(distance[k]!=d)\n {\n return false;\n }\n break;\n }\n }\n }\n return true;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
check-distances-between-same-letters | EASY | WITHOUT HASHMAP | 5 Lines of Code | O(1) | C++ | easy-without-hashmap-5-lines-of-code-o1-kdbwo | 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 | shivansh_07 | NORMAL | 2023-02-25T09:02:26.733735+00:00 | 2023-02-25T09:02:26.733773+00:00 | 11 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n\n\n bool checkDistances(string s, vector<int>& distance) {\n \n\n for(int i = 0; i < s.size();i++){\n\n for(int j = i+1 ; j < s.size();j++){\n\n if(s[i] == s[j]){\n\n if(distance[s[i] - 97] != (j-i-1)){\n return false;\n }\n }\n\n \n }\n }\n\n return true;\n\n \n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
check-distances-between-same-letters | HashMap full Approach Explained || Java | hashmap-full-approach-explained-java-by-48syy | Check Distances Between Same Letters\n# Approach:*\n1.) We iterate over the String and create a hashmap\n2.) While iterating if the character is not in hashmap, | pushprajdubey | NORMAL | 2023-01-25T18:11:37.164533+00:00 | 2023-01-25T18:11:37.164583+00:00 | 34 | false | # **Check Distances Between Same Letters\n# ***Approach:*****\n1.) We iterate over the String and create a hashmap\n2.) While iterating if the character is not in hashmap, we put it in hashmap\n3.) If character is in hashmap we compute the number of letter between the two occurences by cuurIndex-ma.get(char)-1 and check if this matche with distance provided in the array\n\n# ***Time Complexity:** O(n)*\n\n# Code\n```\nclass Solution {\n public boolean checkDistances(String s, int[] distance) {\n HashMap<Character, Integer> map=new HashMap<Character, Integer>();\n for(int i=0; i<s.length(); i++){\n if(!map.containsKey(s.charAt(i))){\n map.put(s.charAt(i), i);\n }\n // Updating the distnace between the current and previous occourence of key if it contains it \n else{\n int prev = map.get(s.charAt(i));\n int index = s.charAt(i)-\'a\';\n // Checking is the computed distance matches with provided distance\n if(distance[index]!=i-prev-1){\n return false;\n }\n }\n }\n return true;\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.