DEV Community

Cover image for Flipping an Image(leetcode)
Tahzib Mahmud Rifat
Tahzib Mahmud Rifat

Posted on

Flipping an Image(leetcode)

INTRODUCTION

Image description

Our problem says, we are given an 2D array. At first we have to reverse each row of the array, then we have to invert(if 0 then set 1, if the value is 1 then set 0) all the elements of the array.

Examples

Image description

Steps

  1. Take a for loop.
  2. reverse each row using while loop.
  3. After reversing now traverse the row again and invert the value.
  4. In the end return the array.

JavaCode

class Solution {
    public int[][] flipAndInvertImage(int[][] image) {
        for(int i = 0; i<image.length; i++){
            int temp = 0, j = 0, k= image[i].length-1;
            while(j < k){
                temp = image[i][j];
                image[i][j] = image[i][k];
                image[i][k] = temp;
                j++;
                k--;
            }

            for(int l = 0; l<image[i].length; l++){
                if(image[i][l] == 1){
                    image[i][l] = 0;
                }else{
                    image[i][l] = 1;
                }
            }
        }
        return image;
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Image description

Top comments (0)

Great read:

Is it Time to go Back to the Monolith?

History repeats itself. Everything old is new again and I’ve been around long enough to see ideas discarded, rediscovered and return triumphantly to overtake the fad. In recent years SQL has made a tremendous comeback from the dead. We love relational databases all over again. I think the Monolith will have its space odyssey moment again. Microservices and serverless are trends pushed by the cloud vendors, designed to sell us more cloud computing resources.

Microservices make very little sense financially for most use cases. Yes, they can ramp down. But when they scale up, they pay the costs in dividends. The increased observability costs alone line the pockets of the “big cloud” vendors.

AWS Security LIVE!

Hosted by security experts, AWS Security LIVE! showcases AWS Partners tackling real-world security challenges. Join live and get your security questions answered.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️