teleren/devto huggingface dataset:
963. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-13 10:36:27

```
class Solution {
 public:
  double minAreaFreeRect(vector<vector<int>>& points) {
    long long ans = LLONG_MAX;
    // for each A, B pair points, {hash(A, B): (ax, ay, bx, by)}
    unordered_map<int, vector<tuple<int, int, int, int>>> centerToPoints;

    for (const auto& A : points)
      for (const auto& B : points) {
        const int center = hash(A, B);
        centerToPoints[center].emplace_back(A[0], A[1], B[0], B[1]);
      }

    // for all pair points "that share the same center"
    for (const auto& [_, points] : centerToPoints)
      for (const auto& [ax, ay, bx, by] : points)
        for (const auto& [cx, cy, dx, dy] : points)
          // AC is perpendicular to AD
          // AC dot AD = (cx - ax, cy - ay) dot (dx - ax, dy - ay) == 0
          if ((cx - ax) * (dx - ax) + (cy - ay) * (dy - ay) == 0) {
            const long long squaredArea =
                dist(ax, ay, cx, cy) * dist(ax, ay, dx, dy);
            if (squaredArea > 0)
              ans = min(ans, squaredArea);
          }

    return ans == LLONG_MAX ? 0 : sqrt(ans);
  }

 private:
  int hash(const vector<int>& p, const vector<int>& q) {
    return ((long long)(p[0] + q[0]) << 16) + (p[1] + q[1]);
  }

  long long dist(int px, int py, int qx, int qy) {
    return (px - qx) * (px - qx) + (py - qy) * (py - qy);
  }
};

```
#Leetcode
#challende
Here is the link for the problem:
https://leetcode.com/problems/minimum-area-rectangle-ii/
962. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-13 10:35:11

```
class Solution {
 public:
  int maxWidthRamp(vector<int>& nums) {
    int ans = 0;
    stack<int> stack;

    for (int i = 0; i < nums.size(); ++i)
      if (stack.empty() || nums[i] < nums[stack.top()])
        stack.push(i);

    for (int i = nums.size() - 1; i > ans; --i)
      while (!stack.empty() && nums[i] >= nums[stack.top()])
        ans = max(ans, i - stack.top()), stack.pop();

    return ans;
  }
};

```
#Leetcode
#challende
Here is the link for the problem:
https://leetcode.com/problems/maximum-width-ramp/
998. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-13 10:34:25

```
class Solution {
 public:
  TreeNode* insertIntoMaxTree(TreeNode* root, int val) {
    if (!root)
      return new TreeNode(val);
    if (root->val < val)
      return new TreeNode(val, root, nullptr);
    root->right = insertIntoMaxTree(root->right, val);
    return root;
  }
};

```

#Leetcode
#challende
Here is the link for the problem:
https://leetcode.com/problems/maximum-binary-tree-ii/
623. Leetcode Solution in Java
Tags: java
Published: 2022-07-13 10:32:24

```
class Solution {
  public TreeNode addOneRow(TreeNode root, int v, int d) {
    if (d == 1) {
      TreeNode newRoot = new TreeNode(v);
      newRoot.left = root;
      return newRoot;
    }

    int depth = 0;
    Queue<TreeNode> q = new ArrayDeque<>(Arrays.asList(root));

    while (!q.isEmpty()) {
      ++depth;
      for (int sz = q.size(); sz > 0; --sz) {
        TreeNode node = q.poll();
        if (node.left != null)
          q.offer(node.left);
        if (node.right != null)
          q.offer(node.right);
        if (depth == d - 1) {
          TreeNode cachedLeft = node.left;
          TreeNode cachedRight = node.right;
          node.left = new TreeNode(v);
          node.right = new TreeNode(v);
          node.left.left = cachedLeft;
          node.right.right = cachedRight;
        }
      }
      if (depth == d - 1)
        break;
    }

    return root;
  }
}

```
#Leetcode
#challende
Here is the link for the problem:
https://leetcode.com/problems/add-one-row-to-tree/
623. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-13 10:31:57

