Skip to content

Instantly share code, notes, and snippets.

@eric100lin
Last active August 29, 2022 09:05
Show Gist options
  • Save eric100lin/85bba0a50a859a0f07888a8d2bbda464 to your computer and use it in GitHub Desktop.
Save eric100lin/85bba0a50a859a0f07888a8d2bbda464 to your computer and use it in GitHub Desktop.
'''
Witness of The Tall People
Hi, here's your problem today. This problem was recently asked by Google:
There are n people lined up, and each have a height represented as an integer. A murder has happened right in front of them, and only people who are taller than everyone in front of them are able to see what has happened. How many witnesses are there?
Example:
Input: [3, 6, 3, 4, 1]
Output: 3
Explanation: Only [6, 4, 1] were able to see in front of them.
#
#
# #
####
####
#####
36341 x (murder scene)
'''
def witnesses(heights):
max_height = float('-inf')
witnesses = 0
for idx in range(len(heights)-1, -1, -1):
if heights[idx] > max_height:
witnesses += 1
max_height = heights[idx]
return witnesses
print(witnesses([3, 6, 3, 4, 1]))
# 3
print(witnesses([3, 4, 4, 4, 1]))
# 2
print(witnesses([-1, -3, -7, -2]))
# 2
@fermanjj
Copy link

This is good, but what if all the elements in the list are negative? Or what if there are two elements with the same height? Additionally, reversing the list costs O(n) time. You could just traverse the list backwards and save an extra iteration through the list.
Check out this solution:

def witnesses(heights):
    max_height = float('-inf')
    total = 0
    for i in range(len(heights) - 1, -1, -1):
        if heights[i] > max_height:
            total += 1
        max_height = max(heights[i], max_height)
    return total


print(witnesses([3, 6, 3, 4, 1]))
# 3
print(witnesses([3, 4, 4, 4, 1]))
# 2
print(witnesses([-1, -3, -7, -2]))
# 2

@eric100lin
Copy link
Author

Thank you for your advice!!
You really point out the defects of my code.
I accepted your change and updated my code.

@fermanjj
Copy link

Awesome! Glad I could help!

@kampaitees
Copy link

you should have common sense that height can never be negative

@eric100lin
Copy link
Author

humm, right for height but still a valid test case if the story change a bit

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment