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

Reinvent your career. Join DEV.

It takes one minute and is worth it for your career.

Get started

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.

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay