Hi Guys, Today is 3 January 2024 and below is the solution for problem of the day
So, the question we have is Number of Laser Beams in a Bank.
In this we have to find total number of lasers. So just imagine it as we have to find number of lines connecting the dots. so if there are 2 dots. we will have one line, if we have 3 dots we will get 3 lines, and so on...
Now relate the above provided example, let's relate this to our problem statement.
We have 4 walls, first wall has 3 lasers, second wall has 0 lasers, third wall got 2 lasers and last wall has 1 laser. So as i suggested we need to connect dots so make sure to only join adjacent dots. So lasers from 1 and 3 wall will connect to each other (6 lasers) and wall 3 and 4 will connect to each other (2 lasers). So total of 8 lasers, which is the required output anyways.
Code Explanation:
Explanation:
The code defines a class named
Solution
.Inside the class, there's a method named
numberOfBeams
that takes a list of strings (bank
) as its input and returns an integer.The method initializes two variables,
val
andtemp
, to keep track of the total number of beams and the count of lasers in the previous row, respectively.It then iterates through each row (
lasers
) in thebank
.For each row, it counts the number of lasers (
count
) by iterating through each character in the row. If a character is "1", the count is incremented.If there are any lasers in the current row (i.e.,
count
is non-zero), it adds the product oftemp
andcount
to the totalval
. This is done to calculate the number of beams formed by connecting lasers in consecutive rows.The
temp
variable is updated with the count of lasers in the current row for the next iteration.Finally, the method returns the total number of beams (
val
).
In summary, the code calculates the total number of beams formed by connecting lasers in consecutive rows, where each row is represented by a string of "0" and "1" characters. The number of beams is determined by multiplying the count of lasers in the current row with the count of lasers in the previous row.
Performance -
1. Time Complexity - O(N*M), N=number of row (length of bank array) and M = number of cells in each row (length of each value in bank array)
2. Space complexity - O(1)
Hi, thanks for reading my post, I hope you enjoyed it. So, if you want me to keep you updated with the tech references in coming future please do share your valuable comments with me and also do not forget to share it with your friends....:)
Comments
Post a Comment