```
class Solution {
 public:
  TreeNode* addOneRow(TreeNode* root, int v, int d) {
    if (d == 1) {
      TreeNode* newRoot = new TreeNode(v);
      newRoot->left = root;
      return newRoot;
    }

    int depth = 0;
    queue<TreeNode*> q{{root}};

    while (!q.empty()) {
      ++depth;
      for (int sz = q.size(); sz > 0; --sz) {
        TreeNode* node = q.front();
        q.pop();
        if (node->left)
          q.push(node->left);
        if (node->right)
          q.push(node->right);
        if (depth == d - 1) {
          TreeNode* cachedLeft = node->left;
          TreeNode* cachedRight = node->right;
          node->left = new TreeNode(v);
          node->right = new TreeNode(v);
          node->left->left = cachedLeft;
          node->right->right = cachedRight;
        }
      }
      if (depth == d - 1)
        break;
    }

    return root;
  }
};

```
#Leetcode
#challende
Here is the link for the problem:
https://leetcode.com/problems/add-one-row-to-tree/
Jetpack compose: Custom animations
Tags: android, jetpackcompose, animations, androiddev
Published: 2022-07-13 10:31:04


## Wanna learn how to design custom [animations](https://blog.canopas.com/animations-in-jetpack-compose-with-examples-48307ba9dff1) in [Jetpack Compose](https://blog.canopas.com/jetpack-compose-mvvm-state-management-in-a-simple-way-4c632fa6f554)?

