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
length-of-longest-v-shaped-diagonal-segment
Longest V-Shaped Diagonal Path in a Grid
longest-v-shaped-diagonal-path-in-a-grid-u02x
IntuitionBrute force with dp optimizationApproachWe start at every cell with value 1 and explore in all four diagonal directions, following an alternating patte
Giri_27
NORMAL
2025-02-17T07:47:50.719758+00:00
2025-02-17T07:47:50.719758+00:00
8
false
# Intuition Brute force with dp optimization <!-- Describe your first thoughts on how to solve this problem. --> # Approach We start at every cell with value 1 and explore in all four diagonal directions, following an alternating pattern between 2 and 0—allowing one change in direction—to find the longest valid V-shaped diagonal path using dynamic programming for efficiency. <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: - O(n * m * 2 * 4) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: - O(n * m * 2 * 4) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: int lenOfVDiagonal(vector<vector<int>>& grid) { int n = grid.size(), m = grid[0].size(); auto next = [&](int i, int j, int dir) -> array<int, 2> { int ni = i, nj = j; if(dir == 0) ni--, nj--; else if(dir == 1) ni--, nj++; else if(dir == 2) ni++, nj++; else ni++, nj--; return {ni, nj}; }; auto valid = [&](int i, int j) -> bool { return (i >= 0 and j >= 0 and i < n and j < m); }; auto condition = [&](int i, int j, int ni, int nj) -> bool { return (grid[i][j] == 2 and grid[ni][nj] == 0) or (grid[i][j] == 0 and grid[ni][nj] == 2); }; int dp[n][m][4][2]; memset(dp, -1, sizeof(dp)); auto f = [&](int i, int j, int dir, int done, auto&& f) -> int { if(dp[i][j][dir][done] != -1) return dp[i][j][dir][done]; auto [ni, nj] = next(i, j, dir); int cur = 0; if(valid(ni, nj)) { if(condition(i, j, ni, nj)) cur = 1 + f(ni, nj, dir, done, f); } int chg = 0; if(done == 0) { int k = (dir + 1) % 4; auto [ni, nj] = next(i, j, k); if(valid(ni, nj) and condition(i, j, ni, nj)) chg = 1 + f(ni, nj, k, 1, f); } return dp[i][j][dir][done] = max(cur, chg); }; int res = 0; for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { if(grid[i][j] != 1) continue; res = max(res, 1); for(int dir = 0; dir < 4; dir++) { auto [ni, nj] = next(i, j, dir); if(valid(ni, nj) and grid[ni][nj] == 2) { res = max(res, 2 + f(ni, nj, dir, 0, f)); } } } } return res; } }; ```
0
0
['C++']
0
length-of-longest-v-shaped-diagonal-segment
Simple || Beginner Friendly || DP
simple-beginner-friendly-dp-by-_phoenix_-2wxb
ApproachComplexity Time complexity: O(N*M) Space complexity: O(N*M) Code
_Phoenix_14
NORMAL
2025-02-17T05:13:48.376761+00:00
2025-02-17T05:13:48.376761+00:00
8
false
# Approach 1) Used dp(i,j,currectDirection,turnPossible) 2) Grid[ni][nj] == abs(grid[i][j]-2) to maintain the sequence 2,0,2,0... & switched 1s' to 0's before recursion to maintain the condition 3) Tried all possibilities -> 1)Maintain the same direction , 2) Turn clockwise and continue finding max length # Complexity - Time complexity: O(N*M) - Space complexity: O(N*M) # Code ```cpp [] class Solution { public: int dir[4][2] = {{-1, -1}, {-1, 1}, {1, 1}, {1, -1}}; bool check(int i, int j, int n, int m) { return (i >= 0 && j >= 0 && i < n && j < m); } int f(int i, int j, int d, int turn, vector<vector<vector<vector<int>>>> &dp, vector<vector<int>> &grid, int n, int m) { if (dp[i][j][d][turn] != -1) return dp[i][j][d][turn]; int maxi = 0; int ni = i + dir[d][0], nj = j + dir[d][1]; if (check(ni, nj, n, m) && grid[ni][nj] == abs(grid[i][j] - 2)) maxi = max(maxi, 1 + f(ni, nj, d, turn, dp, grid, n, m)); if (!turn) { int d0 = (d + 1) % 4; int ni0 = i + dir[d0][0], nj0 = j + dir[d0][1]; if (check(ni0, nj0, n, m) && grid[ni0][nj0] == abs(grid[i][j] - 2)) maxi = max(maxi, 1 + f(ni0, nj0, d0, 1, dp, grid, n, m)); } return dp[i][j][d][turn] = maxi; } int lenOfVDiagonal(vector<vector<int>> &grid) { int n = grid.size(); int m = grid[0].size(); int ans = 0, cnt = 0; vector<vector<vector<vector<int>>>> dp(n, vector<vector<vector<int>>>(m, vector<vector<int>>(4, vector<int>(2, -1)))); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (grid[i][j] == 1) { cnt++; for (int d = 0; d < 4; d++) { grid[i][j] = 0; ans = max(ans, f(i, j, d, 0, dp, grid, n, m)); grid[i][j] = 1; } } } } return (!cnt) ? 0 : ans + 1; } }; ```
0
0
['C++']
0
length-of-longest-v-shaped-diagonal-segment
DP Memoisation : Clear explaination with choices | BEATS 100%
dp-memoisation-clear-explaination-with-c-8r6m
IntuitionApproachfor ever '1' in the grid call this function :if(grid == 1)elseOptimisation :pre-compute the diagonal length of sequence 020202... or 2020202...
SaumyaVyas
NORMAL
2025-02-16T19:56:26.093596+00:00
2025-02-16T19:56:26.093596+00:00
57
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach for ever '1' in the grid call this function : if(grid == 1) explore all four direction, find which one gives best result else two options : 1) keep moving in same direction 2) take a turn return which ever gives max answer Optimisation : pre-compute the diagonal length of sequence 020202... or 2020202... for every cell in all four direction, use these values when you take turn. when taking a turn, just get the precomputed value from dp array depending upon direction and return it # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { //bottomleft, upleft, upright, bottomright int direction[] = {0,1,2,3}; int drr[] = {1,-1,-1,1}; int drc[] = {-1,-1,1,1}; int[][] grid; int[][][] dp; //precompute diagonal lengths int[][][] memo; int n,m; public int lenOfVDiagonal(int[][] grid) { //initialisation this.grid = grid; n = grid.length; m = grid[0].length; dp = new int[n][m][5]; memo = new int[n][m][5]; //initialisation for(int i=0 ; i<n ; i++){ for(int j=0 ; j<m ; j++){ Arrays.fill(memo[i][j], -1); if(grid[i][j] != 1){ Arrays.fill(dp[i][j], 1); } } } //up-left for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if(i==0 || j==0){ dp[i][j][1] = grid[i][j] != 1 ? 1 : 0; } else if(grid[i][j] != 1 && grid[i - 1][j - 1] != 1 && grid[i - 1][j - 1] != grid[i][j]) { dp[i][j][1] = dp[i - 1][j - 1][1] + 1; } } } //bottom-right for (int i = n - 1; i >= 0; i--) { for (int j = m - 1; j >= 0; j--) { if(i==n-1 || j==m-1){ dp[i][j][3] = grid[i][j] != 1 ? 1 : 0; } else if (grid[i][j] != 1 && grid[i + 1][j + 1] != 1 && grid[i + 1][j + 1] != grid[i][j]) { dp[i][j][3] = dp[i + 1][j + 1][3] + 1; } } } //bottom left for (int i = n - 1; i >= 0; i--) { for (int j = 0; j < m; j++) { if(i==n-1 || j==0){ dp[i][j][0] = grid[i][j] != 1 ? 1 : 0; } else if (grid[i][j] != 1 && grid[i + 1][j - 1] != 1 && grid[i + 1][j - 1] != grid[i][j]) { dp[i][j][0] = dp[i + 1][j - 1][0] + 1; } } } //up-right for (int i = 0; i < n; i++) { for (int j = m - 1; j >= 0; j--) { if(i==0 || j==m-1){ dp[i][j][2] = grid[i][j] != 1 ? 1 : 0; } else if (grid[i][j] != 1 && grid[i - 1][j + 1] != 1 && grid[i - 1][j + 1] != grid[i][j]) { dp[i][j][2] = dp[i - 1][j + 1][2] + 1; } } } //function call for every '1' int ans = 0; for(int i=0 ; i<n ; i++){ for(int j=0; j<m ; j++){ if(grid[i][j] == 1){ ans = Math.max(ans, fun(i, j, 4)); } } } return ans ; } int fun(int r, int c, int drx){ //base case if(basecase(r,c,drx)){ return 0; } if(memo[r][c][drx] != -1) return memo[r][c][drx]; //if current cell = 1,(just started) 4 directional choices //drx == 4 represents just started and no direction is selected yet if(drx == 4){ int ans = 0; for(int i=0 ; i<4 ; i++){ int newr = r + drr[i]; int newc = c + drc[i]; if(isValid(newr, newc) && grid[newr][newc] == 2){ ans = Math.max(ans, fun(newr, newc, direction[i])); } } return memo[r][c][drx] = ans+1; } //take turn int ans1 = 0; int newdrx = (drx+1)%4; int newr = r + drr[newdrx]; int newc = c + drc[newdrx]; if(isValid(newr, newc) && grid[newr][newc] != 1 && grid[newr][newc] != grid[r][c]){ ans1 = dp[r][c][newdrx]; } //keep moving in same direction int ans2 = 0; int newrr = r + drr[drx]; int newcc = c + drc[drx]; if(isValid(newrr, newcc) && grid[newrr][newcc] != 1 && grid[newrr][newcc] != grid[r][c]){ ans2 = Math.max(ans2, fun(newrr, newcc, drx)); } ans2++; return memo[r][c][drx] = Math.max(ans1, ans2); } public boolean isValid(int x, int y){ return x>=0 && x<n && y>=0 && y<m; } public boolean basecase(int r, int c, int drx){ if(drx == 0){ if(r >= n || c<0) return true; }else if(drx == 1){ if(r <0 || c<0) return true; }else if(drx == 2){ if(r<0 || c>=m) return true; }else if(drx == 3){ if(r >= n || c >= m) return true; } return false; } } ```
0
0
['Dynamic Programming', 'Memoization', 'Java']
0
length-of-longest-v-shaped-diagonal-segment
Easy Brute Force C++ Solution with noturn and turn MEMO
easy-brute-force-c-solution-with-noturn-9717s
IntuitionWe use the noturn vector to record the maximum distance traveled in a single direction. And use the turn vector to record the maximum distance with tur
william6715
NORMAL
2025-02-16T18:56:31.180478+00:00
2025-02-16T18:56:31.180478+00:00
10
false
# Intuition We use the **noturn** vector to record the maximum distance traveled in a single direction. And use the **turn** vector to record the maximum distance with turning once. # Approach First, record the maximum possible distance that can be traveled from each position in the DIR direction into noturn[dir][r][c]. Next, for each position in turn[dir][r][c], we have two choice. 1. Get the maximum distance that can be traveled by moving in the DIR direction and at most turning once 2. Get the maximum distance that can be traveled by moving in the **(DIR+1)** direction without turning. (It means we turn the direction at (r,c).) Store the larger one into turn[dir][r][c]. Finally, for each grid cell with a value of 1, we check the turn vector values in all four directions. And also check if the value is 2. # Complexity - Time complexity: O(mn) - Space complexity: O(mn) # Code ```cpp [] class Solution { vector<pair<int, int>> dir = {{1,1},{1,-1},{-1,-1},{-1,1}}; int res = 0; public: int lenOfVDiagonal(vector<vector<int>>& grid) { int row = grid.size(); int col = grid[0].size(); vector<vector<vector<int>>> noturn(4, vector<vector<int>>(row, vector<int>(col))); vector<vector<vector<int>>> turn(4, vector<vector<int>>(row, vector<int>(col))); for(int c=0; c<col; ++c){ noturn[0][row-1][c] = 1; noturn[1][row-1][c] = 1; noturn[2][0][c] = 1; noturn[3][0][c] = 1; turn[0][row-1][c] = 1; turn[2][0][c] = 1; } // For noturn dir 2, 3 for(int r=1; r<row; ++r){ for(int c=0; c<col; ++c){ // for 2 LU int prev = (c == 0) ? 0 : noturn[2][r-1][c-1]; // prevLen int val = (c == 0) ? 1 : grid[r-1][c-1]; // prev grid if(2 - val == grid[r][c]){ noturn[2][r][c] = prev + 1; } else { noturn[2][r][c] = 1; } // for 3 RU prev = (c == col-1) ? 0 : noturn[3][r-1][c+1]; val = (c == col-1) ? 1 : grid[r-1][c+1]; if(2 - val == grid[r][c]){ noturn[3][r][c] = prev + 1; } else { noturn[3][r][c] = 1; } } } // For noturn dir 0,1 for(int r=row-2; r>=0; --r){ for(int c=0; c<col; ++c){ // for 1 LD int prev = (c == 0) ? 0 : noturn[1][r+1][c-1]; // prevLen int val = (c == 0) ? 1 : grid[r+1][c-1]; // prev grid if(2 - val == grid[r][c]){ noturn[1][r][c] = prev + 1; } else { noturn[1][r][c] = 1; } // for 0 RD prev = (c == col-1) ? 0 : noturn[0][r+1][c+1]; // prevLen val = (c == col-1) ? 1 : grid[r+1][c+1]; // prev grid if(2 - val == grid[r][c]){ noturn[0][r][c] = prev + 1; } else { noturn[0][r][c] = 1; } } } // For turn at most 1 // For turn dir 2 (3) for(int r=1; r<row; ++r){ for(int c=0; c<col; ++c){ // for 2 LU int prev = (c == 0) ? 0 : turn[2][r-1][c-1]; // prevLen int val = (c == 0) ? 1 : grid[r-1][c-1]; // prev grid if(2 - val == grid[r][c]){ turn[2][r][c] = prev + 1; } else { turn[2][r][c] = 1; } prev = (c == col-1) ? 0 : noturn[3][r-1][c+1]; // prevLen val = (c == col-1) ? 1 : grid[r-1][c+1]; if(2 - val == grid[r][c]){ turn[2][r][c] = max(prev + 1, turn[2][r][c]); } } } // For turn dir 0 (1) for(int r=row-2; r>=0; --r){ for(int c=0; c<col; ++c){ // for 0 RD int prev = (c == col-1) ? 0 : turn[0][r+1][c+1]; // prevLen int val = (c == col-1) ? 1 : grid[r+1][c+1]; // prev grid if(2 - val == grid[r][c]){ turn[0][r][c] = prev + 1; } else { turn[0][r][c] = 1; } // for dir 1 prev = (c == 0) ? 0 : noturn[1][r+1][c-1]; // prevLen val = (c == 0) ? 1 : grid[r+1][c-1]; if(2 - val == grid[r][c]){ turn[0][r][c] = max(prev + 1, turn[0][r][c]); } } } // For turn dir 3 (0) for(int r=0; r<row; ++r){ for(int c=0; c<col; ++c){ // for 3 RU if(r != 0){ int prev = (c == col-1) ? 0 : turn[3][r-1][c+1]; // prevLen int val = (c == col-1) ? 1 : grid[r-1][c+1]; // prev grid if(2 - val == grid[r][c]){ turn[3][r][c] = prev + 1; } else { turn[3][r][c] = 1; } } else { turn[3][r][c] = 1; } // from turn 0 if(r != row-1){ int prev = (c == col-1) ? 0 : noturn[0][r+1][c+1]; // prevLen int val = (c == col-1) ? 1 : grid[r+1][c+1]; // prev grid if(2 - val == grid[r][c]){ turn[3][r][c] = max(prev + 1, turn[3][r][c]); } } } } // For turn dir 1 (2) for(int r=row-1; r>=0; --r){ for(int c=0; c<col; ++c){ // for 1 LD if(r != row-1){ int prev = (c == 0) ? 0 : turn[1][r+1][c-1]; // prevLen int val = (c == 0) ? 1 : grid[r+1][c-1]; // prev grid if(2 - val == grid[r][c]){ turn[1][r][c] = prev + 1; } else { turn[1][r][c] = 1; } } else { turn[1][r][c] = 1; } // from turn 2 if(r != 0){ int prev = (c == 0) ? 0 : noturn[2][r-1][c-1]; // prevLen int val = (c == 0) ? 1 : grid[r-1][c-1]; // prev grid if(2 - val == grid[r][c]){ turn[1][r][c] = max(prev + 1, turn[1][r][c]); } } } } // Final stage for(int r=0; r<row; ++r){ for(int c=0; c<col; ++c){ if(grid[r][c] == 1){ res = max(res, 1); for(int i=0; i<4; ++i){ int newr = r + dir[i].first; int newc = c + dir[i].second; if(newr >= 0 && newr < row && newc >= 0 && newc < col && grid[newr][newc] == 2){ res = max(res, turn[i][newr][newc] + 1); } } } } } return res; } }; ```
0
0
['C++']
0
length-of-longest-v-shaped-diagonal-segment
DP DFS tracking process beats 100%
dp-dfs-tracking-process-beats-100-by-luu-qscp
Intuition DP - DFS tracking process Approach Using ck := make([][][4]int, len(grid)) caching data Index 0 top left, 1 top right, 2 bottom right, 3 bottom left
luudanhhieu
NORMAL
2025-02-16T16:01:58.187906+00:00
2025-02-16T16:01:58.187906+00:00
8
false
# Intuition - DP - DFS tracking process # Approach - Using `ck := make([][][4]int, len(grid))` caching data - Index `0 top left, 1 top right, 2 bottom right, 3 bottom left` - Start with any point `grid[i][j] = 1` and try to calculate from all direction. - Get result for `index i` - Get stack for each direction `top left,top right, bottom right, bottom left`` - Each point of stack get crossing direction and caching data to `ck` - Top left -> Top right and Bottom left (TL -> TR, BL) - TR -> TL, BR - BR -> TR, BL - BL -> TL, BR - Get result for `index i` - Caching data for all direction start from i -> easily if another position cross these point. # Complexity - Time complexity: O(n*n) - Space complexity:O(n) # Code ```golang [] func lenOfVDiagonal(grid [][]int) int { ck := make([][][4]int, len(grid)) for i := range ck { ck[i] = make([][4]int, len(grid[0])) for j := range ck[i] { ck[i][j][0], ck[i][j][1], ck[i][j][2], ck[i][j][3] = -1, -1, -1, -1 } } var rs int //TL 1 TR 2 BL 3 BR 4 for i := 0; i < len(grid); i++ { for j := 0; j < len(grid[0]); j++ { if grid[i][j] == 1 { rs = max(rs, 1) //TL if i > 0 && j > 0 && grid[i-1][j-1] == 2 { stackQ := [][2]int{{i - 1, j - 1}} ii, jj := stackQ[len(stackQ)-1][0], stackQ[len(stackQ)-1][1] for ii > 0 && jj > 0 && grid[ii-1][jj-1]+grid[ii][jj] == 2 { stackQ = append(stackQ, [2]int{ii - 1, jj - 1}) ii-- jj-- } rs = max(rs, len(stackQ)+1) for si := 0; si < len(stackQ); si++ { ck[stackQ[si][0]][stackQ[si][1]][0] = len(stackQ) - 1 - si ck[stackQ[si][0]][stackQ[si][1]][2] = si stackQTr := [][2]int{} stackQBl := [][2]int{} //TR tr := ck[stackQ[si][0]][stackQ[si][1]][1] if tr == -1 { il, jl := stackQ[si][0], stackQ[si][1] for il > 0 && jl < len(grid[0])-1 && grid[il-1][jl+1]+grid[il][jl] == 2 { stackQTr = append(stackQTr, [2]int{il - 1, jl + 1}) il-- jl++ } ck[stackQ[si][0]][stackQ[si][1]][1] = len(stackQTr) tr = len(stackQTr) } rs = max(rs, tr+si+1+1) //BL bl := ck[stackQ[si][0]][stackQ[si][1]][3] if bl == -1 { il, jl := stackQ[si][0], stackQ[si][1] for il < len(grid)-1 && jl > 0 && grid[il+1][jl-1]+grid[il][jl] == 2 { stackQBl = append(stackQBl, [2]int{il + 1, jl - 1}) il++ jl-- } ck[stackQ[si][0]][stackQ[si][1]][3] = len(stackQBl) bl = len(stackQBl) } // add cache for bli := 0; bli < len(stackQBl); bli++ { ck[stackQBl[bli][0]][stackQBl[bli][1]][1] = bli + 1 + tr ck[stackQBl[bli][0]][stackQBl[bli][1]][3] = len(stackQBl) - 1 - bli } for tri := 0; tri < len(stackQTr); tri++ { ck[stackQTr[tri][0]][stackQTr[tri][1]][3] = tri + 1 + bl ck[stackQTr[tri][0]][stackQTr[tri][1]][1] = len(stackQTr) - 1 - tri } } } //BR if i+1 < len(grid) && j+1 < len(grid[0]) && grid[i+1][j+1] == 2 { stackQ := [][2]int{{i + 1, j + 1}} ii, jj := stackQ[len(stackQ)-1][0], stackQ[len(stackQ)-1][1] for ii+1 < len(grid) && jj+1 < len(grid[0]) && grid[ii+1][jj+1]+grid[ii][jj] == 2 { stackQ = append(stackQ, [2]int{ii + 1, jj + 1}) ii++ jj++ } rs = max(rs, len(stackQ)+1) for si := 0; si < len(stackQ); si++ { ck[stackQ[si][0]][stackQ[si][1]][2] = len(stackQ) - 1 - si ck[stackQ[si][0]][stackQ[si][1]][0] = si //TR stackQTr := [][2]int{} stackQBl := [][2]int{} tr := ck[stackQ[si][0]][stackQ[si][1]][1] if tr == -1 { il, jl := stackQ[si][0], stackQ[si][1] for il > 0 && jl < len(grid[0])-1 && grid[il-1][jl+1]+grid[il][jl] == 2 { stackQTr = append(stackQTr, [2]int{il - 1, jl + 1}) il-- jl++ } ck[stackQ[si][0]][stackQ[si][1]][1] = len(stackQTr) tr = len(stackQTr) } //BL bl := ck[stackQ[si][0]][stackQ[si][1]][3] if bl == -1 { il, jl := stackQ[si][0], stackQ[si][1] for il < len(grid)-1 && jl > 0 && grid[il+1][jl-1]+grid[il][jl] == 2 { stackQBl = append(stackQBl, [2]int{il + 1, jl - 1}) il++ jl-- } ck[stackQ[si][0]][stackQ[si][1]][3] = len(stackQBl) bl = len(stackQBl) } rs = max(rs, bl+si+1+1) //add cache for bli := 0; bli < len(stackQBl); bli++ { ck[stackQBl[bli][0]][stackQBl[bli][1]][1] = bli + 1 + tr ck[stackQBl[bli][0]][stackQBl[bli][1]][3] = len(stackQBl) - 1 - bli } for tri := 0; tri < len(stackQTr); tri++ { ck[stackQTr[tri][0]][stackQTr[tri][1]][3] = tri + 1 + bl ck[stackQTr[tri][0]][stackQTr[tri][1]][1] = len(stackQTr) - 1 - tri } } } //TR if i > 0 && j+1 < len(grid[0]) && grid[i-1][j+1] == 2 { stackQ := [][2]int{{i - 1, j + 1}} ii, jj := stackQ[len(stackQ)-1][0], stackQ[len(stackQ)-1][1] for ii > 0 && jj+1 < len(grid[0]) && grid[ii-1][jj+1]+grid[ii][jj] == 2 { stackQ = append(stackQ, [2]int{ii - 1, jj + 1}) ii-- jj++ } rs = max(rs, len(stackQ)+1) for si := 0; si < len(stackQ); si++ { ck[stackQ[si][0]][stackQ[si][1]][1] = len(stackQ) - 1 - si ck[stackQ[si][0]][stackQ[si][1]][3] = si //TL stackQTl := [][2]int{} stackQBr := [][2]int{} tl := ck[stackQ[si][0]][stackQ[si][1]][0] if tl == -1 { il, jl := stackQ[si][0], stackQ[si][1] for il > 0 && jl > 0 && grid[il-1][jl-1]+grid[il][jl] == 2 { stackQTl = append(stackQTl, [2]int{il - 1, jl - 1}) il-- jl-- } ck[stackQ[si][0]][stackQ[si][1]][0] = len(stackQTl) tl = len(stackQTl) } //BR br := ck[stackQ[si][0]][stackQ[si][1]][2] if br == -1 { il, jl := stackQ[si][0], stackQ[si][1] for il < len(grid)-1 && jl < len(grid[0])-1 && grid[il+1][jl+1]+grid[il][jl] == 2 { stackQBr = append(stackQBr, [2]int{il + 1, jl + 1}) il++ jl++ } ck[stackQ[si][0]][stackQ[si][1]][2] = len(stackQBr) br = len(stackQBr) } rs = max(rs, br+si+1+1) //add cache for bli := 0; bli < len(stackQTl); bli++ { ck[stackQTl[bli][0]][stackQTl[bli][1]][2] = bli + 1 + br ck[stackQTl[bli][0]][stackQTl[bli][1]][0] = len(stackQTl) - 1 - bli } for tri := 0; tri < len(stackQBr); tri++ { ck[stackQBr[tri][0]][stackQBr[tri][1]][0] = tri + 1 + tl ck[stackQBr[tri][0]][stackQBr[tri][1]][2] = len(stackQBr) - 1 - tri } } } //BL if i+1 < len(grid) && j > 0 && grid[i+1][j-1] == 2 { stackQ := [][2]int{{i + 1, j - 1}} ii, jj := stackQ[len(stackQ)-1][0], stackQ[len(stackQ)-1][1] for ii+1 < len(grid) && jj > 0 && grid[ii+1][jj-1]+grid[ii][jj] == 2 { stackQ = append(stackQ, [2]int{ii + 1, jj - 1}) ii++ jj-- } rs = max(rs, len(stackQ)+1) for si := 0; si < len(stackQ); si++ { ck[stackQ[si][0]][stackQ[si][1]][3] = len(stackQ) - 1 - si ck[stackQ[si][0]][stackQ[si][1]][1] = si //TL stackQTl := [][2]int{} stackQBr := [][2]int{} tl := ck[stackQ[si][0]][stackQ[si][1]][0] if tl == -1 { il, jl := stackQ[si][0], stackQ[si][1] for il > 0 && jl > 0 && grid[il-1][jl-1]+grid[il][jl] == 2 { stackQTl = append(stackQTl, [2]int{il - 1, jl - 1}) il-- jl-- } ck[stackQ[si][0]][stackQ[si][1]][0] = len(stackQTl) tl = len(stackQTl) } rs = max(rs, tl+si+1+1) //BR br := ck[stackQ[si][0]][stackQ[si][1]][2] if br == -1 { il, jl := stackQ[si][0], stackQ[si][1] for il < len(grid)-1 && jl < len(grid[0])-1 && grid[il+1][jl+1]+grid[il][jl] == 2 { stackQBr = append(stackQBr, [2]int{il + 1, jl + 1}) il++ jl++ } ck[stackQ[si][0]][stackQ[si][1]][2] = len(stackQBr) br = len(stackQBr) } //add cache for bli := 0; bli < len(stackQTl); bli++ { ck[stackQTl[bli][0]][stackQTl[bli][1]][2] = bli + 1 + br ck[stackQTl[bli][0]][stackQTl[bli][1]][0] = len(stackQTl) - 1 - bli } for tri := 0; tri < len(stackQBr); tri++ { ck[stackQBr[tri][0]][stackQBr[tri][1]][0] = tri + 1 + tl ck[stackQBr[tri][0]][stackQBr[tri][1]][2] = len(stackQBr) - 1 - tri } } } } } } return rs } ```
0
0
['Go']
0
length-of-longest-v-shaped-diagonal-segment
Python Hard
python-hard-by-lucasschnee-udlp
null
lucasschnee
NORMAL
2025-02-16T15:10:59.322216+00:00
2025-02-16T15:10:59.322216+00:00
25
false
```python3 [] class Solution: def lenOfVDiagonal(self, grid: List[List[int]]) -> int: M, N = len(grid), len(grid[0]) directions = [(1, 1), (1, -1), (-1, -1), (-1, 1)] @cache def calc(i, j, prev, diag_index, used): best = 0 if used == 0: best = max(best, calc(i, j, prev, (diag_index + 1) % 4, 1)) dx, dy = directions[diag_index] nx, ny = i + dx, j + dy if not (0 <= nx < M) or not (0 <= ny < N): return best if prev == 0: if grid[nx][ny] != 2: return best best = max(best, calc(nx, ny, 2, diag_index, used) + 1) if prev == 2: if grid[nx][ny] != 0: return best best = max(best, calc(nx, ny, 0, diag_index, used) + 1) return best best = 0 for i in range(M): for j in range(N): if grid[i][j] == 1: for ii in range(4): best = max(best, calc(i, j, 0, ii, 0)+1) calc.cache_clear() return best ```
0
0
['Python3']
0
length-of-longest-v-shaped-diagonal-segment
python3 dp
python3-dp-by-maxorgus-65km
Code
MaxOrgus
NORMAL
2025-02-16T11:59:30.507219+00:00
2025-02-16T11:59:30.507219+00:00
23
false
# Code ```python3 [] class Solution: def lenOfVDiagonal(self, grid: List[List[int]]) -> int: M = len(grid) N = len(grid[0]) turned = {(1,1):(1,-1),(1,-1):(-1,-1),(-1,-1):(-1,1),(-1,1):(1,1)} @cache def dp(i,j,d,turn): if i<0 or i>=M or j<0 or j>=N: return 0 res = 1 di,dj = i+d[0],j+d[1] v = grid[i][j] if 0<=di<M and 0<=dj<N: newv = grid[di][dj] if (v == 1 and newv == 2) or tuple(sorted([newv,v]))==(0,2): res = max(res,1+dp(di,dj,d,turn)) else: res = max(res,1+dp(di,dj,d,turn)) if not turn: newd = turned[d] ddi,ddj = i+newd[0],j+newd[1] if 0<=ddi<M and 0<=ddj<N: newv = grid[ddi][ddj] #print(i,j,'turn',v,newv,) if (v == 1 and newv == 2) or tuple(sorted([newv,v]))==(0,2): res = max(res,1+dp(ddi,ddj,newd,True)) else: res = max(res,1+dp(ddi,ddj,newd,True)) return res res = 0 for i in range(M): for j in range(N): if grid[i][j] == 1: for d in turned: res = max(dp(i,j,d,False),res) return res ```
0
0
['Dynamic Programming', 'Python3']
0
length-of-longest-v-shaped-diagonal-segment
Simple DFS
simple-dfs-by-22147407-copu
IntuitionApproachComplexity Time complexity: Space complexity: Code
22147407
NORMAL
2025-02-16T11:41:48.072679+00:00
2025-02-16T11:41:48.072679+00:00
11
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 { public: int ans; int solve(vector<vector<int>>&g,int i,int j,int p,int cur,int x){ if(i<0||j<0||i>=g.size()||j>=g[0].size()||(cur==0&&g[i][j]!=2)||(cur==2&&g[i][j]!=0))return 0; int op1=0; int op2=0; if(p==0){ if(x==0) op1+=1+solve(g,i-1,j-1,1,g[i][j],1); op2=1+solve(g,i+1,j-1,p,g[i][j],x); }else if(p==1){ if(x==0) op1+=1+solve(g,i-1,j+1,2,g[i][j],1); op2=1+solve(g,i-1,j-1,p,g[i][j],x); }else if(p==2){ if(x==0) op1+=1+solve(g,i+1,j+1,3,g[i][j],1); op2=1+solve(g,i-1,j+1,p,g[i][j],x); }else if(p==3){ if(x==0) op1+=1+solve(g,i+1,j-1,0,g[i][j],1); op2=1+solve(g,i+1,j+1,p,g[i][j],x); } return max(op1,op2); } int lenOfVDiagonal(vector<vector<int>>& grid) { ans=-1; for(int i=0;i<grid.size();i++){ for(int j=0;j<grid[0].size();j++){ if(grid[i][j]==1){ int a=0,b=0,c=0,d=0; a=solve(grid,i+1,j-1,0,0,0); b=solve(grid,i-1,j-1,1,0,0); c=solve(grid,i-1,j+1,2,0,0); d=solve(grid,i+1,j+1,3,0,0); ans=max({ans,a,b,c,d}); } } } return ans+1; } }; ```
0
0
['Depth-First Search', 'C++']
0
length-of-longest-v-shaped-diagonal-segment
Best C++ 3D DP Solution
best-c-3d-dp-solution-by-doitkapil-7jjy
IntuitionApproachKeep track of current position, total turns you have taken and the direction in which you are going and apply 3D DP over this. Let me know if I
DoItKapil
NORMAL
2025-02-16T11:36:37.332146+00:00
2025-02-16T11:36:37.332146+00:00
8
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach Keep track of current position, total turns you have taken and the direction in which you are going and apply 3D DP over this. Let me know if I need to explain this further, happy to explain. # Complexity - Time complexity: O(n * m * 10) - Space complexity: 2 * O(n * m * 10) # Code ```cpp [] class Solution { private: vector<int>dirs={-1, -1, 1, 1, -1}; int findMax(int ele, int turn, int d, vector<vector<int>>& grid, int n, int m,vector<vector<vector<int>>>&dp){ int ans=0, r=ele/m, c=ele%m; if(dp[ele][turn][d]!=-1) return dp[ele][turn][d]; for(int k=0;k<=1;k++){ if(k==1 && turn==0) continue; int newr=r+dirs[d+k], newc=c+dirs[(d+1+k)%5]; if(newr<n && newc<m && newr>=0 && newc>=0 && (grid[r][c]+grid[newr][newc]==2) ){ ans=max(ans, findMax(newr*m+newc, turn-k, d+k, grid, n, m, dp)); } } return dp[ele][turn][d] = 1+ans; } public: int lenOfVDiagonal(vector<vector<int>>& grid) { int n=grid.size(), m=grid[0].size(); stack<int>st; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ if(grid[i][j]==1){ st.push(i*m+j); } } } int ans=0; if(st.size()==0) return ans; vector<vector<vector<int>>>dp(n*m+1, vector<vector<int>>(2, vector<int>(5,-1))); while(!st.empty()){ int ele=st.top(); st.pop(); int r=ele/m, c=ele%m; for(int i=0;i<4;i++){ int newr=r+dirs[i], newc=c+dirs[i+1]; if(newr<n && newc<m && newr>=0 && newc>=0 && grid[newr][newc]==2 ){ ans=max(ans, findMax(newr*m+newc, 1, i, grid, n, m, dp)); } } } return 1+ans; } }; ```
0
0
['C++']
0
length-of-longest-v-shaped-diagonal-segment
DFS | C++ | DP | Easy Approach | Beats 100% Space
dfs-c-dp-easy-approach-beats-100-space-b-ly9g
Code
bkbkbhavyakalra
NORMAL
2025-02-16T10:34:52.705324+00:00
2025-02-16T10:36:00.487428+00:00
12
false
# Code ```cpp [] class Solution { public: int n; int m; int dx[4] = {-1,-1,1,1}; int dy[4] = {-1,1,1,-1}; int getAns(vector<vector<int>> &grid, int i, int j, int ch, int a){ int ans = 1; if(ch == 1){ int nx = i + dx[(a + 1)%4]; int ny = j + dy[(a + 1)%4]; if(nx >= 0 && nx < n && ny >= 0 && ny < m){ if(grid[i][j] == 0 && grid[nx][ny] == 2){ ans = max(ans, 1 + getAns(grid, nx, ny, 0, (a+1)%4)); }else if(grid[i][j] == 2 && grid[nx][ny] == 0){ ans = max(ans, 1 + getAns(grid, nx, ny, 0, (a+1)%4)); } } } int nx = i + dx[a]; int ny = j + dy[a]; if(nx >= 0 && nx < n && ny >= 0 && ny < m){ if(grid[i][j] == 0 && grid[nx][ny] == 2){ ans = max(ans, 1 + getAns(grid, nx, ny, ch, a)); }else if(grid[i][j] == 2 && grid[nx][ny] == 0){ ans = max(ans, 1 + getAns(grid, nx, ny, ch, a)); } } return ans; } int lenOfVDiagonal(vector<vector<int>>& grid) { n = grid.size(); m = grid[0].size(); int ans = 0; for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ if(grid[i][j] == 1){ ans = max(ans, 1); for(int a = 0; a < 4; a++){ int nx = i + dx[a]; int ny = j + dy[a]; if(nx >= 0 && nx < n && ny >= 0 && ny < m && grid[nx][ny] == 2){ ans = max(ans, 1 + getAns(grid, nx, ny, 1, a)); } } } } } return ans; } }; ```
0
0
['Dynamic Programming', 'Depth-First Search', 'Graph', 'C++']
0
length-of-longest-v-shaped-diagonal-segment
☕ Java solution
java-solution-by-barakamon-15nz
null
Barakamon
NORMAL
2025-02-16T09:58:05.139928+00:00
2025-02-16T09:58:05.139928+00:00
34
false
![Screenshot_6.png](https://assets.leetcode.com/users/images/e134c588-b5ca-4cc8-be58-2f576b83a16b_1739699881.483507.png) ```java [] public class Solution { public int f(int[][] grid, int parent, int pi, int pj, boolean turned, int d, int n, int m) { int pi2 = pi, pj2 = pj; if (d == 0) { pi--; pj--; } else if (d == 1) { pi--; pj++; } else if (d == 2) { pi++; pj++; } else if (d == 3) { pi++; pj--; } int a = 1, b = 1; if (pi >= 0 && pi < n && pj >= 0 && pj < m) { if ((parent == 1 && grid[pi][pj] == 2) || (parent == 2 && grid[pi][pj] == 0) || (parent == 0 && grid[pi][pj] == 2)) { a = 1 + f(grid, grid[pi][pj], pi, pj, turned, d, n, m); } } if (!turned) { d = (d + 1) % 4; pi = pi2; pj = pj2; if (d == 0) { pi--; pj--; } else if (d == 1) { pi--; pj++; } else if (d == 2) { pi++; pj++; } else if (d == 3) { pi++; pj--; } if (pi >= 0 && pi < n && pj >= 0 && pj < m) { if ((parent == 1 && grid[pi][pj] == 2) || (parent == 2 && grid[pi][pj] == 0) || (parent == 0 && grid[pi][pj] == 2)) { b = 1 + f(grid, grid[pi][pj], pi, pj, true, d, n, m); } } } return Math.max(a, b); } public int lenOfVDiagonal(int[][] grid) { int n = grid.length, m = grid[0].length, q = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (grid[i][j] == 1) { for (int d = 0; d < 4; d++) { q = Math.max(q, f(grid, grid[i][j], i, j, false, d, n, m)); } } } } return q; } } ```
0
0
['Java']
0
length-of-longest-v-shaped-diagonal-segment
C++ | DFS + Dynamic Programming with explanation
c-dfs-dynamic-programming-with-explanati-fnqv
Ref: https://www.zerotoexpert.blog/i/157238403/problem-length-of-longest-v-shaped-diagonal-segmentSolutionIn this problem, we should find the most extended leng
a_ck
NORMAL
2025-02-16T09:12:12.413322+00:00
2025-02-16T09:12:12.413322+00:00
8
false
Ref: https://www.zerotoexpert.blog/i/157238403/problem-length-of-longest-v-shaped-diagonal-segment # Solution In this problem, we should find the most extended length that can be made with a 1,2,0,2,0 sequence. Unlike the typical DFS problem, we should move in a diagonal direction. Also, we can change the direction to one way and at most once. The solution is basically the same as for the typical DFS problem. However, before proceeding, we should consider the following two cases. - Choose the same direction. - Choose to take a 90-degree clockwise turn. In this case, we should not change the direction before. - The value difference between the current and the following positions should be 2 for both cases. So, for every position (x, y), we can keep track of the direction and the changed times. With this information, we can make all the possible moves. However, if the grid size increases, we might visit the same position with the same condition more than once. So, we can use memoization to save the previous result and then return if we visit again. This can be possible because we have at most 500 * 500 * 4 * 2 cases. (500 - m, 500 - n, 4 - direction, 2 - the number of turns) We don’t need to keep track of the previous visit during DFS because we cannot go back because we cannot change the direction 180 degrees. We cannot change the direction twice, so revisiting the same node within the single DFS traverse is impossible. # Code ```cpp [] class Solution { public: int dx[4] = {1,1,-1,-1}; int dy[4] = {1,-1,-1,1}; int dp[501][501][4][2]; bool pos(int x, int y, int nx, int ny, vector<vector<int>> & grid) { return nx >= 0 && ny >= 0 && nx < grid.size() && ny < grid[0].size() && abs(grid[x][y] - grid[nx][ny]) == 2; } int dfs(vector<vector<int>> & grid, int x, int y, int d, int changed) { if (dp[x][y][d][changed] != -1) return dp[x][y][d][changed]; // follow the direction int ans = 1; if (pos(x, y, x + dx[d], y + dy[d], grid)) { ans = max(ans, dfs(grid, x + dx[d], y + dy[d], d, changed) + 1); } // change the direction if (changed == 0) { int nd = (d + 1) % 4; if (pos(x, y, x + dx[nd], y + dy[nd], grid)) { ans = max(ans, dfs(grid, x + dx[nd], y + dy[nd], nd, changed+1) + 1); } } return dp[x][y][d][changed] = ans; } int lenOfVDiagonal(vector<vector<int>>& grid) { const int n = (int)grid.size(); const int m = (int)grid[0].size(); int ans = 0; memset(dp, -1, sizeof(dp)); for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (grid[i][j] == 1) { ans = max(ans, 1); for (int k = 0; k < 4; ++k) { int nx = i + dx[k], ny = j + dy[k]; if (nx < 0 || ny < 0 || nx >= n || ny >= m || grid[nx][ny] != 2) continue; ans = max(ans, dfs(grid, nx, ny, k, 0) + 1); } } } } return ans; } }; ```
0
0
['C++']
0
length-of-longest-v-shaped-diagonal-segment
Travel matrix diagonally, and form dp for each of the four directions
travel-matrix-diagonally-and-form-dp-for-6m92
IntuitionApproachComplexity Time complexity: Space complexity: Code
mnnit_prakharg
NORMAL
2025-02-16T09:06:55.640747+00:00
2025-02-16T09:06:55.640747+00:00
30
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 ```java [] class Solution { public int lenOfVDiagonal(int[][] mat) { int n = mat.length, m = mat[0].length; List<List<Pair>> listMat1 = new ArrayList<>(); List<List<Pair>> listMat2 = new ArrayList<>(); List<List<Pair>> listMat3 = new ArrayList<>(); List<List<Pair>> listMat4 = new ArrayList<>(); for (int col = 0; col < m; col++) { int row = n - 1; int c = col; List<Pair> list = new ArrayList<>(); while (c >= 0 && row >= 0) { list.add(new Pair(row, c)); row--; c--; } listMat1.add(list); } for (int row = n - 2; row >= 0; row--) { int col = m - 1; int r = row; List<Pair> list = new ArrayList<>(); while (col >= 0 && r >= 0) { list.add(new Pair(r, col)); r--; col--; } listMat1.add(list); } // turn 2 for (int row = n - 1; row >= 0; row--) { int col = 0; int r = row; List<Pair> list = new ArrayList<>(); while (col < m && r < n) { list.add(new Pair(r, col)); r++; col++; } listMat2.add(list); } for (int col = 1; col < m; col++) { int row = 0; int c = col; List<Pair> list = new ArrayList<>(); while (c < m && row < n) { list.add(new Pair(row, c)); row++; c++; } listMat2.add(list); } // 3rd turn for (int row = 0; row < n; row++) { int col = 0; int r = row; List<Pair> list = new ArrayList<>(); while (r >= 0 && col < m) { list.add(new Pair(r, col)); r--; col++; } listMat3.add(list); } for (int col = 1; col < m; col++) { int row = n - 1; int c = col; List<Pair> list = new ArrayList<>(); while (row >= 0 && c < m) { list.add(new Pair(row, c)); row--; c++; } listMat3.add(list); } // 4th turn for (int col = 0; col < m; col++) { int row = 0; int c = col; List<Pair> list = new ArrayList<>(); while (row < n && c >= 0) { list.add(new Pair(row, c)); row++; c--; } listMat4.add(list); } for (int row = 1; row < n; row++) { int col = m - 1; int r = row; List<Pair> list = new ArrayList<>(); while (r < n && col >= 0) { list.add(new Pair(r, col)); r++; col--; } listMat4.add(list); } // System.out.println("listMat1: " + listMat1); // System.out.println("listMat2: " + listMat2); // System.out.println("listMat3: " + listMat3); // System.out.println("listMat4: " + listMat4); int[][] dp1 = new int[n][m]; int[][] dp2 = new int[n][m]; int[][] dp3 = new int[n][m]; int[][] dp4 = new int[n][m]; for (List<Pair> list : listMat1) { int ls = list.size(); if (true) { Pair p = list.get(0); int r = p.row, c = p.col; if (mat[r][c] != 1) dp1[r][c] = 1; } for (int i = 1; i < ls; i++) { Pair p = list.get(i); int r = p.row, c = p.col; if (mat[r][c] == 1) dp1[r][c] = 0; else if (mat[r][c] != mat[list.get(i - 1).row][list.get(i - 1).col]) dp1[r][c] = dp1[list.get(i - 1).row][list.get(i - 1).col] + 1; else dp1[r][c] = 1; } } // System.out.println("Printing dp1: "); // for (int i = 0; i < n; i++) { // for (int j = 0; j < m; j++) // System.out.print(dp1[i][j] + " "); // System.out.println(""); // } // 2nd turn for (List<Pair> list : listMat2) { int ls = list.size(); if (true) { Pair p = list.get(0); int r = p.row, c = p.col; if (mat[r][c] != 1) dp2[r][c] = 1; } for (int i = 1; i < ls; i++) { Pair p = list.get(i); int r = p.row, c = p.col; if (mat[r][c] == 1) dp2[r][c] = 0; else if (mat[r][c] != mat[list.get(i - 1).row][list.get(i - 1).col]) dp2[r][c] = dp2[list.get(i - 1).row][list.get(i - 1).col] + 1; else dp2[r][c] = 1; } } // System.out.println("Printing dp2: "); // for (int i = 0; i < n; i++) { // for (int j = 0; j < m; j++) // System.out.print(dp2[i][j] + " "); // System.out.println(""); // } // 3rd turn for (List<Pair> list : listMat3) { int ls = list.size(); if (true) { Pair p = list.get(0); int r = p.row, c = p.col; if (mat[r][c] != 1) dp3[r][c] = 1; } for (int i = 1; i < ls; i++) { Pair p = list.get(i); int r = p.row, c = p.col; if (mat[r][c] == 1) dp3[r][c] = 0; else if (mat[r][c] != mat[list.get(i - 1).row][list.get(i - 1).col]) dp3[r][c] = dp3[list.get(i - 1).row][list.get(i - 1).col] + 1; else dp3[r][c] = 1; } } // System.out.println("Printing dp3: "); // for (int i = 0; i < n; i++) { // for (int j = 0; j < m; j++) // System.out.print(dp3[i][j] + " "); // System.out.println(""); // } // 4th turn for (List<Pair> list : listMat4) { int ls = list.size(); if (true) { Pair p = list.get(0); int r = p.row, c = p.col; if (mat[r][c] != 1) dp4[r][c] = 1; } for (int i = 1; i < ls; i++) { Pair p = list.get(i); int r = p.row, c = p.col; if (mat[r][c] == 1) dp4[r][c] = 0; else if (mat[r][c] != mat[list.get(i - 1).row][list.get(i - 1).col]) dp4[r][c] = dp4[list.get(i - 1).row][list.get(i - 1).col] + 1; else dp4[r][c] = 1; } } // System.out.println("Printing dp4: "); // for (int i = 0; i < n; i++) { // for (int j = 0; j < m; j++) // System.out.print(dp4[i][j] + " "); // System.out.println(""); // } int ans = 0; for (int row = 0; row < n; row++) { for (int col = 0; col < m; col++) { if (mat[row][col] != 1) continue; ans = Math.max(ans, 1); if (true) { int newR = row + 1, newC = col + 1; if (newR < n && newC < m && mat[newR][newC] == 2) { int len1 = dp1[newR][newC]; for (int i = 1; i <= len1; i++) { int newR1 = row + i, newC1 = col + i; ans = Math.max(ans, i + dp3[newR1][newC1]); } } // System.out.println("row: " + row + ", col: " + col + ", ans: " + ans); } if (true) { int newR = row - 1, newC = col - 1; if (newR >= 0 && newC >= 0 && mat[newR][newC] == 2) { int len1 = dp2[newR][newC]; for (int i = 1; i <= len1; i++) { int newR1 = row - i, newC1 = col - i; ans = Math.max(ans, i + dp4[newR1][newC1]); } } // System.out.println("row: " + row + ", col: " + col + ", ans: " + ans); } if (true) { int newR = row + 1, newC = col - 1; if (newR < n && newC >= 0 && mat[newR][newC] == 2) { int len1 = dp3[newR][newC]; for (int i = 1; i <= len1; i++) { int newR1 = row + i, newC1 = col - i; ans = Math.max(ans, i + dp2[newR1][newC1]); } } // System.out.println("row: " + row + ", col: " + col + ", ans: " + ans); } if (true) { int newR = row - 1, newC = col + 1; if (newR >= 0 && newC < m && mat[newR][newC] == 2) { int len1 = dp4[newR][newC]; for (int i = 1; i <= len1; i++) { int newR1 = row - i, newC1 = col + i; ans = Math.max(ans, i + dp1[newR1][newC1]); } } // System.out.println("row: " + row + ", col: " + col + ", ans: " + ans); } } } return ans; } } class Pair { int row; int col; Pair(int r, int c) { row = r; col = c; } public String toString() { return "(" + row + ", " + col + ")"; } } ```
0
0
['Java']
0
length-of-longest-v-shaped-diagonal-segment
C++ || 6D DP -> 4D DP
c-6d-dp-4d-dp-by-neelxdxd-au64
PLEASE UPVOTE IF YOU UNDERSTOOD Code6D DP ~ TLEOptimized 4D DPThe new state is: dp[i][j][dirIdx][nxt/2*2 + flag] i, j: Same as before, current cell coordinate
neelxdxd
NORMAL
2025-02-16T09:04:47.009566+00:00
2025-02-16T09:07:24.385665+00:00
19
false
> #### PLEASE $$UPVOTE$$ IF YOU UNDERSTOOD # Code **`6D DP ~ TLE`** ```cpp [] class Solution { public: struct VectorCompare { bool operator()(const vector<int>& a, const vector<int>& b) const { return a < b; } }; map<vector<int>,vector<int>,VectorCompare>dir; Solution() { dir[vector<int>{-1, 1}] = {1, 1}; dir[vector<int>{1, 1}] = {1, -1}; dir[vector<int>{1, -1}] = {-1, -1}; dir[vector<int>{-1, -1}] = {-1, 1}; } int func(int i,int j,int x,int y,vector<vector<int>>& grid,vector<vector<vector<vector<vector<vector<int>>>>>>&dp,int flag, int nxt, int m,int n,vector<vector<bool>>&vis){ if(i>=m || i<0 || j>=n || j<0) return 0; if(dp[i][j][x+1][y+1][nxt][flag]!=-1) return dp[i][j][x+1][y+1][nxt][flag]; vis[i][j] = true; int change=0,notChange=0; int nx = nxt == 0 ? 2 : 0; if(flag){ vector<int>it = dir[{x,y}]; int a = it[0], b = it[1]; if((x!=a || y!=b) && i+a>=0 && i+a<m && j+b>=0 && j+b<n && !vis[i+a][j+b] && grid[i+a][j+b]==nxt){ // cout<<i<<" "<<j<<" "<<i+a<<" "<<j+b<<endl; change = max(change,1+func(i+a,j+b,a,b,grid,dp,0,nx,m,n,vis)); } } // cout<<i<<" "<<j<<" "<<i+x<<" "<<j+y<<endl; if(i+x>=0 && i+x<m && j+y>=0 && j+y<n && !vis[i+x][j+y] && grid[i+x][j+y] == nxt) notChange = 1+func(i+x,j+y,x,y,grid,dp,flag,nx,m,n,vis); vis[i][j] = false; return dp[i][j][x+1][y+1][nxt][flag] = max(change, notChange); } int lenOfVDiagonal(vector<vector<int>>& grid) { int m = grid.size(),n = grid[0].size(); vector<vector<int>>arr; for(int i=0;i<grid.size();i++){ for(int j=0;j<grid[0].size();j++){ if(grid[i][j] == 1){ arr.push_back({i,j}); } } } if(arr.size() == 0) return 0; vector<vector<vector<vector<vector<vector<int>>>>>>dp(m,(vector<vector<vector<vector<vector<int>>>>>(n,vector<vector<vector<vector<int>>>>(3,(vector<vector<vector<int>>>(3,(vector<vector<int>>(3,vector<int>(2,-1))))))))); int ma = 0; vector<vector<bool>>vis(m,(vector<bool>(n,false))); for(auto it:arr){ int tr=0,tl=0,br=0,bl=0; int x = it[0], y = it[1]; if(x-1>=0 && y+1<n && grid[x-1][y+1]==2){ // cout<<x<<" "<<y<<" "<<x-1<<" "<<y+1<<endl; tr = 2+func(x-1,y+1,-1,1,grid,dp,1,0,m,n,vis); // cout<<endl; } if(x+1<m && y+1<n && grid[x+1][y+1]==2){ // cout<<x<<" "<<y<<" "<<x+1<<" "<<y+1<<endl; br = 2+func(x+1,y+1,1,1,grid,dp,1,0,m,n,vis); // cout<<endl; } if(x+1<m && y-1>=0 && grid[x+1][y-1]==2){ // cout<<x<<" "<<y<<" "<<x+1<<" "<<y-1<<endl; bl = 2+func(x+1,y-1,1,-1,grid,dp,1,0,m,n,vis); // cout<<endl; } if(x-1>=0 && y-1>=0 && grid[x-1][y-1]==2){ // cout<<x<<" "<<y<<" "<<x-1<<" "<<y-1<<endl; tl = 2+func(x-1,y-1,-1,-1,grid,dp,1,0,m,n,vis); // cout<<endl; } ma = max({ma,tr,tl,br,bl}); } return ma == 0 ? 1 : ma; } }; ``` **`Optimized 4D DP`** `The new state is: dp[i][j][dirIdx][nxt/2*2 + flag]` - i, j: Same as before, current cell coordinates - dirIdx: Index into the direction vectors (0,1,2,3) representing the four possible directions - Direction Encoding: Instead of storing x and y separately with the offset (x+1, y+1), I use a single integer dirIdx that indexes into the dirs array: - dirs[0] = {-1,1} (top-right) - dirs[1] = {1,1} (bottom-right) - dirs[2] = {1,-1} (bottom-left) - dirs[3] = {-1,-1} (top-left) - nxt/2*2 + flag: Encodes both nxt and flag into a single dimension (0,1,2,3) - Since nxt is either 0 or 2, we can represent it with a single bit (0→0, 2→1) using nxt/2 - flag is already a binary value (0 or 1). We combine them as nxt/2*2 + flag to get: - nxt=0, flag=0 → 0*2 + 0 = 0 - nxt=0, flag=1 → 0*2 + 1 = 1 - nxt=2, flag=0 → 1*2 + 0 = 2 - nxt=2, flag=1 → 1*2 + 1 = 3 - This combines two dimensions (size 3 and size 2) into a single dimension of size 4 ```cpp [] class Solution { public: // Direction vectors: top-right, bottom-right, bottom-left, top-left vector<vector<int>> dirs = {{-1,1}, {1,1}, {1,-1}, {-1,-1}}; vector<vector<int>> nextDirs = {{1,1}, {1,-1}, {-1,-1}, {-1,1}}; int func(int i, int j, int dirIdx, vector<vector<int>>& grid, int flag, int nxt, int m, int n, vector<vector<bool>>& vis, int dp[501][501][4][4]) { if (i >= m || i < 0 || j >= n || j < 0) return 0; if (dp[i][j][dirIdx][nxt/2*2 + flag] != -1) return dp[i][j][dirIdx][nxt/2*2 + flag]; vis[i][j] = true; int change = 0, notChange = 0; int nx = nxt == 0 ? 2 : 0; int x = dirs[dirIdx][0], y = dirs[dirIdx][1]; if (flag) { int nextDirIdx = (dirIdx + 1) % 4; int a = nextDirs[dirIdx][0], b = nextDirs[dirIdx][1]; if (i+a >= 0 && i+a < m && j+b >= 0 && j+b < n && !vis[i+a][j+b] && grid[i+a][j+b] == nxt) { change = 1 + func(i+a, j+b, nextDirIdx, grid, 0, nx, m, n, vis, dp); } } if (i+x >= 0 && i+x < m && j+y >= 0 && j+y < n && !vis[i+x][j+y] && grid[i+x][j+y] == nxt) { notChange = 1 + func(i+x, j+y, dirIdx, grid, flag, nx, m, n, vis, dp); } vis[i][j] = false; return dp[i][j][dirIdx][nxt/2*2 + flag] = max(change, notChange); } int lenOfVDiagonal(vector<vector<int>>& grid) { int m = grid.size(), n = grid[0].size(); // 4D DP array: [row][col][direction][state] // where state = nxt*2 + flag (0,1,2,3) int dp[501][501][4][4]; memset(dp, -1, sizeof(dp)); vector<vector<bool>> vis(m, vector<bool>(n, false)); int maxLength = 0; // Find all cells with value 1 int cnt = 0; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (grid[i][j] == 1) { cnt++; for (int dirIdx = 0; dirIdx < 4; dirIdx++) { int nx = i + dirs[dirIdx][0]; int ny = j + dirs[dirIdx][1]; if (nx >= 0 && nx < m && ny >= 0 && ny < n && grid[nx][ny] == 2) { int length = 2 + func(nx, ny, dirIdx, grid, 1, 0, m, n, vis, dp); maxLength = max(maxLength, length); } } } } } if(cnt==0) return 0; return maxLength == 0 ? 1 : maxLength; } }; ```
0
0
['Dynamic Programming', 'Recursion', 'Matrix', 'C++']
0
length-of-longest-v-shaped-diagonal-segment
Intuitive and concise DFS + memo solution
intuitive-and-concise-dfs-memo-solution-yt5c4
IntuitionI confess that I didn't get the correct solution during the contest. This is the post correction version. I ran into a few issues that I felt tricky an
xiaozhi1
NORMAL
2025-02-16T08:05:15.585226+00:00
2025-02-16T08:13:54.686734+00:00
24
false
# Intuition I confess that I didn't get the correct solution during the contest. This is the post correction version. I ran into a few issues that I felt tricky and didn't notice while reading the question (I'm not good at reading long questions), so I refactored the code several times. a. The turn should always be 90 degree clock-wise. So for the 4 directions you claimed at the beginning, it should have an order `dirs = [(-1, -1), (-1, 1), (1, 1), (1, -1)]`. b. You could start from any order in the 4 direction, but the next one must be the one after the original order in the list. So `(ori+1)%4` is a good way to iterate it. c. You can turn at-most once, so you know, it needs more varible(`change`) to track trim the normal expansive dfs funtion d. I used a global variable, like `self.ans` to track the final answer, but it exceeds the time-limit. So I tried to add cache to the dfs function. `@functools.cache` leaded to a memory exceeded (I'm not sure why, if you know, please comment below). But after referring other smart people's code, I decided to memorize in my code by myself. e. Originally, I had a visited array to track the coordination I visited in dfs, but given the cache we use, we could eliminate it. # Code ```python3 [] class Solution: def lenOfVDiagonal(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) dirs = [(-1, -1), (-1, 1), (1, 1), (1, -1)] cache = dict() def dfs(i, j, ori, change, v): if (i, j, ori, change) in cache: return cache[(i, j, ori, change)] res = 0 for o in (ori, (ori+1)%4): x = i + dirs[o][0] y = j + dirs[o][1] if 0 <= x < m and 0 <= y < n and grid[x][y] == 2 - v: if ori == o: res = max(res, 1 + dfs(x, y, o, change, grid[x][y])) elif change == 0: res = max(res, 1 + dfs(x, y, o, change+1, grid[x][y])) cache[(i, j, ori, change)] = res return res ans = 0 for i in range(m): for j in range(n): if grid[i][j] == 1: ans = max(ans, 1) for ori in range(len(dirs)): x = i + dirs[ori][0] y = j + dirs[ori][1] if 0 <= x < m and 0 <= y < n and grid[x][y] == 2: ans = max(ans, 2 + dfs(x, y, ori, 0, grid[x][y])) return ans ```
0
0
['Python3']
0
length-of-longest-v-shaped-diagonal-segment
[A⭐] 312ms/100% Java: Novel A-Star-like longest possible path DFS optimization
385ms100-java-a-like-longest-possible-pa-zy50
Notes Before We BeginThere's no tag for A* search here, and since it's probably closest to depth-first (due to the optimization for longest possible path), I ta
mattihito
NORMAL
2025-02-16T07:19:43.360299+00:00
2025-02-17T05:45:50.678826+00:00
35
false
# Notes Before We Begin There's no tag for A* search here, and since it's probably closest to depth-first (due to the optimization for longest possible path), I tagged that. This solution is a variant of Dijkstra's algorithm optimized by a heuristic (making it more akin to A*). It's definitely not the simplest solution. And it's probably not the fastest. There is one readability advantage in that the state itself is encapsulated into its own class, making the search loop itself quite simple. When I first learned about Dijkstra's algorithm, and got some practice with it, a big lightbulb slowly lit in my brain. Another one lit up when someone explained A* as a kind of optimization of Dijkstra's algorithm with the addition of an optimizing heuristic prioritizing the search using a lower-bound estimate of the shortest possible path. I'm not claiming any cleverness here: Dijkstra's is like a familiar hammer to me because I just really like it. Because of this, I tend to be on the lookout for problems that are at least analogous to nails. And while this problem did not initially respond well to the Dijkstra hammer, it does actually respond reasonably well with the help of some adaptations and optimizations I stumbled across. I learned some new things in solving this problem, and I'm sharing this in case anyone else makes some new connections between different ideas from reading it, like I did from fumbling my way through it. # Intuition & Approach This is almost like an A* search to find a shortest path, but we are going to turn it on its head to look for the longest path, instead. Our actual search (starting from a 1-value) can track a priority queue of states, but we put the state with the best possible outcome (based on geometry alone) at the front of the queue, breaking ties by the longest actual length traveled. ### Review of Dijkstra's and A* For Shortest Possible Path To quickly review, when using Dijkstra's algorithm to find a shortest path, we sometimes use a priority queue to track the states and prioritize the shortest paths traveled first; thus when we reach our goal, we can stop because we know we have found the shortest path. The queue and its sort order makes this a guarantee. For each state, we investigate its legal neighboring states, and to further optimize we can keep a set of visited states to avoid duplication. By "state", here, we mean a node in a search graph, as well as the total path traveled so far, as well as any other information required to compute which neighboring states (those reachable via legal edges from the given node) are possible. We can convert this shortest path approach to A* by adding a heuristic: we track the shortest possible path of each state assuming the best case in reaching the goal (where underestimating this shortest possible path is fine, but overestimating it is not). Then we modify our priority queue to prioritize the states with the smallest shortest possible paths, and break ties by the longest actual path traveled. When we find a state that has reached the goal, we can stop, because no other state in the queue could have a shorter path (as each of their shortest possible paths are at least as long as the actual shortest path found, due to the sort order of the priority queue). ### Adaptation for Finding the Longest Path In this problem, we can take a similar approach to A*, but we invert the heuristic and change the sort order because we are looking for the longest possible path. So our priority queue prioritizes the state with the maximum longest possible path (where overestimating this longest possible path is okay, but underestimating it is not). We still break ties by the longest path traveled, because we want to be able to stop when we reach our goal. Similarly to the shortest path approach, when we reach our goal (or a point where the longest actual path length seen so far equals the most recently popped state's longest possible path), we can stop, because all states remaining in the queue have smaller longest possible paths, and thus could not exceed the maximum path length seen. We are being a little loose with the concept of a graph, nodes and edges here, but it works because the problem is isomorphic to searching a graph. ### The Search State Our state will consist of a length traveled `len`, a row `r`, a column `c`, a `dr` value (change in row, row component of velocity), a `dc` value (change in column, column component of velocity) and a count of how many `bends` have been used (max 1). Additionally, each state will have a shared copy of the grid, its number of rows and number of columns (for convenience, these are not actually part of the state itself as they do not vary). Further, each state will precompute its longest possible (geometric) path length, and a hash code based on the actual state values (`len`, `r`, `c`, `dr`, `dc` and `bends`). The longest we can travel is basically how far we can travel to the edge of the board in our current direction plus our current length, provided we have already used our clockwise bend. But if we haven't, then on reaching an edge of the board, we can bend and come back the other way in one dimension. It's okay to overestimate this value (just like in A* search for a shorest path, it's okay to underestimate this value). So we don't have to worry about double-bends due to hitting a second wall to have a better-than-nothing (over)estimate of the longest possible path. ### The Longest Possible Path Heuristic For example, suppose we are moving up and to the right, and we hit the top edge of the grid. We can turn clockwise to move down and to the right until we hit the bottom of the board. We can ignore what might happen if we hit the right wall instead; we can just project the bottom of the board as far to the right as necessary. In fact, for this part, since it's opkay to overestimate, we can ignore whether we are turning clockwise or not. For example, suppose we are moving up and to the right and we hit the right edge of the board. We're done, because turning clockwise continues off away from the right edge of the board. But for our estimation, we can assume a rebound back to the left. This reduces the computation per state, but isn't quite as good at filtering out dead ends. It's a useful but not ideal heuristic -- a trade-off we can make to keep things simple and consider optimizing further later if it turns out to be more profitable to spend more computation time per state to refine this value. But otherwise, with a bend available, it's basically a calculation of the distance (with rebound) we can travel horizontally and vertically, then we mix the non-bending horizontal with the bending vertical and vice versa to get additional options beyond the non-bending path. By "mix" here we mean minimum (of vertical and horizontal), but we take the maximum of the mixed minima to get the best possible path length. (See the constructor of the `State` inner class for the implementation). With this longest possible path heuristic, we can sort our priority queue by the longest possible path, and break ties by longest path traveled so far, such that when we encounter a state whose longest possible path does not exceed our best actual path seen so far, we are done (we need not search further). ### Tracking Previously Visited States We will be starting at various "1" positions in the grid and trying multiple angles. There's a very high likelihood that we'll reach a grid position with the same directional velocity, same bends count and same length traveled so far. So we'll use a hash set to avoid duplicate states. To keep things simple and avoid hashing several values multiple times, and because we'll add (or try to add) every state to this "visited" hash set (ensuring every state will need its hash code at least once), we'll just precompute the hash code in the constructor of our state ensuring it is computed exactly once. ### Stopping if We Find The Actual Maximum Possible Answer The maximum possible answer (geometrically) for a grid is the maximum of: - The minimum of {the number of rows} and {twice the number of columns minus one} - The mimimum of {twice the number of rows minus one} and {the number of columns} For example: in a grid with 3 rows and 8 columns, the maximum possible answer is 5. One example of such a maximum possible answer is: ``` +-+-+-+-+-+-+-+-+ | | |^| | | | | | +-+-+-+-+-+-+-+-+ | |/| |\| | | | | +-+-+-+-+-+-+-+-+ |/| | | |\| | | | +-+-+-+-+-+-+-+-+ ``` So, if for a given grid position with a 1, we find a path length equal to this maximum possible answer, we can stop early, as no larger answer is possible. # Complexity - Time complexity: No idea about average time complexity. We can set an upper bound though. We have an O(mn) iteration over the grid to look for starting points. And we basically have 4 paths out from that to explore, each of which can have a length of O(max(m, n)). But each of these is stored in a priority queue which makes offer and poll O(log x) operation. To simplify this a bit, define m and n such that m is the maximum of the rows or columns in the grid and n is the minimum. Then we have O(m^2 n log m) as an upper bound on time complexity (I think). But due to our optimizations it may be less than this. **Comments welcome if you can add any ideas or corrections about this**. - Space complexity: No idea about average space complexity. As an upper bound, we can argue that our priority queue and requires O(x) space. Our hash set to track previously visited states, but persists across starting points. Using the same definition of m and n above, we have O(m^2 n) as an upper bound on space complexity (I think). But due to our optimizations it may be less than this. **Comments welcome if you can add any ideas or corrections about this**. - Runtime: about 385ms / faster than 100% as of 2025-02-16. (Update: About 312ms with the optimization discussed further down.) # Code ```java [Java (naive longest possible path)] class Solution { public int lenOfVDiagonal(int[][] grid) { final int rows = grid.length; final int cols = grid[0].length; final int maxAnswer = Math.max( Math.min(rows, (cols << 1) - 1), Math.min((rows << 1) - 1, cols)); int answer = 0; final Set<State> seen = new HashSet<>(); for (int r = 0; r < rows; ++r) { for (int c = 0; c < cols; ++c) { if (grid[r][c] == 1) { final int length = maxLength(r, c, grid, rows, cols, seen, maxAnswer); if (length == maxAnswer) { return length; } answer = Math.max(answer, length); } } } return answer; } private int maxLength(int sr, int sc, int[][] grid, int rows, int cols, Set<State> seen, int maxAnswer) { final PriorityQueue<State> pq = new PriorityQueue<>(); for (int dr = -1; dr <= 1; dr += 2) { for (int dc = -1; dc <= 1; dc += 2) { final State start = new State(grid, rows, cols, 1, sr, sc, dr, dc, 0); if (seen.add(start)) { pq.offer(start); } } } int best = 0; while (!pq.isEmpty()) { final State p = pq.poll(); best = Math.max(p.len, best); if (p.possible <= best || best == maxAnswer) { return best; } final List<State> next = p.nextStates(); if (next != null) { for (State n : next) { if (seen.add(n)) { pq.offer(n); } } } } return best; } static class State implements Comparable<State> { // shared state final int[][] grid; final int rows; final int cols; // actual state final int len; final int r; final int c; final int dr; final int dc; final int bends; // extras final int possible; final int hc; public State(int[][] grid, int rows, int cols, int len, int r, int c, int dr, int dc, int bends) { this.grid = grid; this.rows = rows; this.cols = cols; this.len = len; this.r = r; this.c = c; this.dr = dr; this.dc = dc; this.bends = bends; final int straightR = (dr == 1 ? rows - r - 1 : r); final int straightC = (dc == 1 ? cols - c - 1 : c); final int straight = Math.min(straightR, straightC); // (over)estimate the longest possible path for A*-like optimization if (bends < 1) { final int bentR = straightR + rows - 1; final int bentC = straightC + cols - 1; final int bent = Math.max(Math.min(straightR, bentC), Math.min(bentR, straightC)); this.possible = len + Math.max(straight, bent); } else { this.possible = len + straight; } this.hc = Objects.hash(len, r, c, dr, dc, bends); } public List<State> nextStates() { final int rr = this.r + this.dr; final int cc = this.c + this.dc; if (rr < 0 || cc < 0 || rr >= rows || cc >= cols) { return null; } final int current = grid[this.r][this.c]; final int target = (current == 1 ? 2 : 2 - current); if (grid[rr][cc] != target) { return null; } final List<State> out = new ArrayList<>(); final int ll = this.len + 1; out.add(new State(grid, rows, cols, ll, rr, cc, this.dr, this.dc, this.bends)); if (this.bends < 1) { // clockwise: out.add(new State(grid, rows, cols, ll, rr, cc, this.dc, -this.dr, this.bends + 1)); } return out; } @Override public final int hashCode() { return this.hc; } @Override public final boolean equals(Object o) { if (this == o) { return true; } else if (o == null || o.getClass() != getClass()) { return false; } final State other = (State) o; return (this.hc == other.hc && this.len == other.len && this.r == other.r && this.c == other.c && this.dr == other.dr && this.dc == other.dc && this.bends == other.bends); } @Override public final int compareTo(State other) { int diff = other.possible - this.possible; if (diff == 0) { diff = other.len - this.len; } return diff; } } } ``` # Update - Additional Optimization of Longest Possible Path We mentioned above that we might be able to make this faster by improving the longest possible path estimate (to reduce the _over-_ estimation) in the constructor of the `State` inner class. It turns out, computing this exactly (ignoring grid values, just purely from geometry) is not as difficult as it might have seemed. We can create a static method to compute it as follows: ```java [Java (new method only)] private static int computeLongestPossiblePath(int len, int bends, int r, int c, int dr, int dc, int rows, int cols) { final int straightR = (dr > 0 ? rows - r - 1 : r); final int straightC = (dc > 0 ? cols - c - 1 : c); final int straight = Math.min(straightR, straightC); if (bends > 0) { return len + straight; } // Where will we end up? Which wall? And can we turn clockwise there? // Compute straight endpoint and clockwise turn. // Then check if we can proceed after our clockwise turn. // Handle row and col separately for early return. final int r2 = r + (dr * straight); final int dr2 = dc; final int r3 = r2 + dr2; if (r3 < 0 || r3 >= rows) { // Row out of bounds, can't turn, we are done. return len + straight; } final int c2 = c + (dc * straight); final int dc2 = -dr; final int c3 = c2 + dc2; if (c3 < 0 || c3 >= cols) { // Out of bounds, can't turn, we are done return len + straight; } // Our turn was successful. Where does it end up? final int straightR2 = (dr2 > 0 ? rows - r2 - 1 : r2); final int straightC2 = (dc2 > 0 ? cols - c2 - 1 : c2); final int straight2 = Math.min(straightR2, straightC2); return len + straight + straight2; } ``` This involves more computation for each state we generate, so it may not pay off; testing is really the only reasonable way to tell. With this added, we can get down to about 312ms, so we can get about a 15-20% improvement using this improved but more complex heuristic. The full code with this optimization looks like this: ```java [Java (with the additional optimization)] class Solution { public int lenOfVDiagonal(int[][] grid) { final int rows = grid.length; final int cols = grid[0].length; final int maxAnswer = Math.max( Math.min(rows, (cols << 1) - 1), Math.min((rows << 1) - 1, cols)); int answer = 0; final Set<State> seen = new HashSet<>(); for (int r = 0; r < rows; ++r) { for (int c = 0; c < cols; ++c) { if (grid[r][c] == 1) { final int length = maxLength(r, c, grid, rows, cols, seen, maxAnswer); if (length == maxAnswer) { return length; } answer = Math.max(answer, length); } } } return answer; } private int maxLength(int sr, int sc, int[][] grid, int rows, int cols, Set<State> seen, int maxAnswer) { final PriorityQueue<State> pq = new PriorityQueue<>(); for (int dr = -1; dr <= 1; dr += 2) { for (int dc = -1; dc <= 1; dc += 2) { final State start = new State(grid, rows, cols, 1, sr, sc, dr, dc, 0); if (seen.add(start)) { pq.offer(start); } } } int best = 0; while (!pq.isEmpty()) { final State p = pq.poll(); best = Math.max(p.len, best); if (p.possible <= best || best == maxAnswer) { return best; } final List<State> next = p.nextStates(); if (next != null) { for (State n : next) { if (seen.add(n)) { pq.offer(n); } } } } return best; } static class State implements Comparable<State> { // shared state final int[][] grid; final int rows; final int cols; // actual state final int len; final int r; final int c; final int dr; final int dc; final int bends; // extras final int possible; final int hc; public State(int[][] grid, int rows, int cols, int len, int r, int c, int dr, int dc, int bends) { this.grid = grid; this.rows = rows; this.cols = cols; this.len = len; this.r = r; this.c = c; this.dr = dr; this.dc = dc; this.bends = bends; this.possible = computeLongestPossiblePath(len, bends, r, c, dr, dc, rows, cols); this.hc = Objects.hash(len, r, c, dr, dc, bends); } public List<State> nextStates() { final int rr = this.r + this.dr; final int cc = this.c + this.dc; if (rr < 0 || cc < 0 || rr >= rows || cc >= cols) { return null; } final int current = grid[this.r][this.c]; final int target = (current == 1 ? 2 : 2 - current); if (grid[rr][cc] != target) { return null; } final List<State> out = new ArrayList<>(); final int ll = this.len + 1; out.add(new State(grid, rows, cols, ll, rr, cc, this.dr, this.dc, this.bends)); if (this.bends < 1) { // clockwise: out.add(new State(grid, rows, cols, ll, rr, cc, this.dc, -this.dr, this.bends + 1)); } return out; } @Override public final int hashCode() { return this.hc; } @Override public final boolean equals(Object o) { if (this == o) { return true; } else if (o == null || o.getClass() != getClass()) { return false; } final State other = (State) o; return (this.hc == other.hc && this.len == other.len && this.r == other.r && this.c == other.c && this.dr == other.dr && this.dc == other.dc && this.bends == other.bends); } @Override public final int compareTo(State other) { int diff = other.possible - this.possible; if (diff == 0) { diff = other.len - this.len; } return diff; } private static int computeLongestPossiblePath(int len, int bends, int r, int c, int dr, int dc, int rows, int cols) { final int straightR = (dr == 1 ? rows - r - 1 : r); final int straightC = (dc == 1 ? cols - c - 1 : c); final int straight = Math.min(straightR, straightC); final int totalToWall = len + straight; if (bends > 0) { return totalToWall; } // Where will we end up? Which wall? And can we turn clockwise there? // Compute straight endpoint and clockwise turn. // Then check if we can proceed after our clockwise turn. // Handle row and col separately for early return. final int r2 = r + (dr * straight); final int dr2 = dc; final int r3 = r2 + dr2; if (r3 < 0 || r3 >= rows) { // Row out of bounds, can't turn, we are done. return totalToWall; } final int c2 = c + (dc * straight); final int dc2 = -dr; final int c3 = c2 + dc2; if (c3 < 0 || c3 >= cols) { // Out of bounds, can't turn, we are done return totalToWall; } // Our turn was successful. Where does it end up? final int straightR2 = (dr2 == 1 ? rows - r2 - 1 : r2); final int straightC2 = (dc2 == 1 ? cols - c2 - 1 : c2); final int straight2 = Math.min(straightR2, straightC2); return totalToWall + straight2; } } } ``` # Standard Plea If you found this interesting, helpful, or think someone else would, **I would appreciate your upvote**. If you have suggestions, constructive criticism, or any ideas about space or time complexities for this solution, **I would welcome your comments**. Thanks for reading, and happy coding!
0
0
['Depth-First Search', 'Java']
0
length-of-longest-v-shaped-diagonal-segment
beat 100% ms
beat-100-ms-by-hoanghung3011-wrtw
IntuitionApproachComplexity Time complexity: Space complexity: Code
hoanghung3011
NORMAL
2025-02-16T07:00:09.422560+00:00
2025-02-16T07:00:09.422560+00:00
32
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 ```java [] class Solution { int n, m; int[][] grid; // dp[d][i][j][st]: maximum length starting at cell (i,j) in direction d with expected state st. // d in {0,1,2,3}, st in {0,1,2} // State meanings: // 0: expecting 1, // 1: expecting 0, // 2: expecting 2. int[][][][] dp; // Direction vectors for the 4 diagonal directions. // 0: (1,1) (top-left to bottom-right) // 1: (1,-1) (top-right to bottom-left) // 2: (-1,-1) (bottom-right to top-left) // 3: (-1,1) (bottom-left to top-right) int[] dx = {1, 1, -1, -1}; int[] dy = {1, -1, -1, 1}; // Returns the expected value for a given state. private int expected(int st) { if (st == 0) return 1; if (st == 1) return 0; return 2; // st == 2 } // Returns the next state after consuming one cell in the current state. // From state 0 (expecting 1), next becomes state 2 (expecting 2). // From state 2 (expecting 2), next becomes state 1 (expecting 0). // From state 1 (expecting 0), next becomes state 2 (expecting 2). private int nextState(int st) { if (st == 0) return 2; if (st == 2) return 1; return 2; // st == 1 } public int lenOfVDiagonal(int[][] grid) { this.grid = grid; n = grid.length; m = grid[0].length; dp = new int[4][n][m][3]; // Initialize dp arrays to 0. for (int d = 0; d < 4; d++) { for (int i = 0; i < n; i++){ for (int j = 0; j < m; j++){ for (int st = 0; st < 3; st++){ dp[d][i][j][st] = 0; } } } } // Fill dp for each direction separately. // Direction 0: (1,1) - process from bottom-right to top-left. for (int i = n - 1; i >= 0; i--) { for (int j = m - 1; j >= 0; j--) { for (int st = 0; st < 3; st++) { if (grid[i][j] == expected(st)) { int ni = i + dx[0], nj = j + dy[0]; int add = 0; if (ni >= 0 && ni < n && nj >= 0 && nj < m) add = dp[0][ni][nj][nextState(st)]; dp[0][i][j][st] = 1 + add; } } } } // Direction 1: (1,-1) - process from bottom-left to top-right. for (int i = n - 1; i >= 0; i--) { for (int j = 0; j < m; j++) { for (int st = 0; st < 3; st++) { if (grid[i][j] == expected(st)) { int ni = i + dx[1], nj = j + dy[1]; int add = 0; if (ni >= 0 && ni < n && nj >= 0 && nj < m) add = dp[1][ni][nj][nextState(st)]; dp[1][i][j][st] = 1 + add; } } } } // Direction 2: (-1,-1) - process from top-left to bottom-right. for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { for (int st = 0; st < 3; st++) { if (grid[i][j] == expected(st)) { int ni = i + dx[2], nj = j + dy[2]; int add = 0; if (ni >= 0 && ni < n && nj >= 0 && nj < m) add = dp[2][ni][nj][nextState(st)]; dp[2][i][j][st] = 1 + add; } } } } // Direction 3: (-1,1) - process from top-right to bottom-left. for (int i = 0; i < n; i++) { for (int j = m - 1; j >= 0; j--) { for (int st = 0; st < 3; st++) { if (grid[i][j] == expected(st)) { int ni = i + dx[3], nj = j + dy[3]; int add = 0; if (ni >= 0 && ni < n && nj >= 0 && nj < m) add = dp[3][ni][nj][nextState(st)]; dp[3][i][j][st] = 1 + add; } } } } int ans = 0; // Iterate over all starting cells that have value 1 (since state 0 expects 1) // and over each initial direction. for (int i = 0; i < n; i++){ for (int j = 0; j < m; j++){ if (grid[i][j] != 1) continue; for (int d = 0; d < 4; d++){ int L0 = dp[d][i][j][0]; // no-turn segment length ans = Math.max(ans, L0); // Try making one clockwise 90-degree turn. // We try every possible turning point along the first segment. // Let x be the number of steps taken in the first segment (1 <= x <= L0). for (int x = 1; x <= L0; x++){ // Turning cell: reached after x steps along direction d (counting starting cell as step1). int ti = i + (x - 1) * dx[d]; int tj = j + (x - 1) * dy[d]; // The next expected state is determined by x: // if x is odd, then p = x, and since for p>=1, odd positions expect 2, so state=2. // if x is even, state = 1. int newState = (x % 2 == 1) ? 2 : 1; // Turn: new direction is (d+1)%4. int d2 = (d + 1) % 4; int ni = ti + dx[d2], nj = tj + dy[d2]; if (ni < 0 || ni >= n || nj < 0 || nj >= m) continue; int L2 = dp[d2][ni][nj][newState]; if (L2 > 0) { ans = Math.max(ans, x + L2); } } } } } return ans; } } ```
0
0
['Java']
0
length-of-longest-v-shaped-diagonal-segment
Simple readable code. memoization
simple-readable-code-memoization-by-hari-j08u
IntuitionSeperate the logic. first find all possible distences after clockwise 90 degree turn. for all ones check in all four direction how for you can go. also
harisht26698
NORMAL
2025-02-16T06:48:32.942490+00:00
2025-02-16T06:48:32.942490+00:00
39
false
# Intuition Seperate the logic. 1. first find all possible distences after clockwise 90 degree turn. 2. for all ones check in all four direction how for you can go. also check max distence if you take clockwise 90 degree turn. **Important: Clockwise turn** # Approach use four 2D arrays to store the max distence in one direction. for each ones. do dfs and find the max distence if move in same and if we take colckwise 90 degree turn. please see the code. # Complexity - Time complexity: O(m * n * Max(m * n)) - Space complexity: O(m*n) # Code ```java [] class Solution { int[][] downR, downL, upL, upR; // clockwise. dp for wll direction // downR, downL, upL, upR is used to store max possible distence in 4 directions int up = -1, down = 1, left = -1, right = 1; // directions for diagonals public int lenOfVDiagonal(int[][] g) { int m = g.length, n = g[0].length, res = 0; downR = new int[m][n]; downL = new int[m][n]; upL = new int[m][n]; upR = new int[m][n]; // fill -1 to mark unvisited for(int i=0;i<m;i++){ Arrays.fill(downR[i], -1); Arrays.fill(downL[i], -1); Arrays.fill(upL[i], -1); Arrays.fill(upR[i], -1); } // store maximum possible distence in second direction // O(m * n) -> helper will take O(1) because of memoisation result stored in first iteration. for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ if(g[i][j] != 1){ helper(i, j, g, down, right, g[i][j], downR); helper(i, j, g, down, left, g[i][j], downL); helper(i, j, g, up, left, g[i][j], upL); helper(i, j, g, up, right, g[i][j], upR); } } } // O(m * n * Max (m, n)) int req = 2; for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ if(g[i][j] == 1){ // find max len of all 4 directions update result res = Math.max(res, solve(g, i + down, j + right, req, down, right) + 1); res = Math.max(res, solve(g, i + down, j + left, req, down, left) + 1); res = Math.max(res, solve(g, i + up, j + left, req, up, left) + 1); res = Math.max(res, solve(g, i + up, j + right, req, up, right) + 1); } } } return res; } // O(1) because of memozation int helper(int x, int y, int[][] g, int dir1, int dir2, int req, int[][] dp){ if(isInvalid(x, y, g, req)) return 0; req = req == 2 ? 0 : 2; if(dp[x][y] != -1) return dp[x][y]; return dp[x][y] = helper(x + dir1, y + dir2, g, dir1, dir2, req, dp) + 1; } // O(Max(m, n)) int solve(int[][] g, int x, int y, int req, int dir1, int dir2){ if(isInvalid(x, y, g, req)) return 0; req = req == 2 ? 0 : 2; // next required number int res = solve(g, x + dir1, y + dir2, req, dir1, dir2) + 1; // without changing dirction // check next clockwise direction result if(dir1 == down && dir2 == right){ // down right res = Math.max(res, downL[x][y]); // next clockwise dir down Left }else if(dir1 == down && dir2 == left){ // down left res = Math.max(res, upL[x][y]); }else if(dir1 == up && dir2 == left){ // up left res = Math.max(res, upR[x][y]); }else{ // up right res = Math.max(res, downR[x][y]); } return res; } boolean isInvalid(int x, int y, int[][] g, int req){ return x < 0 || y < 0 || x == g.length || y == g[0].length || g[x][y] != req; } } ```
0
0
['Dynamic Programming', 'Depth-First Search', 'Memoization', 'Java']
0
length-of-longest-v-shaped-diagonal-segment
Python DFS solution
python-dfs-solution-by-idntk-nhgg
IntuitionDFS and pruningCode
idntk
NORMAL
2025-02-16T06:14:15.150464+00:00
2025-02-16T06:14:15.150464+00:00
24
false
# Intuition DFS and pruning # Code ```python3 [] from functools import lru_cache class Solution: def lenOfVDiagonal(self, grid: List[List[int]]) -> int: rows, cols = len(grid), len(grid[0]) states = [] memo = {} res = 0 # Directions (diagonals): # 0: top-left (-1,-1) # 1: top-right (-1,1) # 2: bottom-right (1,1) # 3: bottom-left (1,-1) # +1 on the index == clockwise 90-degree turn dirs = [(-1, -1), (-1, 1), (1, 1), (1, -1)] """ state: (row, col, has_turned, direction, size) has_turned, whether the single turn was already used true/false direction, index from dirs size, size of the curr sequence """ def pack_state(r, c, has_turned, direction) -> int: return (r << 11) | (c << 3) | (has_turned << 2) | direction def get_next(r, c, direction): dr, dc = dirs[direction] return r + dr, c + dc def matches_seq(val, size): return val == (2 if size % 2 == 1 else 0) def avail_moves(r, c, dr, dc) -> int: if dr > 0: avail_r = rows - 1 - r else: avail_r = r if dc > 0: avail_c = cols - 1 - c else: avail_c = c return avail_r if avail_r < avail_c else avail_c # best_turn_extension returns the maximum extra steps (k + available moves after turn) # if we were to move k steps in the current direction and then turn (clockwise) optimally. @lru_cache def best_turn_extension(r, c, d) -> int: dr, dc = dirs[d] a = avail_moves(r, c, dr, dc) new_d = (d + 1) % 4 new_dr, new_dc = dirs[new_d] best = 0 for k in range(a + 1): nr = r + k * dr nc = c + k * dc possible = k + avail_moves(nr, nc, new_dr, new_dc) if possible > best: best = possible return best for r in range(rows): for c in range(cols): if grid[r][c] == 1: for d in range(4): st = pack_state(r, c, False, d) memo[st] = 1 states.append((r, c, False, d, 1)) while states: # DFS r, c, has_turned, direction, size = states.pop() res = max(res, size) # prune branches that can't possibly get better than current best dr, dc = dirs[direction] if has_turned: a = avail_moves(r, c, dr, dc) max_moves = size + a else: a = avail_moves(r, c, dr, dc) bound_same = size + a bound_turn = size + best_turn_extension(r, c, direction) max_moves = max(bound_same, bound_turn) if max_moves <= res: continue n_r, n_c = get_next(r, c, direction) if (0 <= n_r < rows) and (0 <= n_c < cols) and matches_seq(grid[n_r][n_c], size): packed_state = pack_state(n_r, n_c, has_turned, direction) if packed_state not in memo or memo[packed_state] < size + 1: memo[packed_state] = size + 1 states.append((n_r, n_c, has_turned, direction, size + 1)) if not has_turned: # attempt a turn to save the sequence direction = (direction + 1) % 4 has_turned = True n_r, n_c = get_next(r, c, direction) if (0 <= n_r < rows) and (0 <= n_c < cols) and matches_seq(grid[n_r][n_c], size): packed_state = pack_state(n_r, n_c, has_turned, direction) if packed_state not in memo or memo[packed_state] < size + 1: memo[packed_state] = size + 1 states.append((n_r, n_c, has_turned, direction, size + 1)) return res ```
0
0
['Python3']
0
length-of-longest-v-shaped-diagonal-segment
Intuitive DFS with caching top down dp
intuitive-dfs-with-caching-top-down-dp-b-exov
ApproachDFS from valid start points to find longest possible path according to rules. Cache each state (row, column, direction, turn) to avoid repeated work.Cod
stephenip
NORMAL
2025-02-16T06:05:01.373224+00:00
2025-02-16T06:05:01.373224+00:00
35
false
# Approach DFS from valid start points to find longest possible path according to rules. Cache each state (row, column, direction, turn) to avoid repeated work. # Code ```python3 [] class Solution: def lenOfVDiagonal(self, grid: List[List[int]]) -> int: n = len(grid) m = len(grid[0]) moves = [(-1, -1), (-1, 1), (1, 1), (1, -1)] cache = dict() # (r, c, direction, turn) -> max length def dfs(r, c, direction, turn, prev): if (r, c, direction, turn) in cache: return cache[(r, c, direction, turn)] res = 1 # start if grid[r][c] == 1: for newDirection, move in enumerate(moves): dy, dx = move newR = r + dy newC = c + dx if newR in range(n) and newC in range(m) and grid[newR][newC] == 2: res = max(res, 1 + dfs(newR, newC, newDirection, 0, (r, c))) else: # continue in curent direction dy, dx = moves[direction] newR = r + dy newC = c + dx nextChar = 2 if grid[r][c] == 0 else 0 if newR in range(n) and newC in range(m) and grid[newR][newC] == nextChar and (newR, newC) != prev: res = max(res, 1 + dfs(newR, newC, direction, turn, (r, c))) # turn clockwise if turn == 0: newDirection = (direction + 1) % len(moves) dy, dx = moves[newDirection] newR = r + dy newC = c + dx nextChar = 2 if grid[r][c] == 0 else 0 if newR in range(n) and newC in range(m) and grid[newR][newC] == nextChar and (newR, newC) != prev: res = max(res, 1 + dfs(newR, newC, newDirection, 1, (r, c))) cache[(r, c, direction, turn)] = res return res res = 0 for r in range(n): for c in range(m): if grid[r][c] == 1: res = max(res, dfs(r, c, -1, 0, (-1, -1))) return res ```
0
0
['Dynamic Programming', 'Depth-First Search', 'Python3']
0
length-of-longest-v-shaped-diagonal-segment
Straightforward Memoization
straightforward-memoization-by-metaphysi-oa2i
IntuitionThis problem can be solved by using the typical, straightforward DP.ApproachEach DP state is (x, y, d, r, k), where (x, y) is the current cell, d is th
metaphysicalist
NORMAL
2025-02-16T05:57:31.248527+00:00
2025-02-16T05:57:31.248527+00:00
19
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> This problem can be solved by using the typical, straightforward DP. # Approach <!-- Describe your approach to solving the problem. --> Each DP state is `(x, y, d, r, k)`, where `(x, y)` is the current cell, `d` is the current direction, `r` is the destinated value at cell `(x, y)`, and `k` is number of rotations. At each cell `(x, y)`, reject the invalid state and explore two options: - Move to the next cell along the same direction - Rotate the direction and move to the next cell The process can be easily implemented by using memoization. # Complexity - Time complexity: $O(NM)$, where $N$ and $M$ are the height and the width of the grid. The other three parameters, `d`, `r`, and `k`, of the DP state are constant. <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: $O(NM)$ <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] class Solution: def lenOfVDiagonal(self, grid: List[List[int]]) -> int: n, m = len(grid), len(grid[0]) dirs = [(1, 1), (1, -1), (-1, -1), (-1, 1)] @cache def dp(x, y, d, r, k): if k > 1 or x < 0 or x >= n or y < 0 or y >= m: return 0 if grid[x][y] != r: return 0 r = 2 if r < 2 else 0 return max(dp(x + dirs[d][0], y + dirs[d][1], d, r, k), dp(x + dirs[(d + 1) % 4][0], y + dirs[(d + 1) % 4][1], (d + 1) % 4, r, k+1), ) + 1 ans = 0 for i in range(n): for j in range(m): if grid[i][j] == 1: for d in range(4): ans = max(ans, dp(i, j, d, 1, 0)) dp.cache_clear() return ans ```
0
0
['Python3']
0
length-of-longest-v-shaped-diagonal-segment
DFS with memo. Beats 100%.
dfs-with-memo-beats-100-by-takasoft-cpey
Intuition and ApproachThink in terms of the pivot point where we do the clockwise 90-degree turn.Assuming we have a function dfs(row, col, direction) which retu
takasoft
NORMAL
2025-02-16T05:14:39.145534+00:00
2025-02-16T05:29:13.973221+00:00
44
false
# Intuition and Approach Think in terms of the pivot point where we do the clockwise 90-degree turn. Assuming we have a function `dfs(row, col, direction)` which returns a tuple `(count of cells that satisfy the problem condition in the given direction, whether we hit 1 at the end or not)` At each row/col (pivot point), run DFS for all 4 directions. The answer is the max of `count + count2 + (1 if one2 is True else 0)` where: - `count` is the count of cells in the direction where we hit 1 at the end - `count2` is the count of cells in the clockwise 90-degree direction - `one2` is whether we hit 1 at end of the clockwise 90-degree direction We use memo in the DFS to avoid recomputation. # Complexity - Time complexity: O(m * n) - Space complexity: O(m * n) # Code ```python3 [] class Solution: def lenOfVDiagonal(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) dirMap = [(1, 1), (1, -1), (-1, -1), (-1, 1)] memo = [[[None for _ in range(4)] for _ in range(n)] for _ in range(m)] def dfs(r, c, d): if memo[r][c][d]: return memo[r][c][d] dr, dc = dirMap[d] rr, cc = r + dr, c + dc if not (0 <= rr < m and 0 <= cc < n): return (0, False) if grid[rr][cc] == 1: return (1, True) if grid[r][c] == 2 else (0, False) if grid[r][c] == grid[rr][cc]: return (0, False) count, one = dfs(rr, cc, d) memo[r][c][d] = (count + 1, one) return memo[r][c][d] res = 0 for r in range(m): for c in range(n): if grid[r][c] == 1: res = max(res, 1) continue dirLens = [dfs(r, c, 0), dfs(r, c, 1), dfs(r, c, 2), dfs(r, c, 3)] for i, (count, one) in enumerate(dirLens): if one: j = (i - 1) % 4 count2, one2 = dirLens[j] res = max(res, count + count2 + (1 if not one2 else 0)) return res ```
0
0
['Depth-First Search', 'Memoization', 'Python3']
0
length-of-longest-v-shaped-diagonal-segment
PY3
py3-by-harshitasree-i2t0
IntuitionApproachComplexity Time complexity: Space complexity: Code
harshitasree
NORMAL
2025-02-16T04:28:04.170768+00:00
2025-02-16T04:28:04.170768+00:00
13
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] class Solution: def lenOfVDiagonal(self, grid): m = len(grid) n = len(grid[0]) clock = {(1, 1): (1, -1), (1, -1): (-1, -1), (-1, -1): (-1, 1), (-1, 1): (1, 1)} @cache def dp(i, j, dx, dy, done, even): if not (0 <= i < m) or not (0 <= j < n): return 0 if grid[i][j] == 1: return 0 if even and grid[i][j] != 2: return 0 if not even and grid[i][j] != 0: return 0 cdx, cdy = clock[(dx, dy)] return 1 + max(dp(i + dx, j + dy, dx, dy, done, not even), dp(i + cdx, j + cdy, cdx, cdy, True, not even) if not done else 0) res = 0 for i in range(m): for j in range(n): if grid[i][j] == 1: for dx, dy in clock: res = max(res, 1 + dp(i + dx, j + dy, dx, dy, False, True)) return res ```
0
0
['Python3']
0
length-of-longest-v-shaped-diagonal-segment
Tedious 4D DP
tedious-4d-dp-by-whoawhoawhoa-7g9c
IntuitionLow constraints allow us to explore all 1's in the grid. But we still need to memoize the results to pass the threshold.ApproachKeeping 4D DP table for
whoawhoawhoa
NORMAL
2025-02-16T04:24:32.024858+00:00
2025-02-16T04:24:32.024858+00:00
43
false
# Intuition Low constraints allow us to explore all 1's in the grid. But we still need to memoize the results to pass the threshold. # Approach Keeping 4D DP table for indices, direction and number of flips done (only can be 0 or 1). Then we need to tediously keep track of patterns and boundaries. # Complexity - Time complexity: $$O(n * m * 4 * 2)$$ - Space complexity: $$O(n * m * 4 * 2)$$ # Code ```java [] class Solution { public int lenOfVDiagonal(int[][] grid) { Integer[][][][] dp = new Integer[grid.length][grid[0].length][4][2]; int res = 0; for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid[0].length; j++) { if (grid[i][j] == 1) { res = Math.max(res, 1); for (int d = 0; d < 4; d++) { int ni = i + dirs[d][0], nj = j + dirs[d][1]; if (ni >= 0 && nj >= 0 && ni != grid.length && nj != grid[0].length && grid[ni][nj] == 2) { res = Math.max(res, 1 + len(dp, grid, d, ni, nj, 0)); } } } } } return res; } static int[][] dirs = {{1, 1}, {1, -1}, {-1, -1}, {-1, 1}}; static int len(Integer[][][][] dp, int[][] grid, int dir, int i, int j, int flip) { if (dp[i][j][dir][flip] != null) { return dp[i][j][dir][flip]; } int res = 1; int ni = i + dirs[dir][0], nj = j + dirs[dir][1]; if (ni >= 0 && nj >= 0 && ni != grid.length && nj != grid[0].length && (grid[i][j] == 2 && grid[ni][nj] == 0 || grid[i][j] == 0 && grid[ni][nj] == 2)) { res = 1 + len(dp, grid, dir, ni, nj, flip); } if (flip == 0) { int ndir = (dir + 1) % 4; ni = i + dirs[ndir][0]; nj = j + dirs[ndir][1]; if (ni >= 0 && nj >= 0 && ni != grid.length && nj != grid[0].length && (grid[i][j] == 2 && grid[ni][nj] == 0 || grid[i][j] == 0 && grid[ni][nj] == 2)) { res = Math.max(res, 1 + len(dp, grid, ndir, ni, nj, 1)); } } return dp[i][j][dir][flip] = res; } } ```
0
0
['Dynamic Programming', 'Memoization', 'Java']
0
length-of-longest-v-shaped-diagonal-segment
O(R * C) | Top down DP
or-c-top-down-dp-by-sergey_chebotarev-lx6o
IntuitionAs usual in these types of questions, we may try and compute the answer for all grid cells if we do it without repeated calculations.If we naively try
sergey_chebotarev
NORMAL
2025-02-16T04:24:04.740237+00:00
2025-02-16T04:24:04.740237+00:00
32
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> As usual in these types of questions, we may try and compute the answer for all grid cells if we do it without repeated calculations. If we naively try to recursovely process every branch outgoing from every start cell, we may get a TLE error. The reason is that the branches may overlap because of clockwise turns. That would lead to an exponential number of repeated calls. To avoid this we may want to cache processing results for every cell and re-use them when needed. Top-down DP comes in handy here. We only need to define the state of the cell we're going to process and cache. The parameters that affect the result are: cell coordinates, our movement direction, how many turns are left (1 or 0) and the expected value of this cell. # Approach <!-- Describe your approach to solving the problem. --> - Traverse every cell in the grid - For every start cell with value '1' try exploring all 4 possible branches for the 4 diagonal directions. - The function that calculates the maximal branch length does the following: - For base invalid cases, when we move outside the grid or have a value mismatch, we return 0 - Otherwise, the base length is 1 plus the length of the branch starting at the next ceil. Here we have 2 potential next cells: - A cell we reach if we move according to the current direction - A cell we reach if we make a clockwise turn - We need to pick the longest of these two options. # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> $$O(R * C * 16) = O(R * C)$$ Where R is the number of rows, C is the number of columns and 16 and the number of parameter combinations (4 directions, 2 turn states, 2 expected values). - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> $$O(R * C)$$ Same as time complexity. We cache all the DP states. # Code ```python3 [] # directions are placed clockwise: each next is a 90-degree turn to the right moves = [(-1, 1), (1, 1), (1, -1), (-1, -1)] def lenOfVDiagonal(self, grid: List[List[int]]) -> int: rows = len(grid) cols = len(grid[0]) @cache def get_max_sequence(r, c, move, turns, expected): if not(0 <= r < rows and 0 <= c < cols) or grid[r][c] != expected: return 0 next_expected = 2 - expected # try same direction result = 1 + get_max_sequence(r + move[0], c + move[1], move, turns, next_expected) if turns > 0: # try turning clockwise move_idx = moves.index(move) next_move = moves[(move_idx + 1) % len(moves)] turn_result = 1 + get_max_sequence(r + next_move[0], c + next_move[1], \ next_move, turns - 1, next_expected) result = max(turn_result, result) return result # try all valid start positons result = 0 for r in range(rows): for c in range(cols): if grid[r][c] != 1: continue for dr, dc in moves: candidate = 1 + get_max_sequence(r + dr, c + dc, (dr, dc), 1, 2) # print([r, c], "dir=", (dr, dc), "res=", candidate) result = max(candidate, result) return result ```
0
0
['Dynamic Programming', 'Recursion', 'Memoization', 'Python3']
0
length-of-longest-v-shaped-diagonal-segment
Python Solution: Achieve About 6000ms and 700mb
python-solution-achieve-about-6000ms-and-3o5s
IntuitionThis solution use DFS (or BFS? I am not very familiar with the term). It start by exploring all possible paths from each of element 1, and avoid the me
SatriaWidy26
NORMAL
2025-02-16T04:23:41.943597+00:00
2025-02-16T04:23:41.943597+00:00
12
false
# Intuition This solution use DFS (or BFS? I am not very familiar with the term). It start by exploring all possible paths from each of element ```1```, and avoid the memory and time limit (very narrowly) by storing the explored path in a hash table (dictionary). The last part is done out of desperation, and it blows up the memory usage. In conclusion, you probably do not want to follow this solution if you are looking for a way to optimise the solution. But anyway, I will still post this solution. # Approach - Look for ```i,j``` such that ```grid[i][j] == 1```. - Start exploring each possible path (those that contain element ```2```) diagonal with respect to ```grid[i][j]```. For each possible path, assign ```length``` (to indicate the length of the path), ```state``` (to indicate whether the next pos should have element ```2``` or ```0```), ```dir``` (to indicate the direction of traversal and prevent turning in the wrong direction), and ```state_dir``` (to prevent overdoing the turn). - The ```dir``` here use the following convention: (left, up) is ```1```, (right, up) is ```2```, (left, down) is ```3```, and (right, down) is ```4```. Therefore, the possible turn in ```1-->2-->4-->3-->1```. The turning is made possible by using ```elif (dir == j or dir == 0) and state_dir < 1``` with ```i,j``` following the ```j-->i``` convention above. - For every traversal, they will return the maximum length as the output, building up to the maximum length of possible paths. - We use python dictionary to store path that have been traversed. As the ```state``` variable is redundant (if we traverse those position, it means the state is already correct), and ```length``` would be our argument, we don't need to put them into the dictionary keys. # Complexity - Time complexity: Each pair ```i, j``` can be traversed up to 8 times (depending on the ```dir``` and ```state_dir``` when they are traversed), but unless I am misunderstood (which is very possible), they will not be traversed more than that. So I guess it maybe is $$O(n^2)$$. - Space complexity: With the same reason, maybe $$O(n^2)$$ (a very heavy at that). # Code ```python3 [] class Solution: def lenOfVDiagonal(self, grid: List[List[int]]) -> int: n = len(grid) m = len(grid[0]) hashmap = {} def dfs(i, j, length, state, dir, state_dir): if (i, j, dir, state_dir) in hashmap: return length + hashmap[(i, j, dir, state_dir)] maxim = length if i - 1 > -1 and j - 1 > -1 and grid[i-1][j-1] == state: if dir == 1: maxim = max(maxim, bfs(i-1, j-1, length+1, 2 - state, 1, state_dir)) elif (dir == 3 or dir == 0) and state_dir < 1: maxim = max(maxim, bfs(i-1, j-1, length+1, 2 - state, 1, state_dir + 1)) if i - 1 > -1 and j + 1 < m and grid[i-1][j+1] == state: if dir == 2: maxim = max(maxim, bfs(i-1, j+1, length+1, 2 - state, 2, state_dir)) elif (dir == 1 or dir == 0) and state_dir < 1: maxim = max(maxim, bfs(i-1, j+1, length+1, 2 - state, 2, state_dir + 1)) if i + 1 < n and j - 1 > -1 and grid[i+1][j-1] == state: if dir == 3: maxim = max(maxim, bfs(i+1, j-1, length+1, 2 - state, 3, state_dir)) elif (dir == 4 or dir == 0) and state_dir < 1: maxim = max(maxim, bfs(i+1, j-1, length+1, 2 - state, 3, state_dir + 1)) if i + 1 < n and j + 1 < m and grid[i+1][j+1] == state: if dir == 4: maxim = max(maxim, bfs(i+1, j+1, length+1, 2 - state, 4, state_dir)) elif (dir == 2 or dir == 0) and state_dir < 1: maxim = max(maxim, bfs(i+1, j+1, length+1, 2 - state, 4, state_dir + 1)) hashmap.update({(i, j, dir, state_dir): maxim - length}) return maxim maximum = 0 for i in range(n): for j in range(m): if grid[i][j] == 1: maximum = max(maximum, dfs(i, j, 1, 2, 0, -1)) return maximum ```
0
0
['Python3']
0
length-of-longest-v-shaped-diagonal-segment
Easy Direct Recursion Brute Force
easy-direct-recursion-brute-force-by-sir-jqb2
IntuitionThe problem requires finding the longest V-shaped diagonal segment in a 2D grid. The segment starts with 1 and follows a sequence of 2, 0, 2, 0, etc. T
Sirjit_Saxena
NORMAL
2025-02-16T04:11:00.836246+00:00
2025-02-16T04:11:00.836246+00:00
33
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> The problem requires finding the longest V-shaped diagonal segment in a 2D grid. The segment starts with 1 and follows a sequence of 2, 0, 2, 0, etc. The segment can make at most one 90-degree turn while maintaining the sequence. The goal is to find the length of the longest such segment. # Approach <!-- Describe your approach to solving the problem. --> 1. Start at Each Cell: We'll go through every cell in the grid. If a cell contains the number 1, it could be the starting point of a V-shaped diagonal segment. 2. Explore Directions: From each starting cell, we'll explore in four diagonal directions: Top-left to bottom-right Top-right to bottom-left Bottom-left to top-right Bottom-right to top-left 3. Follow the Sequence: As we move in a direction, we'll check if the next cell follows the required sequence: 1, 2, 0, 2, 0, and so on. If it does, we continue moving in that direction. 4. Allow One Turn: During the sequence, we're allowed to make at most one 90-degree turn. After the turn, we continue checking the sequence in the new direction. 5. Track the Longest Segment: We'll keep track of the length of the longest valid segment we find while exploring all possible starting points and directions. 6. Return the Result: Finally, we'll return the length of the longest V-shaped diagonal segment. If no valid segment is found, we'll return 0. # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> O(n * m) (linear in terms of the grid size). - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> O(max(n, m)) (due to recursion depth). # Code ```cpp [] class Solution { public: int f(vector<vector<int>>& grid, int parent, int pi, int pj, bool turned, int d, int& n, int& m) { int pi2 = pi, pj2 = pj; if (d == 0) pi--, pj--; if (d == 1) pi--, pj++; if (d == 2) pi++, pj++; if (d == 3) pi++, pj--; int a = 1, b = 1; if (pi < n && pi >= 0 && pj < m && pj >= 0) { if ((parent == 1 && grid[pi][pj] == 2) || (parent == 2 && grid[pi][pj] == 0) || (parent == 0 && grid[pi][pj] == 2)) { a = 1 + f(grid, grid[pi][pj], pi, pj, turned, d, n, m); } } if (turned == false) { d = (d + 1) % 4, pi = pi2, pj = pj2; if (d == 0) pi--, pj--; if (d == 1) pi--, pj++; if (d == 2) pi++, pj++; if (d == 3) pi++, pj--; if (pi < n && pi >= 0 && pj < m && pj >= 0) { if ((parent == 1 && grid[pi][pj] == 2) || (parent == 2 && grid[pi][pj] == 0) || (parent == 0 && grid[pi][pj] == 2)) { b = 1 + f(grid, grid[pi][pj], pi, pj, true, d, n, m); } } } return max(a, b); } int lenOfVDiagonal(vector<vector<int>>& grid) { int n = grid.size(), m = grid[0].size(), q = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (grid[i][j] == 1) { for (int d = 0; d < 4; d++) q = max(q, f(grid, grid[i][j], i, j, false, d, n, m)); } } } return q; } }; ```
0
0
['Recursion', 'C++']
0
length-of-longest-v-shaped-diagonal-segment
Brute force
brute-force-by-uurxsh19ls-qpun
The problem uses brute force instead of moving along the edges with the directions {1, 0}, {0, 1}, {-1, 0}, {0, -1}, it moves diagonally with the directions {1,
xiaochaomeng
NORMAL
2025-02-16T04:05:51.775654+00:00
2025-02-16T04:05:51.775654+00:00
21
false
**The problem uses brute force instead of moving along the edges with the directions {1, 0}, {0, 1}, {-1, 0}, {0, -1}, it moves diagonally with the directions {1, 1}, {-1, 1}, {-1, -1}, {1, -1}, which is the only improvement — moving diagonally** # Code ```cpp [] class Solution { public: int lenOfVDiagonal(vector<vector<int>>& grid) { int n = grid.size(), m = grid[0].size(); vector<vector<int>> jorvexalin = grid; int best = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (grid[i][j] == 1) { vector<pair<int,int>> direct = {{1,1}, {1,-1}, {-1,1}, {-1,-1}}; for (auto &d : direct) { int cur = dfs(i, j, d.first, d.second, false, 1, jorvexalin); best = max(best, cur); } } } } return best; } int dfs(int i, int j, int dx, int dy, bool turned, int p, vector<vector<int>> &g) { int n = g.size(), m = g[0].size(); int exp; if(p == 0) exp = 1; else exp = (p % 2 == 1) ? 2 : 0; int best = 0; int ni = i + dx, nj = j + dy; if (ni >= 0 && nj >= 0 && ni < n && nj < m && g[ni][nj] == ((p % 2 == 1) ? 2 : 0)) { best = max(best, dfs(ni, nj, dx, dy, turned, p+1, g)); } if (!turned) { int ndx = dy, ndy = -dx; ni = i + ndx; nj = j + ndy; if (ni >= 0 && nj >= 0 && ni < n && nj < m && g[ni][nj] == ((p % 2 == 1) ? 2 : 0)) { best = max(best, dfs(ni, nj, ndx, ndy, true, p+1, g)); } } return best + 1; } }; ```
0
0
['C++']
0
length-of-longest-v-shaped-diagonal-segment
Straightforward DP
straightforward-dp-by-jjzin-gm5u
IntuitionDFS = EZMONEYApproachStraightforward DP, keep track of current direction, whether or not you've used up your turn as well as which element is next 0 or
JJZin
NORMAL
2025-02-16T04:04:04.157426+00:00
2025-02-16T04:04:04.157426+00:00
45
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> DFS = EZMONEY # Approach <!-- Describe your approach to solving the problem. --> Straightforward DP, keep track of current direction, whether or not you've used up your turn as well as which element is next 0 or 2 # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> O(n * m) - Space complexity: O(n * m) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] class Solution: def lenOfVDiagonal(self, grid: List[List[int]]) -> int: dx = [-1, 1, 1, -1] dy = [1, 1, -1, -1] tarjan = defaultdict(int) tarjan[0] = 2 tarjan[1] = 0 @cache def recourse(i, x, direction, used_up, theta = 0): theta %= 2 if i >= len(grid) or i < 0: return 0 if x >= len(grid[0]) or x < 0: return 0 if grid[i][x] != tarjan[theta % 2]: return 0 if used_up: return 1 + recourse(i + dx[direction], x + dy[direction],direction, True, theta + 1) a = 1 c = 1 if (i + dx[direction]) < len(grid) and i + dx[direction] >= 0: a = 1 + recourse(i + dx[direction], x + dy[direction],direction, False, theta + 1) # b = 1 + recourse(i + dx[(direction - 1) % 4], x + dy[(direction - 1) % 4],(direction - 1) % 4, True, theta + 1) nx = i + dx[(direction + 1) % 4] ny = x + dy[(direction + 1) % 4] if nx < len(grid) and ny >= 0: c = 1 + recourse(i + dx[(direction + 1) % 4], x + dy[(direction + 1) % 4],(direction + 1) % 4, True, theta + 1) return a if a > c else c ans = 0 for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] != 1: continue for ea in range(4): ans = max(ans, 1 + recourse(i + dx[ea], j + dy[ea], ea, False)) recourse.cache_clear() return ans ```
0
0
['Python3']
0
length-of-longest-v-shaped-diagonal-segment
Intuitive DFS and precomputation || O(nm)
intuitive-dfs-and-precomputation-onm-by-ua45u
IntuitionPrecomputation:We precompute the lengths of valid sequences in four diagonal directions: up-left, up-right, down-left, and down-right. This helps in ef
aashutosh148
NORMAL
2025-02-16T04:03:56.767683+00:00
2025-02-16T04:03:56.767683+00:00
106
false
# Intuition Precomputation: We precompute the lengths of valid sequences in four diagonal directions: up-left, up-right, down-left, and down-right. This helps in efficiently calculating the length of sequences when a turn is taken. DFS Traversal: For each cell containing 1, we perform a DFS in all four diagonal directions to explore valid sequences. During the DFS, we allow at most one 90-degree turn by combining the current sequence length with the precomputed length in the opposite direction. Combining Results: We keep track of the maximum length found during the DFS traversal, ensuring that the sequence follows the rules of the V-shaped segment. # Complexity - Time complexity: O(n^2) - Space complexity: O(n^2) # Code ```cpp [] class Solution { public: int n, m; vector<vector<int>> grid; vector<vector<int>> upLeft, upRight, downLeft, downRight; int lenOfVDiagonal(vector<vector<int>>& grid) { this->grid = grid; n = grid.size(); m = grid[0].size(); upLeft = vector<vector<int>>(n, vector<int>(m, 1)); upRight = vector<vector<int>>(n, vector<int>(m, 1)); downLeft = vector<vector<int>>(n, vector<int>(m, 1)); downRight = vector<vector<int>>(n, vector<int>(m, 1)); for (int i = 1; i < n; i++) { for (int j = 0; j < m; j++) { if (j - 1 >= 0 && ((grid[i][j] == 0 && grid[i-1][j-1] == 2) || (grid[i][j] == 2 && grid[i-1][j-1] == 0))) { upLeft[i][j] += upLeft[i-1][j-1]; } if (j + 1 < m && ((grid[i][j] == 0 && grid[i-1][j+1] == 2) || (grid[i][j] == 2 && grid[i-1][j+1] == 0))) { upRight[i][j] += upRight[i-1][j+1]; } } } for (int i = n - 2; i >= 0; i--) { for (int j = 0; j < m; j++) { if (j - 1 >= 0 && ((grid[i][j] == 0 && grid[i+1][j-1] == 2) || (grid[i][j] == 2 && grid[i+1][j-1] == 0))) { downLeft[i][j] += downLeft[i+1][j-1]; } if (j + 1 < m && ((grid[i][j] == 0 && grid[i+1][j+1] == 2) || (grid[i][j] == 2 && grid[i+1][j+1] == 0))) { downRight[i][j] += downRight[i+1][j+1]; } } } int maxLen = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (grid[i][j] == 1) { maxLen = max(maxLen, 1); int len1 = dfs(i, j, 0); int len2 = dfs(i, j, 1); int len3 = dfs(i, j, 2); int len4 = dfs(i, j, 3); int len = max({len1, len2, len3, len4}); maxLen = max(maxLen, len); } } } return maxLen; } int dfs(int i, int j, int dir) { if (i < 0 || i >= n || j < 0 || j >= m) return 0; int nextVal = (grid[i][j] == 1) ? 2 : (grid[i][j] == 2) ? 0 : 2; int len = 1; int ans = 0; if (dir == 0) { if (i - 1 >= 0 && j - 1 >= 0 && grid[i-1][j-1] == nextVal) { ans = max(ans, len + upRight[i-1][j-1]); len += dfs(i-1, j-1, dir); ans = max(ans, len); } } else if (dir == 1) { if (i - 1 >= 0 && j + 1 < m && grid[i-1][j+1] == nextVal) { ans = max(ans, len + downRight[i-1][j+1]); len += dfs(i-1, j+1, dir); ans = max(ans, len); } } else if (dir == 2) { if (i + 1 < n && j - 1 >= 0 && grid[i+1][j-1] == nextVal) { ans = max(ans, len + upLeft[i+1][j-1]); len += dfs(i+1, j-1, dir); ans = max(ans, len); } } else if (dir == 3) { if (i + 1 < n && j + 1 < m && grid[i+1][j+1] == nextVal) { ans = max(ans, len + downLeft[i+1][j+1]); len += dfs(i+1, j+1, dir); ans = max(ans, len); } } return ans; } }; ```
0
0
['Depth-First Search', 'Matrix', 'C++']
1
length-of-longest-v-shaped-diagonal-segment
bruteforce
bruteforce-by-akbc-o6g2
IntuitionApproachComplexity Time complexity: Space complexity: Code
akbc
NORMAL
2025-02-16T04:01:42.261716+00:00
2025-02-16T04:01:42.261716+00:00
31
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] class Solution: def lenOfVDiagonal(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) @cache def dp(i, j, val, direction, turn): if i < 0 or i >= m or j < 0 or j >= n: return 0 if grid[i][j] != val: return 0 val1 = 2 if val == 0 else 0 if direction == 0: if turn: return 1 + max( dp(i - 1, j - 1, val1, 0, True), dp(i - 1, j + 1, val1, 1, False), ) return 1 + dp(i - 1, j - 1, val1, 0, turn) elif direction == 1: if turn: return 1 + max( dp(i - 1, j + 1, val1, 1, True), dp(i + 1, j + 1, val1, 2, False), ) return 1 + dp(i - 1, j + 1, val1, 1, turn) elif direction == 2: if turn: return 1 + max( dp(i + 1, j + 1, val1, 2, turn), dp(i + 1, j - 1, val1, 3, False), ) return 1 + dp(i + 1, j + 1, val1, 2, turn) else: if turn: return 1 + max( dp(i + 1, j - 1, val1, 3, turn), dp(i - 1, j - 1, val1, 0, False), ) return 1 + dp(i + 1, j - 1, val1, 3, turn) ans = 0 for i in range(m): for j in range(n): if grid[i][j] == 1: ans = max( ans, 1 + max( dp(i - 1, j - 1, 2, 0, True), dp(i - 1, j + 1, 2, 1, True), dp(i + 1, j + 1, 2, 2, True), dp(i + 1, j - 1, 2, 3, True), ), ) return ans ```
0
0
['Python3']
0
shortest-distance-to-a-character
[C++/Java/Python] 2-Pass with Explanation
cjavapython-2-pass-with-explanation-by-l-w2de
Solution 1: Record the Position\n\nInitial result array.\nLoop twice on the string S.\nFirst forward pass to find shortest distant to character on left.\nSecond
lee215
NORMAL
2018-04-22T03:02:07.605639+00:00
2020-02-03T17:21:00.519833+00:00
39,974
false
# Solution 1: Record the Position\n\nInitial result array.\nLoop twice on the string `S`.\nFirst forward pass to find shortest distant to character on left.\nSecond backward pass to find shortest distant to character on right.\n<br>\n\nIn python solution, I merged these two `for` statement.\nWe can do the same in C++/Java by:\n```\nfor (int i = 0; i >= 0; res[n-1] == n ? ++i : --i)\n```\nBut it will become less readable.\n<br>\n\nTime complexity `O(N)`\nSpace complexity `O(N)` for output\n<br>\n\n**C++**\n```cpp\n vector<int> shortestToChar(string S, char C) {\n int n = S.size(), pos = -n;\n vector<int> res(n, n);\n for (int i = 0; i < n; ++i) {\n if (S[i] == C) pos = i;\n res[i] = i - pos;\n }\n for (int i = pos - 1; i >= 0; --i) {\n if (S[i] == C) pos = i;\n res[i] = min(res[i], pos - i);\n }\n return res;\n }\n```\n\n**Java**\n```java\n public int[] shortestToChar(String S, char C) {\n int n = S.length(), pos = -n, res[] = new int[n];\n for (int i = 0; i < n; ++i) {\n if (S.charAt(i) == C) pos = i;\n res[i] = i - pos;\n }\n for (int i = pos - 1; i >= 0; --i) {\n if (S.charAt(i) == C) pos = i;\n res[i] = Math.min(res[i], pos - i);\n }\n return res;\n }\n```\n**Python**\n```py\n def shortestToChar(self, S, C):\n n, pos = len(S), -float(\'inf\')\n res = [n] * n\n for i in range(n) + range(n)[::-1]:\n if S[i] == C:\n pos = i\n res[i] = min(res[i], abs(i - pos))\n return res\n```\n<br><br>\n\n# Solution 2: DP\nAnother idea is quite similar and has a sense of DP.\n<br>\n**C++:**\n```cpp\n vector<int> shortestToChar2(string S, char C) {\n int n = S.size();\n vector<int> res(n);\n for (int i = 0; i < n; ++i)\n res[i] = S[i] == C ? 0 : n;\n for (int i = 1; i < n; ++i)\n res[i] = min(res[i], res[i - 1] + 1);\n for (int i = n - 2; i >= 0; --i)\n res[i] = min(res[i], res[i + 1] + 1);\n return res;\n }\n```\n\n**Java:**\n```java\n public int[] shortestToChar(String S, char C) {\n int n = S.length();\n int[] res = new int[n];\n for (int i = 0; i < n; ++i)\n res[i] = S.charAt(i) == C ? 0 : n;\n for (int i = 1; i < n; ++i)\n res[i] = Math.min(res[i], res[i - 1] + 1);\n for (int i = n - 2; i >= 0; --i)\n res[i] = Math.min(res[i], res[i + 1] + 1);\n return res;\n }\n```\n**Python:**\n```py\n def shortestToChar(self, S, C):\n n = len(S)\n res = [0 if c == C else n for c in S]\n for i in range(1, n):\n res[i] = min(res[i], res[i - 1] + 1)\n for i in range(n - 2, -1, -1):\n res[i] = min(res[i], res[i + 1] + 1)\n return res\n```
412
3
[]
47
shortest-distance-to-a-character
Concise java solution with detailed explanation. Easy understand!!!
concise-java-solution-with-detailed-expl-3k3v
```\n/* "loveleetcode" "e"\n * 1. put 0 at all position equals to e, and max at all other position\n * we will get [max, max, max, 0, max, 0, 0, max, max,
self_learner
NORMAL
2018-04-24T06:07:54.749986+00:00
2018-09-04T23:45:30.816157+00:00
6,082
false
```\n/** "loveleetcode" "e"\n * 1. put 0 at all position equals to e, and max at all other position\n * we will get [max, max, max, 0, max, 0, 0, max, max, max, max, 0]\n * 2. scan from left to right, if =max, skip, else dist[i+1] = Math.min(dp[i] + 1, dp[i+1]), \n * we can get [max, max, max, 0, 1, 0, 0, 1, 2, 3, 4, 0]\n * 3. scan from right to left, use dp[i-1] = Math.min(dp[i] + 1, dp[i-1])\n * we will get[3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0] \n */\nclass Solution {\n public int[] shortestToChar(String s, char c) {\n int n = s.length();\n int[] dist = new int[n];\n for (int i = 0; i < n; i++) {\n if (s.charAt(i) == c) continue;\n dist[i] = Integer.MAX_VALUE;\n }\n for (int i = 0; i < n-1; i++) {\n if (dist[i] == Integer.MAX_VALUE) continue;\n else dist[i + 1] = Math.min(dist[i+1], dist[i] + 1);\n }\n for (int i = n-1; i > 0; i--) {\n dist[i-1] = Math.min(dist[i-1], dist[i] + 1);\n }\n return dist; \n }\n}\n
63
1
[]
8
shortest-distance-to-a-character
C++ | Two Pass | O(n), 0ms, Beats 100% | Easy Explanation
c-two-pass-on-0ms-beats-100-easy-explana-so05
EXPLANATION\n- First, iterate the string \'s\' and store the indexes of \'c\' present in \'s\' into an array or vector ( here vector<int>ioc ) .\n- Make a left
akash2099
NORMAL
2021-02-07T11:48:08.601560+00:00
2021-02-07T12:19:53.128278+00:00
5,296
false
**EXPLANATION**\n- First, iterate the string **\'s\'** and store the **indexes** of **\'c\'** present in \'s\' into an array or vector ( here **```vector<int>ioc```** ) .\n- Make a **left** variable for storing the index of **left nearest \'c\'** in **```ioc```** and a **right** variable for storing the index of **right nearest \'c\'** in **```ioc```**. Initially, **```left=0```** and **```right=0```**, that is keeping the first index of **```ioc```**.\n- Then, iterate string **\'s\'** again and at each iteration check if *current index* crosses **```ioc[right]```** ( that is *index of \'c\' present in ioc pointed by right* ) then we need to make **```left = right```** and **```right=right+1```**.\n- Also, at each iteration find the **minimum** value between the *following two* and store it in **```ans[i]```**.\n\t- **absolute value of (right nearest \'c\' - current index)** represented by **``` abs(ioc[right]-i)```** \n\t- **absolute value of (left nearest \'c\' - current index)** represented by **``` abs(ioc[left]-i)```**\n- Return **ans**.\n\n\n**CODE IMPLEMENTATION**\n```\nclass Solution {\npublic:\n vector<int> shortestToChar(string s, char c) {\n vector<int> ioc; // vector for storing the indexed of c present in s\n int n=s.length();\n \n vector<int>ans(n); // answer vector\n \n for(int i=0;i<n;++i){\n if(s[i]==c) \n ioc.push_back(i);\n }\n \n int m=ioc.size(); // size of ioc vector\n int left=0,right=0;\n \n for(int i=0;i<n;++i){\n \n // if current index has crossed ioc[right] then,\n // we need to make the current left to right and \n // increment current right for pointing to next index of ioc vector ( if exists )\n if(i>ioc[right]){\n left=right;\n if(right<m-1)\n ++right;\n }\n \n // difference = min(abs(right nearest \'c\' - curr index),abs(left nearest \'c\' - curr index))\n ans[i]=min(abs(ioc[right]-i),abs(ioc[left]-i)); \n\n }\n \n return ans;\n }\n};\n```\n\nConsidering *\'n\'* to be the size of the maximum size of the string *\'s\'*.\n\n**TIME COMPLEXITY**\nO(n+n)=**O(n)** [ *For iterating the string two times* ]\n\n**SPACE COMPLEXITY**\n**O(n)** [ *In worst case, all characters of \'s\' is \'c\', at that time ( number of \'c\' in \'s\' = size of \'s\' )* ]
51
3
['C']
7
shortest-distance-to-a-character
[javascript] 2 pass simple solution with explanation
javascript-2-pass-simple-solution-with-e-pyqd
The problem becomes really simple if we consider the example.\njs\n0 1 2 3 4 5 6 7 8 9 10 11\nl o v e l e e t c o d e\n\nWhat is the shortest distance for inde
bt4r9
NORMAL
2021-02-07T10:57:02.200229+00:00
2021-02-08T08:27:14.818458+00:00
1,973
false
The problem becomes really simple if we consider the example.\n```js\n0 1 2 3 4 5 6 7 8 9 10 11\nl o v e l e e t c o d e\n```\nWhat is the shortest distance for index `9` if the character is `e`?\nThe closest `e` from the left side has the index `6`.\n`9 - 6 = 3`\nThe closest `e` from the right side has the index `11`.\n`11 - 9 = 2`\nThe minimum distance between them is 2, so the answer is 2. Can we do it for any index?\nYes we can, all we need to do is to keep track of the previous character index while iterating from the left to the right and vice versa. The only edge case here is that initially we could possibly don\'t have a previous index, so to mitigate it for such indecies we can put the shortest distance for them as Infinity and once we complete 2 passes at least one non-Infinity value for each index should exist.\nLet\'s consider the example again.\n```js\ncharacter = "e"\n\nindex | 0 1 2 3 4 5 6 7 8 9 10 11\nchar | l o v e l e e t c o d e\n// shortest distance from left to right\nl -> r | I I I 0 1 0 0 1 2 3 4 0 // I = Infinity\n// shortest distance from right to left\nl <- r | 3 2 1 0 1 0 0 4 3 2 1 0\n// the minimum between them is the answer\nresult | 3 2 1 0 1 0 0 1 2 2 1 0\n```\n\n```js\nvar shortestToChar = function(s, c) {\n let n = s.length;\n let res = [];\n \n let prev = Infinity;\n\n for (let i = 0; i < s.length; i++) {\n if (s[i] === c) prev = i;\n res[i] = Math.abs(prev - i);\n }\n\n prev = Infinity;\n\n for (let i = n - 1; i >= 0; i--) {\n if (s[i] === c) prev = i;\n res[i] = Math.min(res[i], prev - i);\n }\n\n return res;\n}\n```\n\nTime complexity: O(n)\nSpace complexity: O(n)
31
0
['JavaScript']
1
shortest-distance-to-a-character
[Python] O(n) solution, explained
python-on-solution-explained-by-dbabiche-xhrk
What we need to do in this problem is to iterate our data two times: one time from left to right and second time from right to left. Let us use auxilary functio
dbabichev
NORMAL
2021-02-07T10:14:47.353528+00:00
2021-02-08T08:17:31.209152+00:00
3,024
false
What we need to do in this problem is to iterate our data two times: one time from left to right and second time from right to left. Let us use auxilary function `letter_get(letter, dr)`, where `dr` is direction: `+1` for left->right traversal and `-1` for right -> left traversal.\n\nHow this function will work? We initialize it with zeroes first and we keep `cur` value, which represents the last place where we meet symbol `letter`. We traverse string, check each symbol and if it is equal to `letter`, we update `cur` place. We put `abs(i - cur)` to result: this is distance between current place and last place where we meet symbol `letter`.\n\nFinally, we apply our function twice for two directions and choose the smallest distance. Note also that we initialized `curr = -n`, because in this case we will have distances `>=n` for symbols for places, where we do not have elements equal to `letter` before, and this value is bigger than all possible values in answer, so it works as infinity here.\n\n**Complexity**: time complexity is `O(n)`, space complexity is `O(n)` as well.\n\n```\nclass Solution:\n def shortestToChar(self, S, C):\n def letter_get(letter, dr):\n n = len(S)\n res, cur = [0]*n, -n\n for i in range(n)[::dr]:\n if S[i] == letter: cur = i\n res[i] = abs(i - cur)\n return res\n \n return [min(x,y) for x,y in zip(letter_get(C, 1), letter_get(C, -1))]\n```\n\nIf you have any questions, feel free to ask. If you like solution and explanations, please **Upvote!**
30
1
[]
4
shortest-distance-to-a-character
C++ Simple Solution 0 ms faster than 100%
c-simple-solution-0-ms-faster-than-100-b-f5r0
\nclass Solution {\npublic:\n vector<int> shortestToChar(string s, char c) {\n vector<int> res;\n int prev_char = -s.size();\n for (int
yehudisk
NORMAL
2021-02-07T08:56:21.290683+00:00
2021-02-07T09:12:18.036364+00:00
1,739
false
```\nclass Solution {\npublic:\n vector<int> shortestToChar(string s, char c) {\n vector<int> res;\n int prev_char = -s.size();\n for (int i = 0; i < s.size(); i++) {\n if (s[i] == c)\n prev_char = i;\n res.push_back(i - prev_char);\n }\n\n for (int i = prev_char; i >= 0; i--) {\n if (s[i] == c)\n prev_char = i;\n res[i] = min(res[i], prev_char - i);\n }\n return res;\n }\n};\n```\n**Like it? please upvote...**
22
2
['C']
2
shortest-distance-to-a-character
✅C++ solution || Simple || Easy-understanding
c-solution-simple-easy-understanding-by-kabq1
Explanation:\n create two vectors :- position and answer.\n Traverse the string and collect all the position of given char using the position vector.\n Now trav
ayushsenapati123
NORMAL
2022-06-20T08:16:17.474223+00:00
2022-06-20T08:16:17.474262+00:00
2,754
false
**Explanation:**\n* create two vectors :- `position` and `answer`.\n* Traverse the string and collect all the position of given char using the `position` vector.\n* Now traverse the string and find the shortest distance from the given char to all given positions.\n* Keep pushing the distance to the `answer` vector and at last return it.\n```\nclass Solution {\npublic:\n vector<int> shortestToChar(string s, char c) {\n vector<int> position;\n vector<int> answer;\n \n for(int i=0; i<s.size(); i++)\n {\n if(s[i]==c)\n position.push_back(i);\n }\n \n for(int i=0; i<s.size(); i++)\n {\n int shortest_dist = INT_MAX;\n for(int j=0; j<position.size(); j++)\n {\n shortest_dist = min(shortest_dist, abs(i-position[j]));\n }\n answer.push_back(shortest_dist);\n }\n \n return answer;\n }\n};\n```\n**Please upvote if you find the solution useful, means a lot.**
21
0
['C', 'C++']
1
shortest-distance-to-a-character
Python O(n) by propagation 85%+ [w/ Diagram]
python-on-by-propagation-85-w-diagram-by-i8mv
Python O(n) by propagation\n\n---\n\nHint:\n\nImagine parameter C as a flag on the line.\n\nThink of propagation technique:\n1st-pass iteration propagates dista
brianchiang_tw
NORMAL
2020-03-03T03:13:33.691717+00:00
2023-12-18T09:29:25.181152+00:00
2,572
false
Python O(n) by propagation\n\n---\n\n**Hint**:\n\nImagine parameter C as a flag on the line.\n\nThink of propagation technique:\n**1st-pass** iteration **propagates distance** from C on the **left hand side**\n**2nd-pass** iteration **propagates distance** from C on the **right hand side** with min( 1st-pass result, 2nd-pass propagation distance ) in order to update with shortest path.\n\n---\n\n**Abstract Model**:\n![image](https://assets.leetcode.com/users/brianchiang_tw/image_1583205184.png)\n\n\n---\n\n**Implementation**:\n\n```\nclass Solution:\n def shortestToChar(self, S: str, C: str) -> List[int]:\n \n shortest_dist = []\n size = len(S)\n \n if size == 1:\n # Quick response for single character test case\n # Description guarantee that character C must exist in string S\n return [0]\n \n \n # Propagate distance from left to right\n for idx, char in enumerate(S):\n \n if char == C:\n shortest_dist.append(0)\n else:\n if idx == 0:\n shortest_dist.append( size )\n else:\n # Propagate distance from C on left hand side\n shortest_dist.append( shortest_dist[-1] + 1)\n \n \n \n # Propagate distance from right to left \n for idx in range(2, size+1):\n \n # Propagate distance from C on right hand side\n shortest_dist[-idx] = min(shortest_dist[-idx], shortest_dist[-idx+1]+1 )\n\n \n return shortest_dist\n```
20
1
['Python', 'Python3']
4
shortest-distance-to-a-character
Python 3
python-3-by-zychen016-exu7
\nclass Solution:\n def shortestToChar(self, S, C):\n """\n :type S: str\n :type C: str\n :rtype: List[int]\n """\n
zychen016
NORMAL
2018-05-17T13:05:34.434464+00:00
2018-10-25T14:39:35.628981+00:00
3,486
false
```\nclass Solution:\n def shortestToChar(self, S, C):\n """\n :type S: str\n :type C: str\n :rtype: List[int]\n """\n c = []\n for i, v in enumerate(S):\n if v == C:\n c.append(i)\n\n r = []\n for i in range(len(S)):\n r.append(min([abs(t - i)for t in c]))\n return r\n\n\n```
17
3
[]
6
shortest-distance-to-a-character
Python || 99.92% Faster || Two Pointers || O(n) Solution
python-9992-faster-two-pointers-on-solut-dgnu
\nclass Solution:\n def shortestToChar(self, s: str, c: str) -> List[int]:\n a,n=[],len(s)\n for i in range(n):\n if s[i]==c:\n
pulkit_uppal
NORMAL
2022-11-27T15:24:08.175101+00:00
2022-11-27T15:25:18.127808+00:00
4,882
false
```\nclass Solution:\n def shortestToChar(self, s: str, c: str) -> List[int]:\n a,n=[],len(s)\n for i in range(n):\n if s[i]==c:\n a.append(i)\n answer=[]\n j=0\n for i in range(n):\n if s[i]==c:\n answer.append(0)\n j+=1\n elif i<a[0]:\n answer.append(a[0]-i)\n elif i>a[-1]:\n answer.append(i-a[-1])\n else:\n answer.append(min((a[j]-i),(i-a[j-1])))\n return answer\n```\n\n**An upvote will be encouraging**
16
1
['Array', 'Two Pointers', 'Python', 'Python3']
5
shortest-distance-to-a-character
java 98% 100%
java-98-100-by-themonkey-g6u7
\nclass Solution {\n public int[] shortestToChar(String S, char C) {\n char[] arrS=S.toCharArray(); \n int[] dist=new int[arrS.length];\n
themonkey
NORMAL
2019-07-26T05:27:54.416465+00:00
2019-07-26T05:27:54.416498+00:00
1,707
false
```\nclass Solution {\n public int[] shortestToChar(String S, char C) {\n char[] arrS=S.toCharArray(); \n int[] dist=new int[arrS.length];\n int disToL=S.length(), disToR=S.length(); \n \n for(int i=0;i<arrS.length;i++){ //pass 1, determine distance to nearest C on the left \n if(arrS[i]==C)\n disToL=0;\n dist[i]=disToL;\n disToL++;\n }\n \n for(int i=arrS.length-1;i>=0;i--){ //pass 2, determine distance to nearest C on the right, compare with previous pass and take minimum \n if(arrS[i]==C)\n disToR=0;\n dist[i]=Math.min(dist[i],disToR);\n disToR++;\n }\n \n return dist;\n }\n}\n```
16
0
[]
7
shortest-distance-to-a-character
Java - Single Pass with Trailing Pointer (Concise)
java-single-pass-with-trailing-pointer-c-tmj3
Idea is exactly the same as other solutions using stack or two pointers. Keep track of the last seen target character C as well as a left pointer pointing to th
bradshaw
NORMAL
2018-04-22T05:19:14.949470+00:00
2018-09-26T23:19:23.759964+00:00
3,509
false
Idea is exactly the same as other solutions using stack or two pointers. Keep track of the last seen target character C as well as a left pointer pointing to the last non C character. \n\nIf you hit a nonC character and have not seen any C yet, max out that value.\n\nIf you hit a nonC character and have seen a C, the current distance to C is the current position i minus the index of the last seen C.\n\nIf you hit a C, update all entries from the left pointer up until the current index with the correct value. This is the minimum between the distance to the current C and the previous distance to another C. Finally, update the last seen C index to the current index.\n\n```\n public int[] shortestToChar(String S, char C) {\n int[] result = new int[S.length()];\n \n int lastC = -1;\n int lastNonC = 0;\n \n for(int i = 0; i<S.length(); i++)\n if(S.charAt(i) == C){\n while(lastNonC<=i)\n result[lastNonC] = Math.min(result[lastNonC], i-lastNonC++);\n lastC = i;\n }else\n result[i] = lastC != -1 ? i-lastC : Integer.MAX_VALUE;\n \n return result;\n }\n```
16
2
[]
7
shortest-distance-to-a-character
Intuition leads to approach | Java | optimize intuition to get effective solution
intuition-leads-to-approach-java-optimiz-0e13
Intuition:\nSimple intuition: \n\n Suppose the answer is stored ans array.\n ans[i] is minimum of distances from all the positions of character C in string S\nE
ksumit9895
NORMAL
2021-02-08T10:50:00.044735+00:00
2021-02-08T10:50:00.044764+00:00
1,715
false
**Intuition:**\n**Simple intuition**: \n\n* Suppose the answer is stored ans array.\n* ans[i] is minimum of distances from all the positions of character C in string S\nEx : Input: s = "loveleetcode", c = "e"\nIndices of e = {3, 5, 6, 12}\n* To get the shortest distance, we need to check the nearest from both sides.\n* Run 2 loops from both end, updating the min value.\n\n**Solution**:\n* We have to traverse the array two times, one from left to right & right to left.\n\n**Time Complexity**: Forward loop & Backward Loop : O(N) + O(N) ~ O(N)\n**Space Complexity**: Without considering answer array : O(1) \n```\nclass Solution {\n public int[] shortestToChar(String s, char c) {\n int len = s.length();\n int ans[] = new int[len];\n int prev = len;\n \n // forward\n for(int i = 0; i < len; i++){\n if(s.charAt(i) == c){\n prev = 0;\n ans[i] = 0;\n }\n else\n ans[i] = ++prev;\n }\n \n prev = len;\n for(int i = len-1; i >= 0; i--){\n if(s.charAt(i) == c){\n prev = 0;\n ans[i] = Math.min(ans[i], 0);\n }\n else\n ans[i] = Math.min(ans[i], ++prev);\n }\n \n return ans;\n }\n}\n\n```\n\n**Intuition 2**: \n```\nclass Solution {\n public int[] shortestToChar(String s, char c) {\n int len = s.length();\n int[] ans = new int[len];\n Arrays.fill(ans, len + 1);\n int j;\n for(int i = 0; i < len; i++){\n if(s.charAt(i) == c){\n ans[i] = 0;\n j = i - 1;\n //fill reverse \n while(j >= 0 && ans[j] > i - j){\n ans[j] = i - j;\n j--;\n }\n //fill forward\n j = i + 1;\n while( j < len && s.charAt(j) != c){\n ans[j] = j - i;\n j++;\n }\n i = j - 1;\n }\n }\n return ans;\n }\n}\n```\n**Optimization**: \nWhile traversing the string, \n* ans[i] = 0 for all i where s.charAt(i) == c\n* start filling from the index of character to both ends.\n1. For forward: start filling {1, 2, 3... } from j = i+1 till we reach to another c or end of the string.\n2. For backward : From j = i -1 till we reach to another c or start of the string.\n\t\t\t\t\t\t\tFill minimum of ans[j] & i - j (distance of j from i).\n* If at any point if ans[j] is less than & equal to i-j, for all the elements before jth index i-j is greater than ans[j]\n\n**Solution**:\n* We have to traverse the array from one end, if there is a character c, update in backward too.\n\n**Time Complexity**: Forward loop & Backward Loop : O(N) + O(N/2) ~ O(N) where N is number of string.\n**Space Complexity**: Without considering answer array : O(1) \n```\nclass Solution {\n public int[] shortestToChar(String s, char c) {\n int N = s.length();\n int[] ans = new int[N];\n int prev = N + 1, j;\n for (int i = 0; i < N; ++i) {\n if (s.charAt(i) == c) {\n ans[i] = 0;\n prev = 1;\n j = i-1;\n while( j >= 0 && ans[j] > i - j ){\n ans[j] = i - j;\n j--;\n }\n }\n else\n ans[i] = prev++;\n }\n return ans;\n }\n}\n```
11
0
['Java']
3
shortest-distance-to-a-character
[JAVA] BEATS 100.00% MEMORY/SPEED 0ms // APRIL 2022
java-beats-10000-memoryspeed-0ms-april-2-j7rf
\n\tclass Solution {\n\n public int[] shortestToChar(String s, char c) {\n int len = s.length();\n int ans[] = new int[len];\n int prev
darian-catalin-cucer
NORMAL
2022-04-20T06:40:56.250241+00:00
2022-04-20T06:40:56.250289+00:00
1,723
false
\n\tclass Solution {\n\n public int[] shortestToChar(String s, char c) {\n int len = s.length();\n int ans[] = new int[len];\n int prev = len;\n \n // forward\n for(int i = 0; i < len; i++){\n if(s.charAt(i) == c){\n prev = 0;\n ans[i] = 0;\n }\n else\n ans[i] = ++prev;\n }\n \n prev = len;\n for(int i = len-1; i >= 0; i--){\n if(s.charAt(i) == c){\n prev = 0;\n ans[i] = Math.min(ans[i], 0);\n }\n else\n ans[i] = Math.min(ans[i], ++prev);\n }\n \n return ans;\n }\n\t}
10
0
['Java']
1
shortest-distance-to-a-character
Shortest Distance to a Character | Simple DP Solution w/ Explanation | beats 100% / 100%
shortest-distance-to-a-character-simple-0y0y3
(Note: This is part of a series of Leetcode solution explanations (index). If you like this solution or find it useful, please upvote this post.)\n\n---\n\nIdea
sgallivan
NORMAL
2021-02-07T09:13:40.649470+00:00
2021-02-07T09:13:40.649508+00:00
410
false
*(Note: This is part of a series of Leetcode solution explanations ([**index**](https://dev.to/seanpgallivan/leetcode-solutions-index-57fl)). If you like this solution or find it useful,* ***please upvote*** *this post.)*\n\n---\n\n***Idea:***\n\nSince this problem is asking us to reference characters both ahead and behind the current charcter, this should bring to mind a two-pass **dynamic programming** solution. We can iterate through the input string (**S**) once and fill our answer array (**ans**) with the distance from the preceeding occurrence of **C**.\n\nThen we can iterate backwards through **S** again so that we can pick the best result between the value we obtained in the first pass with the distance from the preceeding **C** going the opposite direction.\n\n---\n\n***Javascript Code:***\n\nThe best result for the code below is **80ms / 39.0MB** (beats 99% /100%).\n```javascript\nvar shortestToChar = function(S, C) {\n let len = S.length, ans = new Uint16Array(len)\n ans[0] = S.charAt(0) === C ? 0 : 10001\n for (let i = 1; i < len; i++) \n ans[i] = S.charAt(i) === C ? 0 : ans[i-1] + 1\n for (let i = len - 2; ~i; i--)\n ans[i] = Math.min(ans[i], ans[i+1] + 1)\n return ans\n};\n```\n\n---\n\n***Python3 Code:***\n\nThe best result for the code below is **28ms / 14.3MB** (beats 99% / 86%).\n```python\nclass Solution:\n def shortestToChar(self, S: str, C: str) -> List[int]:\n ans = []\n ans.append(0 if S[0] == C else 10001)\n for i in range(1,len(S)):\n ans.append(0 if S[i] == C else ans[i-1] + 1)\n for i in range(len(S)-2,-1,-1):\n ans[i] = min(ans[i], ans[i+1] + 1)\n return ans\n```\n\n---\n\n***Java Code:***\n\nThe best result for the code below is **1ms / 38.8MB** (beats 97% / 93%).\n```java\nclass Solution {\n public int[] shortestToChar(String S, char C) {\n int len = S.length();\n int[] ans = new int[len];\n ans[0] = S.charAt(0) == C ? 0 : 10001;\n for (int i = 1; i < len; i++) \n ans[i] = S.charAt(i) == C ? 0 : ans[i-1] + 1;\n for (int i = len - 2; i >= 0; i--)\n ans[i] = Math.min(ans[i], ans[i+1] + 1); \n return ans;\n }\n}\n```\n\n---\n\n***C++ Code:***\n\nThe best result for the code below is **0ms /6.5MB** (beats 100% / 97%).\n```c++\nclass Solution {\npublic:\n vector<int> shortestToChar(string S, char C) {\n int len = S.length();\n std::vector<int> ans;\n ans.push_back(S[0] == C ? 0 : 10001);\n for (int i = 1; i < len; i++) \n ans.push_back(S[i] == C ? 0 : ans[i-1] + 1);\n for (int i = len - 2; i >= 0; i--)\n ans[i] = min(ans[i], ans[i+1] + 1); \n return ans;\n }\n};\n```
10
6
[]
2
shortest-distance-to-a-character
easy solution
easy-solution-by-leelasravanthi423-161i
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
leelasravanthi423
NORMAL
2023-12-13T17:34:19.704081+00:00
2023-12-13T17:34:19.704113+00:00
1,068
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 shortestToChar(self, s: str, c: str) -> List[int]:\n a=[]\n b=[]\n for i in range(len(s)):\n if s[i]==c:\n a.append(i)\n for i in range(len(s)):\n c=[]\n for j in a:\n c.append(abs(i-j))\n b.append(min(c))\n return b\n\n \n```
9
0
['Python3']
0
shortest-distance-to-a-character
C++ || Basic || Easy implementaion
c-basic-easy-implementaion-by-priyamesh2-k1bn
\nclass Solution {\npublic:\n vector<int> shortestToChar(string s, char c) {\n vector<int>out;\n vector<int>pos;\n \n //collect a
priyamesh28
NORMAL
2021-06-11T09:02:43.965760+00:00
2021-06-11T09:02:43.965804+00:00
640
false
```\nclass Solution {\npublic:\n vector<int> shortestToChar(string s, char c) {\n vector<int>out;\n vector<int>pos;\n \n //collect all the position of given char\n for(int i=0;i<s.size();i++)\n {\n if(s[i]==c)\n pos.push_back(i);\n }\n \n //traversal and find the min diffrence from the given char to all given pos\n for(int i=0;i<s.size();i++)\n {\n int min_dis=INT_MAX;\n for(int j=0;j<pos.size();j++)\n {\n min_dis=min(min_dis,abs(i-pos[j]));\n }\n out.push_back(min_dis);\n }\n return out;\n \n }\n};\n# If you find any issue in understanding the solutions then comment below, will try to help you.\nIf you found my solution useful.\nSo please do upvote and encourage me to document all leetcode problems\uD83D\uDE03\nHappy Coding :)\n```
9
0
['C']
0
shortest-distance-to-a-character
JavaScript Simple 1-Pass Beats 100%
javascript-simple-1-pass-beats-100-by-co-jljv
javascript\nvar shortestToChar = function(s, c) {\n const answer = Array(s.length).fill(Infinity);\n let l = Infinity, r = Infinity;\n \n for(let f
control_the_narrative
NORMAL
2021-02-07T08:46:03.364078+00:00
2021-02-08T10:28:19.712931+00:00
804
false
```javascript\nvar shortestToChar = function(s, c) {\n const answer = Array(s.length).fill(Infinity);\n let l = Infinity, r = Infinity;\n \n for(let f = 0; f < s.length; f++) {\n const b = s.length-1-f;\n \n l = s[f] === c ? 0 : l+1;\n r = s[b] === c ? 0 : r+1;\n \n answer[f] = Math.min(answer[f], l);\n answer[b] = Math.min(answer[b], r);\n }\n return answer; \n};\n```
9
0
['JavaScript']
4
shortest-distance-to-a-character
[Java], 2 Solutions, self explained, easy to read, 2 iterations
java-2-solutions-self-explained-easy-to-dx1uu
1- Using DP\n going from left to right, at each position i ans[i] = ans[i-1] + 1\n going from right to left, at each position i ans[i] = ans[i+1] + 1\n\npublic
ahmednabil
NORMAL
2021-02-07T11:05:06.404545+00:00
2021-02-07T12:38:42.604567+00:00
1,353
false
1- Using DP\n* going from left to right, at each position i ans[i] = ans[i-1] + 1\n* going from right to left, at each position i ans[i] = ans[i+1] + 1\n```\npublic int[] shortestToChar(String s, char c) {\n int n = s.length();\n int[] ans = new int[n];\n Arrays.fill(ans, n);\n for(int i=0; i<n; i++) {\n if(s.charAt(i) == c) ans[i] = 0;\n else if(i > 0) ans[i] = Math.min(ans[i], ans[i-1] + 1);\n }\n \n for(int i=n-1; i>=0; i--) {\n if(s.charAt(i) == c) ans[i] = 0;\n else if (i < n-1) ans[i] = Math.min(ans[i], ans[i+1] + 1);\n }\n return ans;\n}\n```\n\n2- keep track of last appearance of C\n* pos = last appearance of c\n* going from left to right, dist[i] = i - pos\n* going from right to left, dist[i] = pos - i\n\n```\npublic int[] shortestToChar(String s, char c) {\n int n = s.length();\n int pos = -n;\n int[] ans = new int[n];\n\n for(int i=0; i<n; i++) {\n if(s.charAt(i) == c) pos = i;\n ans[i] = i - pos;\n }\n\n pos = 2*n;\n for(int i=n-1; i>=0; i--) {\n if(s.charAt(i) == c) pos = i;\n ans[i] = Math.min(ans[i], pos - i);\n }\n\n return ans;\n}\n```
8
0
['Java']
0
shortest-distance-to-a-character
Beginner friendly easy solution | JAVA
beginner-friendly-easy-solution-java-by-u4y9o
\n\n# Code\n\nclass Solution {\n public int[] shortestToChar(String s, char c) {\n int[] ans=new int[s.length()];\n List<Integer> ls=new ArrayL
sumo25
NORMAL
2024-02-09T12:29:42.168451+00:00
2024-02-09T12:29:42.168479+00:00
907
false
\n\n# Code\n```\nclass Solution {\n public int[] shortestToChar(String s, char c) {\n int[] ans=new int[s.length()];\n List<Integer> ls=new ArrayList<>();\n for(int i=0;i<s.length();i++){\n if(s.charAt(i)==c){\n ls.add(i);\n }\n }\n \n for(int i=0;i<s.length();i++){\n int minn=Integer.MAX_VALUE;\n for(int j=0;j<ls.size();j++){\n minn=Math.min(minn,Math.abs(i-ls.get(j)));\n }\n ans[i]=minn;\n }\n return ans;\n }\n}\n```
7
0
['Java']
0
shortest-distance-to-a-character
Python 3 Solution, Brute Force and Two Pointers - 2 Solutions
python-3-solution-brute-force-and-two-po-rr73
Brute Force:\n\nclass Solution:\n def shortestToChar(self, s: str, c: str) -> List[int]:\n req = []\n ind_list = []\n for i in range(len
deleted_user
NORMAL
2022-05-04T08:18:05.542540+00:00
2022-05-04T08:18:05.542569+00:00
1,224
false
Brute Force:\n```\nclass Solution:\n def shortestToChar(self, s: str, c: str) -> List[int]:\n req = []\n ind_list = []\n for i in range(len(s)):\n if s[i] == c:\n ind_list.append(i)\n min_dis = len(s)\n for j in range(len(s)):\n for k in range(len(ind_list)):\n min_dis = min(min_dis, abs(j - ind_list[k]))\n req.append(min_dis)\n min_dis = len(s)\n \n return req\n```\n\nTwo Pointers, O(n) Time and Space\n```\nclass Solution:\n def shortestToChar(self, s: str, c: str) -> List[int]:\n# Travelling front to back\n result = ["*"] * len(s)\n i, j = 0, 0\n while i < len(s) and j < len(s):\n if s[i] == s[j] == c:\n result[i] = 0\n i += 1\n j += 1\n elif s[i] != c and s[j] == c:\n result[i] = abs(i-j)\n i += 1\n elif s[i] != c and s[j] != c:\n j += 1\n \n# Travelling back to front\n i = j = len(s) - 1\n while i >= 0 and j >= 0:\n if s[i] == s[j] == c:\n result[i] = 0\n i -= 1\n j -= 1\n elif s[i] != c and s[j] == c:\n if type(result[i]) == int:\n result[i] = min(result[i], abs(i-j))\n else:\n result[i] = abs(i-j)\n i -= 1\n elif s[i] != c and s[j] != c:\n j -= 1\n \n return result\n```
7
0
['Two Pointers', 'Python', 'Python3']
2
shortest-distance-to-a-character
JavaScript - 2 passes
javascript-2-passes-by-slkuo230-jfo7
\nvar shortestToChar = function(S, C) {\n const dp = new Array(S.length).fill(Infinity);\n \n dp[0] = S[0] === C ? 0 : Infinity\n \n for(let i =
slkuo230
NORMAL
2020-02-16T21:35:29.139224+00:00
2020-02-16T21:35:29.139258+00:00
953
false
```\nvar shortestToChar = function(S, C) {\n const dp = new Array(S.length).fill(Infinity);\n \n dp[0] = S[0] === C ? 0 : Infinity\n \n for(let i = 1; i < S.length; i++) {\n if(S[i] === C) {\n dp[i] = 0;\n } else {\n dp[i] = dp[i-1] === Infinity ? Infinity : dp[i-1] + 1;\n }\n }\n\n let dist = Infinity;\n \n for(let i = S.length-1; i >= 0; i--) {\n if(S[i] === C) {\n dist = 0;\n }\n dp[i] = Math.min(dist, dp[i]);\n dist += 1;\n }\n \n return dp;\n \n};\n```
7
0
['JavaScript']
1
shortest-distance-to-a-character
c++ easy solution
c-easy-solution-by-sailakshmi1-qws5
```\nclass Solution {\npublic:\n vector shortestToChar(string s, char c) {\n vectorposition;\n vectorans;\n for(int i=0;i<s.length();i++
sailakshmi1
NORMAL
2022-06-19T13:30:36.332170+00:00
2022-06-19T13:30:36.332217+00:00
833
false
```\nclass Solution {\npublic:\n vector<int> shortestToChar(string s, char c) {\n vector<int>position;\n vector<int>ans;\n for(int i=0;i<s.length();i++){\n if(s[i]==c){\n position.push_back(i);\n }\n }\n for(int i=0;i<s.length();i++){ \n int mn=INT_MAX;\n for(int j=0;j<position.size();j++){\n mn=min(mn,abs(i-position[j]));\n }\n ans.push_back(mn);\n }\n return ans;\n }\n};
6
0
['C', 'C++']
0
shortest-distance-to-a-character
【Python3】Any improvement ?
python3-any-improvement-by-qiaochow-00rz
\nclass Solution:\n def shortestToChar(self, s: str, c: str) -> List[int]:\n L = []\n for idx, value in enumerate(s):\n if value ==
qiaochow
NORMAL
2021-05-23T22:46:47.533774+00:00
2021-05-23T22:46:47.533817+00:00
780
false
```\nclass Solution:\n def shortestToChar(self, s: str, c: str) -> List[int]:\n L = []\n for idx, value in enumerate(s):\n if value == c:\n L.append(idx)\n \n distance = []\n i = 0\n for idx, value in enumerate(s):\n if value == c:\n distance.append(0)\n i += 1\n elif idx < L[0]:\n distance.append(L[0] - idx)\n elif idx > L[-1]:\n distance.append(idx - L[-1])\n else:\n distance.append(min((L[i] - idx), (idx - L[i-1]))) \n return distance\n```
6
0
['Python', 'Python3']
0
shortest-distance-to-a-character
[Java] | Two Pointers | One Pass | Time: O(n) | Optimal - Faster than 98.5%
java-two-pointers-one-pass-time-on-optim-6gud
Approach:\n\nMaintain two pointers (one for the current character in S (sIndex) and the other (cIndex) to track the next occurence of C in S). Also have another
svantedd
NORMAL
2020-06-14T19:44:59.566027+00:00
2020-06-14T19:51:55.728544+00:00
374
false
Approach:\n\nMaintain two pointers (one for the current character in S (sIndex) and the other (cIndex) to track the next occurence of C in S). Also have another variable to hold the previous occurence of C in S (prevCIndex) which is initially set to -1.\n\nFirstly, as it\'s guaranteed to have at least one C in S, find the first occurence of C in S by incrementing C pointer (cIndex). Now, until the S pointer (sIndex) reaches C pointer (cIndex), calculate the shortest distance which is (cIndex - sIndex). Remember at this stage there is no previous occurrence of C in S. Therefore, `result[i] = cIndex - sIndex;`\n\nMoving on, there are two cases: \n1) You might\'ve a next of occurrence of C in S\n2) You might not have any more occurrences of C (in the case which cIndex is beyond String length). \n\nIn the former, you get the minimum of the previous C Index and the current C Index to the current character in S (`Math.min(cIndex - sIndex, sIndex - prevCIndex)`)\n& in the latter you just calculate the distance from the previous C Index to the current character in S (`sIndex - prevCIndex`).\n\nRefer to the below code for better understanding.\n\n```\n public int[] shortestToChar(String S, char C) {\n int[] result = new int[S.length()];\n\n\t\t// Pointers to track C in S & the current moving index in S respectively\n\t\tint cIndex = 0, sIndex = 0;\n\n\t\t// Pointer to track the previous occurrence of C in S - Initially set to -1\n\t\tint prevCIndex = -1;\n\n\t\twhile (cIndex < S.length()) {\n\t\t\t// Find the first/next occurrence of C in S\n\t\t\twhile (cIndex < S.length() && S.charAt(cIndex) != C) {\n\t\t\t\tcIndex++;\n\t\t\t}\n\n\t\t\t// Move the S pointer until C and fill the result with the shortest distance\n\t\t\twhile (sIndex < cIndex) {\n\t\t\t\tif (prevCIndex == -1) {\n\t\t\t\t\t// Initial stage where there is no previous occurrence of C in S yet\n\t\t\t\t\tresult[sIndex] = cIndex - sIndex;\n\t\t\t\t} else if (cIndex < S.length() && S.charAt(cIndex) == C) {\n\t\t\t\t\t// You have both previous and the next occurrences of C in S - Get the minimum\n\t\t\t\t\tresult[sIndex] = Math.min(cIndex - sIndex, sIndex - prevCIndex);\n\t\t\t\t} else {\n\t\t\t\t\t// Last stage where you crossed the last occurrence of C in S\n\t\t\t\t\tresult[sIndex] = sIndex - prevCIndex;\n\t\t\t\t}\n\n\t\t\t\t// Increment the current pointer in S\n\t\t\t\tsIndex++;\n\t\t\t}\n\n\t\t\t// Set the current occurrence of C to previous\n\t\t\tprevCIndex = cIndex;\n\n\t\t\t// Increment both the pointers\n\t\t\tsIndex++;\n\t\t\tcIndex++;\n\t\t}\n \n return result;\n }\n```\n\n\nTime: O(n)\nSpace: O(1) (Excluding the result array to be returned)
6
1
['Two Pointers']
1
shortest-distance-to-a-character
JavaScript Solution with Comments
javascript-solution-with-comments-by-spo-oybn
Runtime: 92 ms, faster than 51.38% of JavaScript online submissions\n> Memory Usage: 40.8 MB, less than 58.84% of JavaScript online submissions\n\njavascript\n/
sporkyy
NORMAL
2020-02-20T13:53:57.962598+00:00
2021-03-05T21:26:15.427659+00:00
743
false
> Runtime: **92 ms**, faster than *51.38%* of JavaScript online submissions\n> Memory Usage: **40.8 MB**, less than *58.84%* of JavaScript online submissions\n\n```javascript\n/**\n * @param {string} s\n * @param {character} c\n * @return {number[]}\n */\nconst shortestToChar = (s, c) => {\n // Create an array to hold the distances the same length as the string\n // And fill it with `Infinity` because `Math.min` gets used below\n // But filling with `s.length` or `104` (from Constraints) would also work.\n const res = new Array(s.length).fill(Infinity);\n for (\n // Create some variables to use while looping through the string\n // - `li` Left Index: Traverse the string from left to right\n // - `ld` Left Distance: Reset to `0` every time `c` is seen in the string\n // - `ri` Right Index: Traverse the string from right to left\n // - `rd` Right Distance: Reset to `0` every time `c` is seen in the string\n let li = 0, ld = Infinity, ri = s.length - 1, rd = Infinity;\n // Stop the loop before the Left Index goes off the right end of the string\n // This also stops the loop before the Right Index goes off the left end\n li < s.length;\n // After every iteration:\n // - The left index moves `1` place to the left\n // - The left distance increases by `1`\n // - The right index moves `1` place to the right\n // - The right distance increases by `1`\n li++, ld++, ri--, rd++\n ) {\n // If the character at the left index is the character we\'re looking for,\n // reset the left distance to `0`\n if (s[li] === c) ld = 0;\n // As we move left, set the `res` array value to the lesser distance:\n // - `res[li]` The default value, `Infinity` or, passed the halfway point,\n // the previously set Right Distance to the sought character\n // - `ld` Distance to the sought character looking left\n res[li] = Math.min(res[li], ld);\n // If the character at the right index is the character we\'re looking for,\n // reset the right distance to `0`\n if (s[ri] === c) rd = 0;\n // As we move right, set the `res` array value to the lesser distance:\n // - `res[ri]` The default value, `Infinity` or, passed the halfway point,\n // the previously set Left Distance to the sought character\n // - `rd` Distance to the sought character looking right\n res[ri] = Math.min(res[ri], rd);\n }\n return res;\n};\n```
6
0
['JavaScript']
1
shortest-distance-to-a-character
Kotlin Best Solution
kotlin-best-solution-by-progp-de4d
\n# Code\n\nimport kotlin.math.min\n\nclass Solution {\n fun shortestToChar(s: String, c: Char): IntArray {\n\t// tracks postitions of occurences of the char
progp
NORMAL
2023-12-10T08:00:28.451876+00:00
2023-12-10T08:00:28.451914+00:00
190
false
\n# Code\n```\nimport kotlin.math.min\n\nclass Solution {\n fun shortestToChar(s: String, c: Char): IntArray {\n\t// tracks postitions of occurences of the character c in string s\n var positions = mutableListOf<Int>()\n\t\t\n var ans = mutableListOf<Int>()\n \n for(i in 0..s.length-1){\n if(s[i]==c)\n positions.add(i)\n }\n\t\t\n\t// cannot explain this xD\n positions.add(-1)\n \n\t// position of left occurence of c in s\n var left = -1\n\t\t\n\t// position of right occurence of c in s\n var right = positions.removeAt(0)\n\t\t\n\t// left distance\n var ld : Int\n\t\t\n\t// right distance\n var rd : Int\n \n for(i in 0..s.length-1){\n ld = Int.MAX_VALUE\n rd = Int.MAX_VALUE\n if(left!=-1)\n ld = i-left\n if(right!=-1)\n rd = right-i\n ans.add(min(ld, rd))\n \n if(i==right){\n left = right\n right = positions.removeAt(0)\n }\n }\n \n return ans.toIntArray()\n }\n}\n```
5
0
['Kotlin']
0
shortest-distance-to-a-character
Java | Do check out for explanation | Faster than 100%
java-do-check-out-for-explanation-faster-thsb
Do vote up if you like it :)\n\nThe idea is to find the minimum char say c index from right for all position.\nAnd again find the minimum char say c index from
nknidhi321
NORMAL
2021-06-27T09:11:34.391146+00:00
2021-06-27T09:14:10.184176+00:00
195
false
**Do vote up if you like it :)**\n\nThe idea is to find the minimum char say c index from right for all position.\nAnd again find the minimum char say c index from left for all position.\nNow, whichever (left or right) gives you the minimum that is the minimum distance for char c for that position.\n\n```\nclass Solution {\n \n public int[] shortestToChar(String s, char c) {\n \n int[] ans = new int[s.length()];\n int index = 0;\n \n for(int i = s.length() - 1; i >= 0; i--){\n if(s.charAt(i) == c){\n index = i;\n }\n ans[i] = Math.abs(i - index);\n }\n \n for(int i = 0; i < s.length(); i++){\n if(s.charAt(i) == c){\n index = i;\n }\n ans[i] = Math.min(ans[i], Math.abs(i - index));\n }\n return ans;\n }\n}\n```\n------------------------------------------------------------
5
0
[]
0
shortest-distance-to-a-character
2-line python solution
2-line-python-solution-by-mhviraf-zq88
\nclass Solution:\n def shortestToChar(self, s: str, c: str) -> List[int]:\n ids = [i for i in range(len(s)) if s[i] == c]\n return [min([abs(i
mhviraf
NORMAL
2021-03-03T06:07:31.955173+00:00
2021-03-03T06:07:31.955230+00:00
855
false
```\nclass Solution:\n def shortestToChar(self, s: str, c: str) -> List[int]:\n ids = [i for i in range(len(s)) if s[i] == c]\n return [min([abs(i-id_) for id_ in ids]) for i in range(len(s))]\n```
5
0
['Python', 'Python3']
0
shortest-distance-to-a-character
[C++] [Two Pass] - Easy to understand solution
c-two-pass-easy-to-understand-solution-b-uvq7
Approach 1 : Using BFS for shortest distance \n\tTime Complexity - O(n)\n\tSpace Complexity - O(n) \n\nclass Solution {\npublic:\n vector<int> shortestToChar
morning_coder
NORMAL
2021-02-08T03:57:10.600634+00:00
2021-02-08T03:59:21.005026+00:00
801
false
**Approach 1 : Using BFS for shortest distance** \n\tTime Complexity - O(n)\n\tSpace Complexity - O(n) \n```\nclass Solution {\npublic:\n vector<int> shortestToChar(string s, char c) {\n int len=s.length();\n vector<int> ans(len,INT_MAX);\n queue<vector<int> > q;\n for(int i=0;i<len;i++)\n if(s[i]==c){\n q.push({i,0});\n ans[i]=0;\n }\n while(!q.empty()){\n int qsize=q.size();\n while(qsize--){\n vector<int> v=q.front();\n q.pop();\n if(v[0]+1<len && ans[v[0]+1]==INT_MAX){\n q.push({v[0]+1,v[1]+1});\n ans[v[0]+1]=v[1]+1;\n } \n if(v[0]>0 && ans[v[0]-1]==INT_MAX){\n q.push({v[0]-1,v[1]+1});\n ans[v[0]-1]=v[1]+1;\n }\n }\n }\n return ans;\n }\n};\n```\n\n\n\n**Approach 2 : Without extra space , two traversals -one from start , another from end**\n\tTime Complexity - O(n)\n\tSpace Complexity - O(1)\n\n```\nclass Solution {\npublic:\n vector<int> shortestToChar(string s, char c) {\n int len=s.length();\n vector<int> ans(len,INT_MAX);\n int pos_c=len*(-1);\n for(int i=0;i<len;i++){\n if(s[i]==c)\n pos_c=i;\n ans[i]=min(ans[i],i-pos_c);\n }\n pos_c=2*len;\n for(int i=len-1;i>=0;i--){\n if(s[i]==c)\n pos_c=i;\n ans[i]=min(ans[i],pos_c-i);\n }\n return ans;\n }\n};\n```\n\nHave doubts , please let me know in comments.
5
0
['Breadth-First Search', 'C', 'C++']
0
shortest-distance-to-a-character
2-pass but different and intuitive; comments included
2-pass-but-different-and-intuitive-comme-kgt2
\nimport kotlin.math.min\n\nclass Solution {\n fun shortestToChar(s: String, c: Char): IntArray {\n\t// tracks postitions of occurences of the character c in
rakeshseervi
NORMAL
2021-02-07T10:56:01.634215+00:00
2021-02-07T11:29:17.037390+00:00
271
false
```\nimport kotlin.math.min\n\nclass Solution {\n fun shortestToChar(s: String, c: Char): IntArray {\n\t// tracks postitions of occurences of the character c in string s\n var positions = mutableListOf<Int>()\n\t\t\n var ans = mutableListOf<Int>()\n \n for(i in 0..s.length-1){\n if(s[i]==c)\n positions.add(i)\n }\n\t\t\n\t// cannot explain this xD\n positions.add(-1)\n \n\t// position of left occurence of c in s\n var left = -1\n\t\t\n\t// position of right occurence of c in s\n var right = positions.removeAt(0)\n\t\t\n\t// left distance\n var ld : Int\n\t\t\n\t// right distance\n var rd : Int\n \n for(i in 0..s.length-1){\n ld = Int.MAX_VALUE\n rd = Int.MAX_VALUE\n if(left!=-1)\n ld = i-left\n if(right!=-1)\n rd = right-i\n ans.add(min(ld, rd))\n \n if(i==right){\n left = right\n right = positions.removeAt(0)\n }\n }\n \n return ans.toIntArray()\n }\n}\n```
5
0
['Kotlin']
1
shortest-distance-to-a-character
Python. O(n), Simple & easy-understanding cool solution.
python-on-simple-easy-understanding-cool-s30b
\tclass Solution:\n\t\tdef shortestToChar(self, s: str, c: str) -> List[int]:\n\t\t\tn = lastC =len(s)\n\t\t\tans = [n] * n\n\t\t\tfor i in itertools.chain(rang
m-d-f
NORMAL
2021-02-07T08:31:01.957605+00:00
2021-02-07T08:59:03.191157+00:00
487
false
\tclass Solution:\n\t\tdef shortestToChar(self, s: str, c: str) -> List[int]:\n\t\t\tn = lastC =len(s)\n\t\t\tans = [n] * n\n\t\t\tfor i in itertools.chain(range(n), range(n)[::-1]):\n\t\t\t\tif s[i] == c: lastC = i\n\t\t\t\tans[i] = min(ans[i], abs( i - lastC))\n\t\t\treturn ans
5
2
['Python', 'Python3']
0
shortest-distance-to-a-character
Python One Line Solution!!!
python-one-line-solution-by-debbiealter-tm6k
\nclass Solution:\n def shortestToChar(self, s: str, c: str) -> List[int]:\n return [min([abs(j - i) for j in [i for i in range(len(s)) if s[i] == c]]
debbiealter
NORMAL
2021-02-07T08:06:16.457251+00:00
2021-02-07T08:06:35.302178+00:00
224
false
```\nclass Solution:\n def shortestToChar(self, s: str, c: str) -> List[int]:\n return [min([abs(j - i) for j in [i for i in range(len(s)) if s[i] == c]]) for i in range(len(s))]\n```
5
4
['Python']
4
shortest-distance-to-a-character
Python3 100% faster, 100% less memory (20ms, 14mb)
python3-100-faster-100-less-memory-20ms-btts9
\nclass Solution:\n def shortestToChar(self, S: str, C: str) -> List[int]:\n l = [0] * len(S)\n prev = None\n for i, x in enumerate(S):\
haasosaurus
NORMAL
2020-10-29T05:46:49.369088+00:00
2020-10-29T06:10:05.758016+00:00
1,099
false
```\nclass Solution:\n def shortestToChar(self, S: str, C: str) -> List[int]:\n l = [0] * len(S)\n prev = None\n for i, x in enumerate(S):\n if x == C:\n\n\t\t\t\t# only correct the closer half of the indexes between previous and current if previous is not None\n start = 0 if prev is None else (i + prev) // 2 + 1\n\n\t\t\t\t# slice assign where corrections are needed to a range\n l[start:i + 1] = range(i - start, -1, -1)\n\n prev = i\n elif prev is not None:\n l[i] = i - prev\n return l\n```
5
0
['Python', 'Python3']
1
shortest-distance-to-a-character
Sharing Most Elegant cpp solution [ 12 ms ]
sharing-most-elegant-cpp-solution-12-ms-o3fun
```\nvector shortestToChar(string S, char C) {\n sets; int currentMin(INT_MAX);vectorans{};\n for(int i=0;i<S.length();i++) if(S[i]==C) s.insert(i
sarora160
NORMAL
2020-07-10T12:23:01.940867+00:00
2020-07-10T12:23:01.940916+00:00
311
false
```\nvector<int> shortestToChar(string S, char C) {\n set<int>s; int currentMin(INT_MAX);vector<int>ans{};\n for(int i=0;i<S.length();i++) if(S[i]==C) s.insert(i);\n for(int i=0;i<S.length();i++){\n for(auto x:s){\n if(abs(i-x)<currentMin) currentMin=abs(i-x);\n }\n ans.push_back(currentMin);\n currentMin=INT_MAX;\n }\n return ans;\n }
5
3
['C', 'C++']
2
shortest-distance-to-a-character
C++ Simplest Solution O(n)
c-simplest-solution-on-by-ddev-m4mp
vector<int> shortestToChar(string S, char C) {\n int len = S.length(), loc = -1;\n vector<int> result(len, INT_MAX);\n \n for(int i
ddev
NORMAL
2018-04-22T03:04:13.760593+00:00
2018-04-22T03:04:13.760593+00:00
1,589
false
vector<int> shortestToChar(string S, char C) {\n int len = S.length(), loc = -1;\n vector<int> result(len, INT_MAX);\n \n for(int i = 0; i < len; i++) {\n if(S[i] == C) loc = i;\n result[i] = min(result[i], loc != -1 ? abs(i - loc) : INT_MAX);\n }\n \n for(int i = len - 1; i >= 0; i--) {\n if(S[i] == C) loc = i;\n result[i] = min(result[i], abs(i - loc));\n }\n \n return result;\n }
5
2
[]
0
shortest-distance-to-a-character
Simple solution using two pointers | O(N) | 1ms
simple-solution-using-two-pointers-on-1m-l0yt
Intuition\n Describe your first thoughts on how to solve this problem. \n- Using two pointer approach\n\n# Approach\n Describe your approach to solving the prob
astronag
NORMAL
2023-08-12T12:56:45.065235+00:00
2023-08-12T12:59:09.810024+00:00
1,033
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- Using two pointer approach\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- We need to store previous and next closest occurrence of the character `c` in both the sides of the current index, `i`.\n- `previous` will have the closest occurrence of `c` to the left side of `i`.\n- `next` will have the closest occurrence of `c` to the right side of `i`. \n- Everytime `i` moves past `next`, the following operations will be made\n * `prev = next` \n * `next` moves forward in searching the next occurrence of `c` \n- At every index, the absolute minumum of `next - i` and `i - previous` gives the shortest distance to `c` \n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N) (for result array)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int[] shortestToChar(String s, char c) {\n int[] result = new int[s.length()];\n \n // Find the first occurrence of c\n int next = moveForward(s, c, 0);\n int previous = next;\n\n for (int i = 0; i < s.length(); ++i) {\n if (i > next) {\n previous = next;\n next = moveForward(s, c, next + 1);\n }\n\n result[i] = Math.abs(Math.min(next - i, i - previous));\n }\n\n return result;\n }\n\n private int moveForward(String s, char c, int position) {\n while(position < s.length()) {\n if (s.charAt(position) == c) {\n break;\n }\n ++position;\n }\n\n // When `c` does not occur further in the string, return MAX value\n // This makes `previous` as the only valid closest occurrence\n if (position == s.length()) {\n return Integer.MAX_VALUE;\n }\n return position;\n }\n}\n```
4
0
['Two Pointers', 'Java']
0
shortest-distance-to-a-character
✌️😀 😀 JAVA EASY TO UNDERSTAND 😀 😀 ✌️
java-easy-to-understand-by-sauravmehta-b2ql
Happy Coding\u270C\uFE0F\u270C\uFE0F\u270C\uFE0F\n\nclass Solution {\n public int[] shortestToChar(String s, char c)\n {\n int[] arr=new int[s.length()
Sauravmehta
NORMAL
2022-10-10T13:55:39.193903+00:00
2022-10-10T13:55:39.193942+00:00
1,869
false
# Happy Coding\u270C\uFE0F\u270C\uFE0F\u270C\uFE0F\n```\nclass Solution {\n public int[] shortestToChar(String s, char c)\n {\n int[] arr=new int[s.length()];\n for(int i=0;i<s.length();i++)\n {\n int left=i-1;\n int right=i+1;\n while(left>=0 || right <s.length())\n {\n if(s.charAt(i)==c)\n {\n arr[i]=0;\n break;\n }\n \n if(right < s.length() && s.charAt(right) == c)\n {\n arr[i]=right-i;\n break;\n }\n if( left >= 0 && s.charAt(left)== c)\n {\n arr[i]=i-left;\n break;\n }\n left--;\n right++;\n }\n }\n return arr;\n }\n}\n```
4
0
['Java']
0
shortest-distance-to-a-character
C++ | Easiest | O(n) time | 100% fastest
c-easiest-on-time-100-fastest-by-samarpi-vrgi
\n vector<int> shortestToChar(string s, char c) {\n vector<int> v , ans;\n for(int i = 0 ; i < s.size() ;i++){\n if(s[i] == c)\n
samarpitdua24
NORMAL
2022-09-19T10:00:14.618579+00:00
2022-09-19T10:00:43.299344+00:00
717
false
```\n vector<int> shortestToChar(string s, char c) {\n vector<int> v , ans;\n for(int i = 0 ; i < s.size() ;i++){\n if(s[i] == c)\n v.push_back(i);\n }\n int j = 0;\n for(int i = 0 ; i < s.size() ;i++){\n \n if(j == 0)\n ans.push_back(v[j] - i); \n else if(j >= v.size())\n ans.push_back(i - v[j - 1]);\n else\n ans.push_back(min(v[j] - i , i - v[j - 1]));\n if(s[i] == c)\n j++;\n }\n return ans;\n }\n\t```
4
0
['C', 'C++']
0
shortest-distance-to-a-character
Easy Java O(N) soution
easy-java-on-soution-by-anup-08ao
\npublic static int[] shortestToChar(String s, char c) {\n int n = s.length();\n int[] arr = new int[n];\n int c_position = -n;\n\n
anup_
NORMAL
2022-09-10T10:28:11.736083+00:00
2022-09-10T10:28:11.736125+00:00
1,184
false
```\npublic static int[] shortestToChar(String s, char c) {\n int n = s.length();\n int[] arr = new int[n];\n int c_position = -n;\n\n for (int i = 0; i < n; i++) {\n if(s.charAt(i) == c){\n c_position = i;\n }\n arr[i] = i - c_position;\n }\n\n for (int i = n-1; i >= 0; i--) {\n if(s.charAt(i) == c){\n c_position = i;\n }\n arr[i] = Math.min(arr[i], Math.abs(i - c_position));\n }\n return arr;\n }\n\t\n\t// Please Up-Vote\n\t```
4
0
['Java']
0
shortest-distance-to-a-character
Easiest Python solution with explanation
easiest-python-solution-with-explanation-grqw
\nclass Solution:\n def shortestToChar(self, s: str, c: str) -> List[int]:\n # occurence of charachter in the array.\n occ = []\n for i
EbrahimMG
NORMAL
2022-07-02T10:43:02.918004+00:00
2022-07-02T10:43:02.918047+00:00
801
false
```\nclass Solution:\n def shortestToChar(self, s: str, c: str) -> List[int]:\n # occurence of charachter in the array.\n occ = []\n for i in range(len(s)):\n if s[i] == c:\n occ.append(i)\n ans = []\n for i in range(len(s)):\n #checking distance of each point from occurences ans the selecting the least distance. \n tmplst = []\n for j in occ:\n tmplst.append(abs(i-j))\n ans.append(min(tmplst))\n return ans\n```
4
0
['Array', 'Python', 'Python3']
0
shortest-distance-to-a-character
[PYTHON] Shortest Distance to a Character | Runtime: 32ms & Memory usage: 14,200 kB
python-shortest-distance-to-a-character-4an29
"""\n implemented by me \n Noted: Time Complexity = 32ms O(n)\n Space Complexity = O(n)\n """\n\n dist = []\n
arunrathi201
NORMAL
2021-02-08T07:41:56.428799+00:00
2021-02-08T07:41:56.428868+00:00
264
false
"""\n implemented by me \n Noted: Time Complexity = 32ms O(n)\n Space Complexity = O(n)\n """\n\n dist = []\n c_ind = []\n for i in range(len(s)):\n if s[i] == c:\n c_ind.append(i)\n\n c_count = 0\n for i in range(len(s)):\n if s[i] == c:\n dist.append(0)\n if c_count < len(c_ind)-1:\n c_count += 1\n elif c_count == 0:\n dist.append(abs(c_ind[c_count]-i))\n elif abs(c_ind[c_count-1]-i) <= abs(c_ind[c_count]-i):\n dist.append(abs(c_ind[c_count-1]-i))\n else:\n dist.append(abs(c_ind[c_count]-i))\n\n return dist
4
1
['Python']
0
shortest-distance-to-a-character
Java || 2-pointer || O(n) || 1ms || beats 97%
java-2-pointer-on-1ms-beats-97-by-legend-xmxf
\n public int[] shortestToChar(String s, char c) {\n \n int ptr1 = Integer.MAX_VALUE;\n int ptr2 = Integer.MAX_VALUE;\n int index
LegendaryCoder
NORMAL
2021-02-07T11:49:45.864046+00:00
2021-02-07T11:51:21.992569+00:00
294
false
\n public int[] shortestToChar(String s, char c) {\n \n int ptr1 = Integer.MAX_VALUE;\n int ptr2 = Integer.MAX_VALUE;\n int index = -1;\n int l = s.length();\n int[] ans = new int[l];\n \n while(index<l-1){\n int temp = index+1;\n \n while(temp<l && s.charAt(temp)!=c)\n temp++;\n \n if(temp == l){\n temp = Integer.MAX_VALUE;\n }\n \n ptr2 = ptr1;\n ptr1 = temp;\n \n index++;\n while(index<l && index<=temp){\n ans[index] = Math.min(Math.abs(ptr1-index),Math.abs(ptr2-index));\n index++;\n }\n index--;\n }\n \n return ans;\n }\n
4
0
[]
0
shortest-distance-to-a-character
C++. O(n), Simple & easy-understanding cool solution.
c-on-simple-easy-understanding-cool-solu-235j
\tclass Solution {\n\tpublic:\n\t\tvector shortestToChar(string s, char c) {\n\t\t\tint n = s.size(), lastC = -n, i = 0;\n\t\t\tvector ans (n, n);\n\t\t\tfor (;
m-d-f
NORMAL
2021-02-07T08:55:09.667808+00:00
2021-02-07T08:56:33.623465+00:00
409
false
\tclass Solution {\n\tpublic:\n\t\tvector<int> shortestToChar(string s, char c) {\n\t\t\tint n = s.size(), lastC = -n, i = 0;\n\t\t\tvector<int> ans (n, n);\n\t\t\tfor (; i < n; ++i)\n\t\t\t{\n\t\t\t\tif ( s[i] == c ) lastC = i;\n\t\t\t\tans[i] = i - lastC;\n\t\t\t}\n\t\t\tfor (i = lastC; i >= 0; --i)\n\t\t\t{\n\t\t\t\tif ( s[i] == c ) lastC = i;\n\t\t\t\tans[i] = min(ans[i], lastC - i);\n\t\t\t}\n\t\t\treturn ans;\n\t\t}\n\t};
4
0
['C', 'C++']
0
shortest-distance-to-a-character
2 Solutions | Easy to Understand | Faster | Binary Search | Python Solution
2-solutions-easy-to-understand-faster-bi-q8b2
\n def using_solution_tab_solution(self, S, C):\n out = []\n prev = float(\'inf\')\n for i, v in enumerate(S):\n if v == C: p
mrmagician
NORMAL
2020-05-01T03:26:08.524729+00:00
2020-05-01T03:26:08.524766+00:00
845
false
```\n def using_solution_tab_solution(self, S, C):\n out = []\n prev = float(\'inf\')\n for i, v in enumerate(S):\n if v == C: prev = i\n out.append(abs(prev - i))\n prev = float(\'inf\')\n for i in range(len(S) -1 , -1 , -1):\n v = S[i]\n if v == C: prev = i\n out[i] = min(out[i], abs(prev - i))\n return out\n \n def using_binary_search(self, S, C):\n occurences = [i for i,v in enumerate(S) if v == C]\n out = []\n for i,v in enumerate(S):\n closest = self.find_closest(occurences, i)\n out.append(abs(closest - i))\n return out\n \n def find_closest(self, arr, target):\n # using binary search to find closest\n start, end = 0, len(arr) - 1\n while start < end - 1:\n mid = (start + end) // 2\n diff = arr[mid] - target\n if diff == 0: return arr[mid]\n elif diff < 0: start = mid\n else: end = mid\n # print(arr[start], arr[end])\n return arr[end] if abs(arr[end] - target) <= abs(arr[start] - target) else arr[start]\n```\n\n**I hope that you\'ve found the solution useful.**\n*In that case, please do upvote and encourage me to on my quest to document all leetcode problems\uD83D\uDE03*\nPS: Search for **mrmagician** tag in the discussion, if I have solved it, You will find it there\uD83D\uDE38
4
1
['Binary Search', 'Python', 'Python3']
0
shortest-distance-to-a-character
EASY SOLUTION
easy-solution-by-khushi_1502-i2vh
\n\n# Code\njava []\nclass Solution {\n public int[] shortestToChar(String s, char c) {\n List<Integer> l=new ArrayList<>();\n for(int i =0;i<s
khushi_1502
NORMAL
2024-11-22T10:46:37.193259+00:00
2024-11-22T10:46:37.193308+00:00
624
false
\n\n# Code\n```java []\nclass Solution {\n public int[] shortestToChar(String s, char c) {\n List<Integer> l=new ArrayList<>();\n for(int i =0;i<s.length();i++)\n {\n if(s.charAt(i)==c)\n l.add(i);\n }\n int ans[]=new int[s.length()];\n for(int i=0;i<s.length();i++)\n {\n int min=Integer.MAX_VALUE;;\n for(int j=0;j<l.size();j++)\n {\n min=Math.min(min, Math.abs(i-l.get(j)));\n }\n ans[i]=min;\n }\n return ans;\n }\n}\n```
3
0
['Java']
0
shortest-distance-to-a-character
SIMPLE TWO-POINTER C++ SOLUTION
simple-two-pointer-c-solution-by-jeffrin-x94y
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
Jeffrin2005
NORMAL
2024-07-20T12:43:10.678415+00:00
2024-07-20T12:43:41.271930+00:00
454
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:o(n+n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:o(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n\n/*\n// Example dry run with s = "loveleetcode", c = \'e\'\n// Initial state: indicesOfC = [3, 5, 6, 11], n = 12, ans = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], left = 0, right = 0\n// First iteration (i = 0 to 2): No change in right, ans updates based on distance to indicesOfC[0] = 3\n// Second iteration (i = 3): ans[3] = 0 (direct hit on \'e\')\n// Third iteration (i = 4): ans[4] = 1 (closest \'e\' at index 3 or 5)\n// Fourth iteration (i = 5): ans[5] = 0 (direct hit on \'e\')\n// Fifth iteration (i = 6): ans[6] = 0 (direct hit on \'e\')\n// Sixth iteration (i = 7 to 10): ans updates based on distance to nearest \'e\' at indices 6 or 11\n// Seventh iteration (i = 11): ans[11] = 0 (direct hit on \'e\')\n// Final result: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]\n*/\nclass Solution {\npublic:\n vector<int> shortestToChar(string s, char c) {\n vector<int> indicesOfC;\n int n = s.length();\n vector<int> ans(n);\n for (int i = 0; i < n; i++) {\n if (s[i] == c) indicesOfC.push_back(i);\n }\n int m = indicesOfC.size();\n int left = 0;\n int right = 0;\n for (int i = 0; i < n; i++) {\n if (i > indicesOfC[right] && right < m - 1) {\n left = right; // Left is crossed right so update left to right and right++ right moving for next neared right \'c\' pos \n right++;\n }\n if (right == left) {\n ans[i] = abs(indicesOfC[right] - i);\n } else {\n ans[i] = min(abs(indicesOfC[right] - i), abs(indicesOfC[left] - i));\n }\n }\n return ans;\n }\n}; \n```
3
0
['C++']
0
shortest-distance-to-a-character
Easy Explanation || 3ms
easy-explanation-3ms-by-soumya2031-gfcu
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nFirst collect all the i
soumya2031
NORMAL
2024-07-13T07:36:19.790934+00:00
2024-07-13T07:36:19.790955+00:00
568
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFirst collect all the index of required character c in the string.\nThere are only 4 possibilities \n1) element == c\n2) element lies before the first appearance of c \n3) element lies after the last appearance of c \n4) element lies in between the first and the last apperance of c.\n\n1-> in this case ans[i] = 0.\n2-> in this case ans[i] = first appearance index - i.\n3-> in this case ans[i] = i - last appearnace index\n4-> in this case ans[i] = minimum of ( i - it\'s previous appearnce index , it\'s next appearnce index - i).\n\n# Complexity\n- Time complexity:O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int[] shortestToChar(String s, char c) {\n int n = s.length();\n int[] ans =new int[n];\n\n List<Integer> li = new ArrayList<>();\n for(int i=0;i<n;i++){\n if(s.charAt(i)==c) li.add(i);\n }\n int start = 0;\n int end = li.size()-1;\n int left = -1;\n for(int i=0;i<n;i++){\n if( s.charAt(i)==c ){\n ans[i] = 0;\n left++;\n }\n else{\n if(i < li.get(start)) ans[i]=li.get(start) -i;\n else if(i > li.get(end)) ans[i]=i-li.get(end);\n else{\n ans[i]= Math.min(i-li.get(left),li.get(left+1)-i);\n }\n }\n }\n return ans;\n }\n}\n```
3
0
['Array', 'Java']
2
shortest-distance-to-a-character
Simple Java Code || Beats 100%
simple-java-code-beats-100-by-saurabh_mi-dsqj
Complexity\n- Time complexity:\nO(n)\n- Space complexity:\nO(n)\n# Code\n\nclass Solution {\n public int[] shortestToChar(String s, char c) {\n int n
Saurabh_Mishra06
NORMAL
2024-01-17T11:41:38.565187+00:00
2024-01-17T11:41:38.565209+00:00
508
false
# Complexity\n- Time complexity:\nO(n)\n- Space complexity:\nO(n)\n# Code\n```\nclass Solution {\n public int[] shortestToChar(String s, char c) {\n int n = s.length();\n int[] output = new int[n];\n int cPosition = -n;\n\n for(int i=0; i<n; i++){\n if(s.charAt(i) == c){\n cPosition = i;\n }\n output[i] = i-cPosition;\n }\n\n for(int i=n-1; i>=0; i--){\n if(s.charAt(i) == c){\n cPosition = i;\n }\n output[i] = Math.min(output[i], Math.abs(i - cPosition));\n }\n return output;\n }\n}\n```
3
0
['Java']
0
shortest-distance-to-a-character
DarkNerd | Easy Solution | Iterative way |
darknerd-easy-solution-iterative-way-by-wg9by
Approach\n- Find out two index of character \'c\' which are side by side int the array. \n- Then find the sortest diffenece for all the characters between those
darknerd
NORMAL
2024-01-12T06:23:16.736015+00:00
2024-01-12T06:23:16.736048+00:00
564
false
# Approach\n- Find out two index of character \'c\' which are side by side int the array. \n- Then find the sortest diffenece for all the characters between those two index with the calculated two index.\n- For the characters in the starting not getting bound between two indexs of \'c\' using a dummy value `-10000`.\n- And for the characters not bound between twi indexs of \'c\' for them calculating the difference betwwen there present index and last index of \'c\'.\n\n# Complexity\n- Time complexity:\n$$O(2n)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\nclass Solution {\n public int[] shortestToChar(String s, char c) {\n int n = s.length();\n int[] ans = new int[n];\n char[] arr = s.toCharArray();\n int i = -1;\n int prev = -10000;\n \n for(int j = 0; j<n; j++){\n while(arr[j] == c && i<j){\n i++;\n ans[i] = Math.min(Math.abs(i-prev), Math.abs(j-i));\n\n if(i == j){\n prev = j;\n }\n }\n }\n\n for(; i<n; i++){\n ans[i] = Math.abs(i-prev);\n }\n\n return ans;\n }\n}\n```\n![image.png](https://assets.leetcode.com/users/images/f02ede1e-5f4c-42fe-8fc1-17cec6659cd1_1705040559.6838267.png)\n
3
0
['Array', 'Two Pointers', 'Java']
0
shortest-distance-to-a-character
VERY EASY TO UNDERSTAND
very-easy-to-understand-by-honeytechie-vzq0
PLEASE UPVOTE IF YOU ANYWAY LIKE IT\n# Code\n\nclass Solution {\npublic:\n vector<int> shortestToChar(string s, char c) {\n vector<int>left(s.size(),-
honeytechie
NORMAL
2023-06-02T20:00:50.013318+00:00
2023-06-02T20:00:50.013357+00:00
565
false
# PLEASE UPVOTE IF YOU ANYWAY LIKE IT\n# Code\n```\nclass Solution {\npublic:\n vector<int> shortestToChar(string s, char c) {\n vector<int>left(s.size(),-1);\n int j=0;\n int flag=0;\n for(int i=0;i<s.size();i++)\n {\n if(s[i]==c && flag==1)\n {\n left[i]=0;\n j=0;\n }\n if(s[i]==c)\n {\n left[i]=0;\n j=1;\n flag=1;\n }\n else if(s[i]!=c && flag==1)\n {\n left[i]=j++;\n }\n }\n vector<int>right(s.size(),-1);\n j=0;\n flag=0;\n for(int i=s.size()-1;i>=0;i--)\n {\n if(s[i]==c && flag==1)\n {\n right[i]=0;\n j=0;\n }\n if(s[i]==c)\n {\n right[i]=0;\n j=1;\n flag=1;\n }\n else if(s[i]!=c && flag==1)\n {\n right[i]=j++;\n }\n }\n vector<int>hny;\n for(int i=0;i<s.size();i++)\n {\n if(left[i]>=0 && right[i]>=0)\n {\n hny.push_back(min(left[i],right[i]));\n }\n else \n hny.push_back(max(left[i],right[i]));\n }\n return hny;\n }\n};\n```
3
0
['C++']
0
shortest-distance-to-a-character
Solution in C++
solution-in-c-by-ashish_madhup-5gg1
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
ashish_madhup
NORMAL
2023-04-15T17:34:45.053926+00:00
2023-04-15T17:34:45.053970+00:00
470
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> shortestToChar(string s, char c)\n {\n vector<int>indexes;\n vector<int>sol;\n for(int i = 0; i < s.length(); i++)\n {\n if(s[i] == c) indexes.push_back(i);\n }\n for(int i = 0; i < s.length(); i++)\n {\n int min_dist = 10000;\n for(int j : indexes)\n {\n min_dist = min(min_dist,abs(j-i));\n }\n sol.push_back(min_dist);\n }\n return sol;\n }\n};\n```
3
0
['C++']
0
shortest-distance-to-a-character
easy cpp solution
easy-cpp-solution-by-mohiteravi348-iiob
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
mohiteravi348
NORMAL
2023-01-27T05:12:06.992205+00:00
2023-01-27T05:12:06.992237+00:00
1,001
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> shortestToChar(string s, char c) {\n vector<int>ind;\n vector<int>ans;\n for(int i=0;i<s.size();i++) {\n if(s[i]==c)ind.push_back(i);\n }\n \n for(int i=0;i<s.size();i++){\n int d=100000;\n for(int j=0;j<ind.size();j++){\n int d2 = abs(i-ind[j]);\n if(d2<d)d=d2;\n } \n ans.push_back(d);\n }\n return ans;\n }\n};\n```
3
0
['C++']
0
shortest-distance-to-a-character
Java || Brute Force Solution
java-brute-force-solution-by-ritabrata_1-lq3r
\nclass Solution {\n public int[] shortestToChar(String s, char c) {\n List<Integer> list = new ArrayList<>();\n char c1[] = s.toCharArray();\n
Ritabrata_1080
NORMAL
2022-10-03T18:51:42.634048+00:00
2022-10-03T18:51:42.634101+00:00
1,129
false
```\nclass Solution {\n public int[] shortestToChar(String s, char c) {\n List<Integer> list = new ArrayList<>();\n char c1[] = s.toCharArray();\n for(int i = 0;i<c1.length;i++){\n if(c1[i] == c){\n list.add(i);\n }\n }\n int res[] = new int[c1.length];\n for(int i = 0;i<res.length;i++){\n int min = Integer.MAX_VALUE;\n for(int p : list){\n min = Math.min(min, Math.abs(i-p));\n }\n res[i] = min;\n }\n return res;\n }\n}\n```
3
0
['Java']
1
shortest-distance-to-a-character
Simple Javascript solution - faster than 80% only 1 loop
simple-javascript-solution-faster-than-8-b5co
You just push a 0 if the char is the c, and if not you calculate the min between the distance of the last 0 and the next c in the string using indexOf and lastI
dmarcosc
NORMAL
2022-07-22T17:55:03.631198+00:00
2022-07-22T17:55:03.631248+00:00
355
false
You just push a 0 if the char is the c, and if not you calculate the min between the distance of the last 0 and the next c in the string using indexOf and lastIndexOf\n\n````\n/**\n * @param {string} s\n * @param {character} c\n * @return {number[]}\n */\nvar shortestToChar = function(s, c) {\n \n let result = []\n \n for(let i = 0; i< s.length ; i++) {\n \n if(s.charAt(i) === c) result.push(0)\n else {\n const next = s.indexOf(c,i) === -1 ? Infinity : s.indexOf(c,i) -i\n const prev = result.lastIndexOf(0) === -1 ? Infinity : i- result.lastIndexOf(0) \n result.push(Math.min(next,prev))\n }\n \n }\n \n return result\n};\n````
3
0
['JavaScript']
0
shortest-distance-to-a-character
Java || 98% faster / only one loop / simple / efficient /
java-98-faster-only-one-loop-simple-effi-dniz
\nclass Solution {\n public int[] shortestToChar(String s, char c) {\n int[] ans = new int[s.length()];\n \n for (int i = 0, j = 0; i <
csarmien318
NORMAL
2021-10-26T15:49:46.753273+00:00
2021-10-26T15:49:46.753315+00:00
603
false
```\nclass Solution {\n public int[] shortestToChar(String s, char c) {\n int[] ans = new int[s.length()];\n \n for (int i = 0, j = 0; i < ans.length; i++) {\n if (i == 0) j = s.indexOf(c);\n if (i > j && s.indexOf(c, i) >= 0 && Math.abs(j-i) > Math.abs(s.indexOf(c, i)-i)) {\n j = s.indexOf(c, i);\n }\n ans[i] = Math.abs(j-i);\n }\n \n return ans;\n }\n}\n```
3
0
['Java']
1
shortest-distance-to-a-character
C++ | O(n) | Easy to Understand
c-on-easy-to-understand-by-mantavya-7259
\n\n\nclass Solution {\npublic:\n vector<int> shortestToChar(string s, char c) {\n \n int n=s.length();\n vector<int>ans(n,0);\n
mantavya
NORMAL
2021-02-08T19:36:34.887093+00:00
2021-02-08T19:39:41.474457+00:00
124
false
\n```\n\nclass Solution {\npublic:\n vector<int> shortestToChar(string s, char c) {\n \n int n=s.length();\n vector<int>ans(n,0);\n int lp=-999999;\n \n for(int i=0;i<n;i++)\n {\n if(s[i]==c)\n lp=i;\n \n ans[i]=i-lp;\n }\n \n lp=INT_MAX;\n for(int i=n-1;i>=0;i--)\n {\n if(s[i]==c)\n lp=i;\n \n ans[i]=min(ans[i],lp-i);\n }\n\n return ans;\n \n }\n};\n```\n**Upvote if found helpful**
3
0
[]
0
shortest-distance-to-a-character
Any language | Two pass | O(n), 0ms | Very easy with detailed explanation | Example on Golang
any-language-two-pass-on-0ms-very-easy-w-hemo
How to find a minimal distance? We need to take into consideration only distance from closest letters from left and right side. No need to count distance from f
el777
NORMAL
2021-02-07T21:14:42.182883+00:00
2021-02-07T21:15:43.995611+00:00
157
false
How to find a minimal distance? We need to take into consideration only distance from closest letters from left and right side. No need to count distance from far remote letters.\n\n\nNext, when we see a part of a string like here and suppose we want to calculate distance from `o` to closest `e`\'s.\n```\nleetcode\n ^\n```\nLet\'s split a task into 2 symmetrical ones: distance from left letter and distance from right letter.\n\nHow to calculate and store distance from left `e`? Just walk through the string and check - if we see letter `e` then its distance is 0, and with any another letter distance increments by 1.\n\nSo distances between letters `e` will be (I\'ve added extra space between letters for readibility):\n\n```\nl e e t c o d e\n ^\n\t\t 0 1 2 3 4 5\n```\n\nNext, go from right with the same distance calculation. But this time check if there\'s a closer letter `e` from another side.\n\nWe may code this using any language only with standard operators and arrays. \nHere\'s an example on Golang.\n\n```golang\nfunc shortestToChar(s string, c byte) []int {\n\t// cache string length\n var lens = len(s)\n\t// prepare a storage for the result \n\t// slice (or array, vector) with length equal to len(s) initialized with zeros\n var res = make([]int, lens)\n \n // current distance from last seen letter `c`\n // we start with increadibly high value to show it\'s invalid\n var dist = lens + 100\n \n // scan from left to right, increase distance from last seen letter\n // flush distance to zero at every new seen required letter\n for i := 0; i < lens; i++ {\n if s[i] == c {\n dist = 0\n }\n res[i] = dist\n dist++\n }\n \n // the same backwards \n // but also check if we have less distance from opposite letter\n for i := lens-1; i >=0; i-- {\n if s[i] == c {\n dist = 0\n }\n if dist < res[i] {\n res[i] = dist\n }\n dist++\n }\n \n return res\n}\n```
3
0
['Go']
0
shortest-distance-to-a-character
Java Solution linear time
java-solution-linear-time-by-govindshaky-0ciy
```\nclass Solution \n{\n public int[] shortestToChar(String s, char c) \n {\n int l = -1;\n int r = s.indexOf(c);\n int[] ans = new
govindshakya
NORMAL
2021-02-07T14:52:09.640481+00:00
2021-02-07T14:52:09.640520+00:00
85
false
```\nclass Solution \n{\n public int[] shortestToChar(String s, char c) \n {\n int l = -1;\n int r = s.indexOf(c);\n int[] ans = new int[s.length()];\n \n for(int i = 0 ; i < s.length() ; i++)\n {\n if(s.charAt(i) == c )\n {\n l = r;\n \n if(s.substring(i+1).indexOf(c) == -1)\n r = -1;\n else\n r = (i+1) + s.substring(i+1).indexOf(c);\n }\n \n if(r == -1)\n ans[i] = i-l;\n else if(l == -1)\n ans[i] = r-i;\n else if(r != -1 && l != -1)\n ans[i] = Math.min(i - l , r - i);\n }\n \n return ans;\n }\n}
3
0
[]
0
shortest-distance-to-a-character
Declarative JavaScript Solution using Array.reduce() and Array.map()
declarative-javascript-solution-using-ar-6jkl
Modern declarative JavaScript use of string destructuring and array methods.\n\nPlease keep in mind, this is an example of declarative JavaScript programming vs
mrchakooo
NORMAL
2020-09-30T17:40:48.311398+00:00
2020-09-30T17:40:48.311431+00:00
209
false
Modern declarative JavaScript use of string destructuring and array methods.\n\nPlease keep in mind, this is an example of declarative JavaScript programming vs imperative solutions.\nThe solution won\'t be the fastest or the most memory efficient.\n\nHere\'s some references if you\'re more interested about what reduce and map can do:\nhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce\nhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map\n\n```\nvar shortestToChar = function(S, C) {\n \n // We create an array of indices of where the character C occurs\n //\n // [...S] is a string destructuring, we turn the string into an array\n // of characters (in JavaScript, it\'s really just single character strings)\n //\n // On this new string array, we use Array.reduce(), which is a powerful way of\n // exploring arrays with a callback function. The callback function in this example is\n // (acc, currC, ind) => currC === C ? [...acc, ind] : acc\n // which is stating "for each element, take the \'Accumulator\', \'Current Element\', and \'Index\'\n // and return what our next accumulator will be". The accumulator was initialized to be\n // an empty array and if the character matches, we copy our current accumulator array into\n // a new array and append the current Index. If it doesn\'t match, just return our Accumulator\n //\n // The ultimate result is our accumulator, which is an array of indices.\n \n const indexesOfC = [...S].reduce(\n (acc, currC, currInd) => currC === C ? [...acc, currInd] : acc\n , [])\n \n // Here, we are mapping each character to a number. This is the perfect time\n // to use Array.map()! Array.map also uses a callback function, but this time it\'s\n // (char, ind) => <some code returning what we want to map>\n // "char" being "Current Element" and "ind" being an optional parameter "Current Index"\n //\n // We then run an Array.reduce() on our indices of character C. This time the accumulator\n // is going to be recording the shortest distance from the current S index to the closest\n // C index. We return the smaller of the saved value (acc) and the distance (Math.abs(ind - curr))\n //\n // Note that the accumulator is initially set to Infinity. You can also use Number.MAX_VALUE.\n \n return [...S].map((char, ind) => \n indexesOfC.reduce((acc, curr) => \n Math.min(acc, Math.abs(ind - curr))\n , Infinity)\n )\n};\n```
3
0
['JavaScript']
0
shortest-distance-to-a-character
javascript solution
javascript-solution-by-wvha-6cn7
Probably not the best solution but it\'s straightforward and works \n\nSteps:\n- initialize an array \n- Loop through the string\n- find the closest character C
wvha
NORMAL
2019-12-30T22:59:49.080827+00:00
2019-12-30T23:00:31.186690+00:00
376
false
Probably not the best solution but it\'s straightforward and works \n\nSteps:\n- initialize an array \n- Loop through the string\n- find the closest character C with a helper function \n\n- at each letter, calculate and return the distance of the closest C \n- push that value distance to the array \n\n\n```\nvar shortestToChar = function(S, C) {\n let arr = []\n for (let i = 0; i < S.length; i++) {\n // should return i of the closest character\n let closest = findClosest(i, S, C); \n \n // add to array \n arr.push(closest)\n }\n return arr\n};\n\nvar findClosest = function(i, S, C) {\n if (S[i] === C) return 0\n \n let j = 1\n\t// set limits for beginning and end of S string\n while (i >= 0 || i <= S.length) {\n\t\t// checks the character in either direction by j units\n if (S[i + j] === C || S[i - j] === C) {\n return j;\n }\n j++;\n }\n}\n```
3
0
['JavaScript']
1
shortest-distance-to-a-character
Python, with comments
python-with-comments-by-jcchoi-xg19
\'\'\'\nclass Solution(object):\n def shortestToChar(self, S, C):\n\n res = []\n pos = [] \n \n # keep indexes of C in S\n
jcchoi
NORMAL
2019-12-05T03:42:59.735038+00:00
2019-12-05T03:42:59.735074+00:00
287
false
\'\'\'\nclass Solution(object):\n def shortestToChar(self, S, C):\n\n res = []\n pos = [] \n \n # keep indexes of C in S\n for i in range(len(S)):\n if S[i] == C:\n pos.append(i) \n \n for i in range(len(S)):\n # set default value as length of S\n\t\t\tmn = len(S) \n for p in pos: \n # calculate minimum value of distance\n\t\t\t\tmn = min(mn, abs(i-p)) \n res.append(mn)\n return res\n\'\'\'
3
0
['Python']
0
shortest-distance-to-a-character
Python 3 O(1) auxiliary space one traversal algorithm
python-3-o1-auxiliary-space-one-traversa-cn86
Instead of keeping O(2N) minimum distance list by traversing twice, I just kept the length of the substring that exists between the character C or edge and outp
ypark66
NORMAL
2019-10-22T19:19:34.789941+00:00
2019-10-22T19:24:23.114361+00:00
574
false
Instead of keeping O(2N) minimum distance list by traversing twice, I just kept the length of the substring that exists between the character C or edge and output the distance.\n```\n def shortestToChar(self, S: str, C: str) -> List[int]:\n r, seen_c, l = [], False, 0\n for w in S:\n if w == C:\n if seen_c: # C"substring"C\n for i in range(1,l//2+1):\n r.append(i)\n for i in range(l//2+l%2,0,-1):\n r.append(i)\n else: # ["substring"C\n for i in range(l,0,-1):\n r.append(i)\n seen_c, l = True, 0\n r.append(0)\n else:\n l += 1\n for i in range(1,l+1): # C"substring"]\n r.append(i)\n return r\n```
3
0
['Python', 'Python3']
2
shortest-distance-to-a-character
python oneliner
python-oneliner-by-renzhang88-pdau
return [min(abs(i - ll) for ll in [i for i, e in enumerate(S) if e == C]) for i in range(len(S))]
renzhang88
NORMAL
2018-04-22T13:22:30.466868+00:00
2018-10-25T14:39:00.376769+00:00
776
false
return [min(abs(i - ll) for ll in [i for i, e in enumerate(S) if e == C]) for i in range(len(S))]
3
2
[]
3
shortest-distance-to-a-character
Check At Once and you dont have need to Check another solution..♥
check-at-once-and-you-dont-have-need-to-pd6kq
IntuitionApproach first i created arraylist in which i stored a index of that character to compare a minimum distance between indexes; and then iterate a loop t
AbhiBhingole
NORMAL
2025-04-02T13:26:01.687640+00:00
2025-04-02T13:26:01.687640+00:00
82
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> 1) first i created arraylist in which i stored a index of that character to compare a minimum distance between indexes; 2) and then iterate a loop through string and check which distance is minimum from that index (use list to check minimum distance and i also used abs(which provide a positive value), math.min funciton(which provide a minimum numbe))... 3) check solution for more understanding..♥ ![49h9ra.jpg](https://assets.leetcode.com/users/images/4c8e89c2-71f3-4121-96a7-c84b5eac949f_1743600357.2126265.jpeg) # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public int[] shortestToChar(String s, char c) { List<Integer>list = new ArrayList<>(); for(int i = 0; i<s.length(); i++){ if(s.charAt(i)==c){ list.add(i); } } int ans[] = new int[s.length()]; for(int i = 0; i<s.length(); i++){ int min = Integer.MAX_VALUE; for(int j = 0; j<list.size(); j++){ min = Math.min(min,Math.abs(i-list.get(j))); } ans[i] = min; } return ans; } } ```
2
0
['Java']
0
shortest-distance-to-a-character
submission beat 100% of other submissions' runtime|| just simple traversing || TC->O(N)|| SC->O(N)||
submission-beat-100-of-other-submissions-7adr
IntuitionApproachComplexity Time complexity: Space complexity: Code
Rohan07_6473
NORMAL
2025-02-07T14:04:53.426682+00:00
2025-02-07T14:04:53.426682+00:00
235
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 { public: vector<int> shortestToChar(string s, char c) { int n = s.size(); vector<int>ans(n ,INT_MAX); //for returnnumg the ans int prev =-1; //because it is pointing to the given c character // for left to right for(int i =0 ;i<n ;i++){ if(s[i] == c){ prev =i ; //prev pointing to the given c } if(prev!=-1){ ans[i]=abs(i-prev); } } //for right to left prev =-1; // assign this -1 second time for calculating for(int i = n-1 ;i>=0 ;i--){ if(s[i] == c){ prev =i ; } if(prev!= -1){ ans[i] =min(ans[i] , abs(prev-i)); //min of the current calculation or which are already store in the ans vector } } return ans; } }; ```
2
0
['C++']
0
shortest-distance-to-a-character
Easy solution using arrays | 100% beats
easy-solution-using-arrays-100-beats-by-jdm1o
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
RAVINDRAN_S
NORMAL
2024-11-21T05:05:56.256221+00:00
2024-11-21T05:05:56.256242+00:00
33
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(n^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<int> shortestToChar(string s, char c) {\n vector<int>r;\n for (int i=0;i<s.size();i++){\n if (s[i]==c){\n r.push_back(i);\n }\n }\n vector<int>ans;\n \n for (int j=0;j<s.size();j++){\n int minm=INT_MAX;\n for (int a=0;a<r.size();a++){\n minm=min(minm,abs(j-r[a]));\n \n }\n ans.push_back(minm);\n \n }\n return ans;\n }\n};\n```
2
0
['C++']
0
shortest-distance-to-a-character
2 Pass Solution | O(n) time, O(1) auxiliary space | Python
2-pass-solution-on-time-o1-auxiliary-spa-fp27
Complexity\n- Time complexity: O(n)\n- Auxiliary Space complexity: O(1)\n- Overall Space complexity: O(n)\n\n# Code\n\nclass Solution:\n def shortestToChar(s
HariShankarKarthik
NORMAL
2024-06-07T00:33:08.221000+00:00
2024-06-07T00:33:08.221027+00:00
171
false
# Complexity\n- Time complexity: $$O(n)$$\n- Auxiliary Space complexity: $$O(1)$$\n- Overall Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution:\n def shortestToChar(self, s: str, c: str) -> List[int]:\n n = len(s)\n result = [float(\'inf\') for _ in range(n)]\n \n shortest_dist = n - 1\n for i in range(n):\n if s[i] == c:\n shortest_dist = 0\n \n result[i] = shortest_dist\n shortest_dist += 1\n \n shortest_dist = n - 1\n for i in range(n - 1, -1, -1):\n if s[i] == c:\n shortest_dist = 0\n \n result[i] = min(result[i], shortest_dist)\n shortest_dist += 1\n \n return result\n\n # O(n) time\n # O(1) auxiliary space\n```
2
0
['Array', 'Two Pointers', 'String', 'Python', 'Python3']
0
shortest-distance-to-a-character
simple and easy C++ solution 😍❤️‍🔥
simple-and-easy-c-solution-by-shishirrsi-9c2r
if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n\n# Code\n\nclass Solution {\npublic:\n vector<int> shortestToChar(string s, char c) \n {\n i
shishirRsiam
NORMAL
2024-05-24T16:03:49.875657+00:00
2024-05-24T16:03:49.875697+00:00
524
false
# if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> shortestToChar(string s, char c) \n {\n int n = s.size();\n vector<int>ans, idx;\n for(int i=0;i<n;i++)\n if(s[i]==c) idx.push_back(i);\n \n int cur = 0, next = 1, flag = true;\n for(int i=0;i<n;i++)\n {\n if(next < idx.size())\n ans.push_back(min(abs(idx[cur] - i), abs(idx[next] - i)));\n else ans.push_back(abs(idx[cur] - i));\n if(s[i]==c and flag) flag = false;\n else if(s[i]==c and !flag) cur++, next++;\n if(cur == idx.size()) cur--;\n }\n return ans;\n }\n};\n```
2
0
['Array', 'Two Pointers', 'String', 'C++']
3