Check image in an 0 or 1 matrix
Anonymous User
484

Hey, I was asked this one question in today's interview, and it toally threw me off my game. Porbably because I haven't solved anything similar before. I wasn't able to find it on Leetcode or any other platform. Just curious, if anyone has solved this before?

solution:

With the help of the interviewer, I was able to solve it by using the idea of calculating the height and width of the image, and then checking if it's a close match to sqaure (i.e. Apple) or rectangle (banana)

Would you rate it 'Easy', 'medium' or 'Hard'?

**

Question

We'll be writing a function that takes in a NxN picture (black and white) in the form of a 2-dimensional array. The array will contain either 0 = white, or 1 = black. The picture will either be a banana or an apple. Write a function banana_or_apple(input) that returns either 'banana' or 'apple'

The input can be like this

 apple = [
   [0,0,0,0,0,0,0,0,0,0,0],
   [0,0,0,0,1,0,0,0,0,0,0],
   [0,0,0,0,0,1,0,0,0,0,0],
   [0,0,0,1,1,1,1,1,0,0,0],
   [0,0,0,1,1,1,1,1,0,0,0],
   [0,0,0,1,1,1,1,1,0,0,0],
   [0,0,0,1,1,1,1,1,0,0,0],
   [0,0,0,0,1,1,1,0,0,0,0],
   [0,0,0,0,0,0,0,0,0,0,0],
   [0,0,0,0,0,0,0,0,0,0,0],
   [0,0,0,0,0,0,0,0,0,0,0]
 ];


 banana2 = [
   [0,0,0,0,0,1,0,0,0,0,0],
   [0,0,0,0,0,1,0,0,0,0,0],
   [0,0,0,0,0,1,1,0,0,0,0],
   [0,0,0,0,0,1,1,1,0,0,0],
   [0,0,0,0,0,1,1,1,0,0,0],
   [0,0,0,0,0,1,1,1,0,0,0],
   [0,0,0,0,0,1,1,0,0,0,0],
   [0,0,0,0,0,1,1,0,0,0,0],
   [0,0,0,0,0,1,0,0,0,0,0],
   [0,0,0,0,0,0,0,0,0,0,0],
   [0,0,0,0,0,0,0,0,0,0,0]
 ];

 banana = [
   [0,0,0,1,1,1,0,0,0,0,0],
   [0,0,0,0,1,1,0,0,0,0,0],
   [0,0,0,0,0,1,1,0,0,0,0],
   [0,0,0,0,0,1,1,1,0,0,0],
   [0,0,0,0,0,1,1,1,0,0,0],
   [0,0,0,0,0,1,1,1,0,0,0],
   [0,0,0,0,0,1,1,1,0,0,0],
   [0,0,0,0,1,1,1,0,0,0,0],
   [0,0,0,1,1,1,0,0,0,0,0],
   [0,0,0,1,1,0,0,0,0,0,0],
   [0,0,1,0,0,0,0,0,0,0,0]
 ];
 
 rotated_apple = [
    [0,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,1,1,1,1,0,0,0],
    [0,0,0,1,1,1,1,1,0,1,0],
    [0,0,0,1,1,1,1,1,1,0,0],
    [0,0,0,1,1,1,1,1,0,0,0],
    [0,0,0,0,1,1,1,1,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,0]
]

**

Comments (1)