This article will help you learn how to implement super cool custom animations using Jetpack compose in [Android](https://blog.canopas.com/android-drag-and-drop-ui-element-in-jetpack-compose-14922073b3f1).

### We are going to implement four different animations in this post.


{% 
 embed 
https://cdn.hashnode.com/res/hashnode/image/upload/v1657707693100/47e5jaar7.gif align="left"}

1. **Heartbeat animation:** This animation contains a heart-shaped image and we will animate it in such a way that it looks like a beating heart.

2. **Wiggle animation:** In this animation, we will have a square box and we will provide a wiggling effect on the box.

3. **Flash animation:**In this animation, we will have a square box and we will provide a flashing effect on the box.

4. **[Chasing circle animation](https://blog.canopas.com/progress-animations-in-jetpack-compose-with-examples-eb76cc28fbb6)**: This animation contains multiple arcs and a circle and we will provide scaling and rotating effects on them.

Don’t worry if you didn’t get all the animations.

Check out the project on [GitHub](https://gitlab.com/cp-hardik-p/customanimations) for the complete working solution and example.

Read full version of this post on [canopas blog](https://blog.canopas.com/jetpack-compose-custom-animations-550dcdcded83).
662. Leetcode Solution in Java
Tags: java
Published: 2022-07-13 10:30:16

```
class Solution {
  public int widthOfBinaryTree(TreeNode root) {
    if (root == null)
      return 0;

    int ans = 0;
    Deque<Pair<TreeNode, Integer>> q = new ArrayDeque<>(); // {node, index}
    q.offer(new Pair<>(root, 1));

    while (!q.isEmpty()) {
      final int offset = q.peekFirst().getValue() * 2;
      ans = Math.max(ans, q.peekLast().getValue() - q.peekFirst().getValue() + 1);
      for (int sz = q.size(); sz > 0; --sz) {
        final TreeNode node = q.peekFirst().getKey();
        final int index = q.pollFirst().getValue();
        if (node.left != null)
          q.offer(new Pair<>(node.left, index * 2 - offset));
        if (node.right != null)
          q.offer(new Pair<>(node.right, index * 2 + 1 - offset));
      }
    }

    return ans;
  }
}

```
#Leetcode
#challende
Here is the link for the problem:
https://leetcode.com/problems/maximum-width-of-binary-tree/
688. Leetcode Solution in Java
Tags: java
Published: 2022-07-13 10:29:17

```
class Solution {
  public double knightProbability(int N, int K, int r, int c) {
    final double kProb = 0.125;
    final int[][] dirs = {{-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}};

    // dp[i][j] := probability to stand on (i, j)
    double[][] dp = new double[N][N];
    dp[r][c] = 1.0;

    for (int k = 0; k < K; ++k) {
      double[][] newDp = new double[N][N];
      for (int i = 0; i < N; ++i)
        for (int j = 0; j < N; ++j)
          if (dp[i][j] > 0.0) {
            for (int[] dir : dirs) {
              final int x = i + dir[0];
              final int y = j + dir[1];
              if (x < 0 || x >= N || y < 0 || y >= N)
                continue;
              newDp[x][y] += dp[i][j] * kProb;
            }
          }
      dp = newDp;
    }

    double ans = 0.0;

    for (double[] row : dp)
      ans += Arrays.stream(row).sum();

    return ans;
  }
}

```

#Leetcode
#challende
Here is the link for the problem:
https://leetcode.com/problems/knight-probability-in-chessboard/
688. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-13 10:28:42

```
class Solution {
 public:
  double knightProbability(int N, int K, int r, int c) {
    constexpr double kProb = 0.125;
    const vector<pair<int, int>> dirs{{-2, 1}, {-1, 2}, {1, 2},   {2, 1},
                                      {2, -1}, {1, -2}, {-1, -2}, {-2, -1}};

    // dp[i][j] := probability to stand on (i, j)
    vector<vector<double>> dp(N, vector<double>(N));
    dp[r][c] = 1.0;

    for (int k = 0; k < K; ++k) {
      vector<vector<double>> newDp(N, vector<double>(N));
      for (int i = 0; i < N; ++i)
        for (int j = 0; j < N; ++j)
          if (dp[i][j] > 0.0) {
            for (const auto& [dx, dy] : dirs) {
              const int x = i + dx;
              const int y = j + dy;
              if (x < 0 || x >= N || y < 0 || y >= N)
                continue;
              newDp[x][y] += dp[i][j] * kProb;
            }
          }
      dp = move(newDp);
    }

    return accumulate(begin(dp), end(dp), 0.0,
                      [](double s, vector<double>& row) {
      return s + accumulate(begin(row), end(row), 0.0);
    });
  }
};

```
#Leetcode
#challende
Here is the link for the problem:
https://leetcode.com/problems/knight-probability-in-chessboard/
684. Leetcode Solution in JavaScript
Tags: javascript
Published: 2022-07-13 10:27:48

```
var findRedundantConnection = function(edges) {
    let par = Array.from({length: edges.length + 1}, (_,i) => i)
    const find = x => x === par[x] ? par[x] : par[x] = find(par[x])
    const union = (x,y) => par[find(y)] = find(x)
    for (let [a,b] of edges)
        if (find(a) === find(b)) return [a,b]
        else union(a,b)
};
```
#Leetcode
#challende
Here is the link for the problem:
https://leetcode.com/problems/redundant-connection/
947. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-13 10:26:18

```
class Solution {
 public:
  int removeStones(vector<vector<int>>& stones) {
    int numOfIslands = 0;
    vector<vector<int>> graph(stones.size());
    unordered_set<int> seen;

    for (int i = 0; i < stones.size(); ++i)
      for (int j = i + 1; j < stones.size(); ++j)
        if (stones[i][0] == stones[j][0] || stones[i][1] == stones[j][1]) {
          graph[i].push_back(j);
          graph[j].push_back(i);
        }

    for (int i = 0; i < stones.size(); ++i)
      if (seen.insert(i).second) {
        dfs(graph, i, seen);
        ++numOfIslands;
      }

    return stones.size() - numOfIslands;
  }

 private:
  void dfs(const vector<vector<int>>& graph, int u, unordered_set<int>& seen) {
    for (const int v : graph[u])
      if (seen.insert(v).second)
        dfs(graph, v, seen);
  }
};

```

#Leetcode
#challende
Here is the link for the problem:
https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/
947. Leetcode Solution in Java
Tags: java
Published: 2022-07-13 10:25:47

```
class Solution {
  public int removeStones(int[][] stones) {
    int numOfIslands = 0;
    List<Integer>[] graph = new List[stones.length];
    Set<Integer> seen = new HashSet<>();

    for (int i = 0; i < graph.length; ++i)
      graph[i] = new ArrayList<>();

    for (int i = 0; i < stones.length; ++i)
      for (int j = i + 1; j < stones.length; ++j)
        if (stones[i][0] == stones[j][0] || stones[i][1] == stones[j][1]) {
          graph[i].add(j);
          graph[j].add(i);
        }

    for (int i = 0; i < stones.length; ++i)
      if (seen.add(i)) {
        dfs(graph, i, seen);
        ++numOfIslands;
      }

    return stones.length - numOfIslands;
  }

  private void dfs(List<Integer>[] graph, int u, Set<Integer> seen) {
    for (final int v : graph[u])
      if (seen.add(v))
        dfs(graph, v, seen);
  }
}

```
#Leetcode
#challende
Here is the link for the problem:
https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/
983. Leetcode Solution in Java
Tags: java
Published: 2022-07-13 10:24:42

```
class Solution {
  public int mincostTickets(int[] days, int[] costs) {
    int ans = 0;
    Queue<int[]> last7 = new ArrayDeque<>(); // [day, cost]
    Queue<int[]> last30 = new ArrayDeque<>();

    for (int day : days) {
      while (!last7.isEmpty() && last7.peek()[0] + 7 <= day)
        last7.poll();
      while (!last30.isEmpty() && last30.peek()[0] + 30 <= day)
        last30.poll();
      last7.offer(new int[] {day, ans + costs[1]});
      last30.offer(new int[] {day, ans + costs[2]});
      ans = Math.min(ans + costs[0], Math.min(last7.peek()[1], last30.peek()[1]));
    }

    return ans;
  }
}

```
#Leetcode
#challende
Here is the link for the problem:
https://leetcode.com/problems/minimum-cost-for-tickets/
983. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-13 10:24:10

```
class Solution {
 public:
  int mincostTickets(vector<int>& days, vector<int>& costs) {
    int ans = 0;
    queue<pair<int, int>> last7;
    queue<pair<int, int>> last30;

    for (int day : days) {
      while (!last7.empty() && last7.front().first + 7 <= day)
        last7.pop();
      while (!last30.empty() && last30.front().first + 30 <= day)
        last30.pop();
      last7.emplace(day, ans + costs[1]);
      last30.emplace(day, ans + costs[2]);
      ans = min({ans + costs[0], last7.front().second, last30.front().second});
    }

    return ans;
  }
};

```
#Leetcode
#challende
Here is the link for the problem:
https://leetcode.com/problems/minimum-cost-for-tickets/
999. Leetcode Solution in Java
Tags: java
Published: 2022-07-13 10:23:21

```
class Solution {
  public int numRookCaptures(char[][] board) {
    int ans = 0;
    int i0 = 0;
    int j0 = 0;

    for (int i = 0; i < 8; ++i)
      for (int j = 0; j < 8; ++j)
        if (board[i][j] == 'R') {
          i0 = i;
          j0 = j;
        }

    for (int[] d : new int[][] {{1, 0}, {0, 1}, {-1, 0}, {0, -1}})
      for (int i = i0 + d[0], j = j0 + d[1]; 0 <= i && i < 8 && 0 <= j && j < 8;
           i += d[0], j += d[1]) {
        if (board[i][j] == 'p')
          ++ans;
        if (board[i][j] != '.')
          break;
      }

    return ans;
  }
}

```
#Leetcode
#challende
Here is the link for the problem:
https://leetcode.com/problems/available-captures-for-rook/
999. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-13 10:22:17

```
class Solution {
 public:
  int numRookCaptures(vector<vector<char>>& board) {
    int ans = 0;
    int i0 = 0;
    int j0 = 0;

    for (int i = 0; i < 8; ++i)
      for (int j = 0; j < 8; ++j)
        if (board[i][j] == 'R') {
          i0 = i;
          j0 = j;
        }

    for (auto d : vector<vector<int>>({{1, 0}, {0, 1}, {-1, 0}, {0, -1}}))
      for (int i = i0 + d[0], j = j0 + d[1]; 0 <= i && i < 8 && 0 <= j && j < 8;
           i += d[0], j += d[1]) {
        if (board[i][j] == 'p')
          ++ans;
        if (board[i][j] != '.')
          break;
      }

    return ans;
  }
};

```
#Leetcode
#challende
Here is the link for the problem:
https://leetcode.com/problems/available-captures-for-rook/
1022. Leetcode Solution in Java
Tags: java
Published: 2022-07-13 10:15:32

```
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    int res;
public int sumRootToLeaf(TreeNode root) {
    dfs(root, 0);
    return res;
}

void dfs(TreeNode node, int num) {
    if (node == null) return;
    num = (num << 1) + node.val;
    if (node.left == null && node.right == null) {
        res += num;
        return;
    }
    dfs(node.left, num);
    dfs(node.right, num);
}
   
}
```
#Leetcode
#challende
Here is the link for the problem:
https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/
1015. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-13 10:14:08

```
class Solution {
 public:
  int smallestRepunitDivByK(int K) {
    if (K % 10 != 1 && K % 10 != 3 && K % 10 != 7 && K % 10 != 9)
      return -1;

    unordered_set<int> seen;
    int N = 0;

    for (int length = 1; length <= K; ++length) {
      N = (N * 10 + 1) % K;
      if (N == 0)
        return length;
      if (seen.count(N))
        return -1;
      seen.insert(N);
    }

    return -1;
  }
};

```
#Leetcode
#challende
Here is the link for the problem:
https://leetcode.com/problems/smallest-integer-divisible-by-k/
SonarQube + Docker + .NET Core Code Analysis
Tags: sonarqube, docker, dotnet, codeanalysis
Published: 2022-07-13 10:13:49

Writing quality code plays a vital role in the software development life cycle. There are few tools to help us to write cleaner code. [SonarQube](https://www.sonarqube.org/) is one of the tools which has a free community version.
[SonarQube](https://www.sonarqube.org/) performs various analyzes, bugs, code smells, test coverage, vulnerabilities, duplicate blocks.

#### Install SonarQube on Docker
Let's now install the [SonarQube](https://www.sonarqube.org/) on docker desktop. You should have [Docker Desktop](https://www.docker.com/products/docker-desktop/) installed & logged in. Run this command on command prompt.
```
docker pull sonarqube
```
Now we have to do the port mapping
```
docker run --name Sonarqube --publish 192.168.4.176:9000:9000 sonarqube
```
Replace the followings with your values
**Sonarqube** - Name of the containter (Sonarqube)
**192.168.4.176** - IP Address of the PC
**9000** - Port that we are going to map

once the installation completes, Open your browser & go to <u>http://localhost:9000</u>, it will prompts you to change the "admin" password. After that you will be directed to [SonarQube](https://www.sonarqube.org/) home page.

#### Install SonarScanner for .NET Core Global Tool
```
dotnet tool install --global dotnet-sonarscanner
```

#### Create a project in SonarQube
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0e46n5amsxlz7o1t7yfs.png) click on the "Manually" option & on the next screen provide name & key for the project. 
![Create project](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y6respz0npk59hmm7b9t.png)In this article we will go with a local repository. 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x0ugnintkvcikjsbx07f.png)Provide a name for the token & press "Generate" button. Once token is generated press on "Continue" button to run analysis on your project.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jwsr646bi1sznylefv0k.png)

#### Run analysis on your project
Select ".NET" as the build type & ".NET Core" as the build tool.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4974e8r2ouivpzmt8r0f.png)Go to the root folder of your .NET Core project solution & open a command prompt from it. Now we can run the commands provided in the page one by one in the command prompt.
```
dotnet sonarscanner begin /k:"DemoProject" /d:sonar.host.url="http://localhost:9000"  /d:sonar.login="sqp_4f474d2d735dec2daa03b382cfde19ddc59cb18c"
```
```
dotnet build
```
```
dotnet sonarscanner end /d:sonar.login="sqp_4f474d2d735dec2daa03b382cfde19ddc59cb18c"
```
make sure to save these commands to re-run the code analysis.
Once the last commands completes the page will be automatically refreshed with the report.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rzbygdgs5qugfjsfo6rj.png)

Happy Coding 😀
1015. Leetcode Solution in Java
Tags: java
Published: 2022-07-13 10:13:37

```
class Solution {
  public int smallestRepunitDivByK(int K) {
    if (K % 10 != 1 && K % 10 != 3 && K % 10 != 7 && K % 10 != 9)
      return -1;

    Set<Integer> seen = new HashSet<>();
    int N = 0;

    for (int length = 1; length <= K; ++length) {
      N = (N * 10 + 1) % K;
      if (N == 0)
        return length;
      if (seen.contains(N))
        return -1;
      seen.add(N);
    }

    return -1;
  }
}

```
#Leetcode
#challende
Here is the link for the problem:
https://leetcode.com/problems/smallest-integer-divisible-by-k/
1009. Leetcode Solution in Java
Tags: java
Published: 2022-07-13 10:12:44

```
class Solution {
  public int bitwiseComplement(int N) {
    int mask = 1;

    while (mask < N)
      mask = (mask << 1) + 1;

    return mask ^ N;
  }
}

```
#Leetcode
#challende
Here is the link for the problem:
https://leetcode.com/problems/complement-of-base-10-integer/
1009. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-13 10:12:18

```
class Solution {
 public:
  int bitwiseComplement(int N) {
    int mask = 1;

    while (mask < N)
      mask = (mask << 1) + 1;

    return mask ^ N;
  }
};

```
#Leetcode
#challende
Here is the link for the problem:
https://leetcode.com/problems/complement-of-base-10-integer/
1195. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-13 10:11:11

```
class FizzBuzz {
private:
    int n;
    int cur;
    mutex mtx;

public:
    FizzBuzz(int n) {
        this->n = n;
        this->cur = 1;
    }

    // printFizz() outputs "fizz".
    void fizz(function<void()> printFizz) {
        while(this->cur <= this->n){
            if(this->cur % 15 != 0 && this->cur % 3 == 0){
                mtx.lock();
                printFizz();
                this->cur++;
                mtx.unlock();
            }
        }
    }

    // printBuzz() outputs "buzz".
    void buzz(function<void()> printBuzz) {
        while(this->cur <= this->n){
            if(this->cur % 15 != 0 && this->cur % 5 == 0){
                mtx.lock();
                printBuzz();
                this->cur++;
                mtx.unlock();
            }
        }
    }

    // printFizzBuzz() outputs "fizzbuzz".
	void fizzbuzz(function<void()> printFizzBuzz) {
        while(this->cur <= this->n){
            if(this->cur % 15 == 0){
                mtx.lock();
                printFizzBuzz();
                this->cur++;
                mtx.unlock();
            }
        }
    }

    // printNumber(x) outputs "x", where x is an integer.
    void number(function<void(int)> printNumber) {
        while(this->cur <= this->n){
            if(this->cur % 3 != 0 && this->cur % 5 != 0){
                mtx.lock();
                printNumber(this->cur);
                this->cur++;
                mtx.unlock();
            }
        }
    }
};
```


#Leetcode
#challende
Here is the link for the problem:
https://leetcode.com/problems/fizz-buzz-multithreaded/
1260. Leetcode Solution in java
Tags: java
Published: 2022-07-13 10:09:22

```
class Solution {
  public List<List<Integer>> shiftGrid(int[][] grid, int k) {
    final int m = grid.length;
    final int n = grid[0].length;
    List<List<Integer>> ans = new ArrayList<>();
    int[][] arr = new int[m][n];

    k %= m * n;

    for (int i = 0; i < m; ++i)
      for (int j = 0; j < n; ++j) {
        int index = (i * n + j + k) % (m * n);
        int x = index / n;
        int y = index % n;
        arr[x][y] = grid[i][j];
      }

    for (int[] row : arr)
      ans.add(Arrays.stream(row).boxed().collect(Collectors.toList()));

    return ans;
  }
}

```

#Leetcode
#challende
Here is the link for the problem:
https://leetcode.com/problems/shift-2d-grid/
1260. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-13 10:08:44

```
class Solution {
 public:
  vector<vector<int>> shiftGrid(vector<vector<int>>& grid, int k) {
    const int m = grid.size();
    const int n = grid[0].size();
    vector<vector<int>> ans(m, vector<int>(n));

    k %= m * n;

    for (int i = 0; i < m; ++i)
      for (int j = 0; j < n; ++j) {
        int index = (i * n + j + k) % (m * n);
        int x = index / n;
        int y = index % n;
        ans[x][y] = grid[i][j];
      }

    return ans;
  }
};

```
#Leetcode
#challende
Here is the link for the problem:
https://leetcode.com/problems/shift-2d-grid/