Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

832. Flipping an Image

Explanation

To solve this problem, we need to first reverse each row of the input image matrix. Then, we invert the values in the matrix by flipping 0s to 1s and 1s to 0s. This process can be achieved by iterating through each row, reversing it, and then flipping the values.

Algorithm:

  1. Iterate through each row of the image matrix.
  2. Reverse each row.
  3. Invert the values in each row.

Time Complexity:

The time complexity of this algorithm is O(n^2), where n is the size of the input image matrix.

Space Complexity:

The space complexity is O(1) as we are modifying the input matrix in place.

class Solution {
    public int[][] flipAndInvertImage(int[][] image) {
        int n = image.length;
        
        for (int i = 0; i < n; i++) {
            int left = 0;
            int right = n - 1;
            while (left <= right) {
                int temp = image[i][left] ^ 1;
                image[i][left] = image[i][right] ^ 1;
                image[i][right] = temp;
                left++;
                right--;
            }
        }
        
        return image;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.