Hacker News new | ask | show | jobs
by stephen_cagle 83 days ago
> Find Minimum in Rotated Sorted Array

I've seen that problem in an interview before, and I thought the solution I hit upon was pretty fun (if dumb).

  class Solution:
      def findMin(self, nums: List[int]) -> int:
          class RotatedList():
              def __init__(self, rotation):
                  self.rotation = rotation
              def __getitem__(self, index):
                  return nums[(index + self.rotation) % len(nums)]
  
          class RotatedListIsSorted():
              def __getitem__(self, index) -> bool:
                  rotated = RotatedList(index)
                  print(index, [rotated[i] for i in range(len(nums))])
                  return rotated[0] < rotated[len(nums) // 2]
              def __len__(self):
                  return len(nums)
  
          rotation = bisect_left(RotatedListIsSorted(), True)
          print('rotation =>', rotation)
          return RotatedList(rotation)[0]

I think it is really interesting that you can define "list like" things in python using just two methods. This is kind of neat because sometimes you can redefine an entire problem as actually just the questions of finding the binary search of a list of solutions to that problem; here you are looking for the leftmost point that it becomes True. Anyway, I often bomb interviews by trying out something goofy like this, but I don't know, when it works, it is glorious!

Good luck on your second round!

1 comments

I only did these types of interviews when applying for internships in uni, but I really don't think you would get away with using an inbuilt binary search (via bisect left) in a question that is basically "binary search with a quirk".
It's certainly not an "elitist initiation ordeal" to ask a potential crewmate to sketch a library function they've selected, what abstraction or ideas it implicitly contains, and what bearing those have on their overall approach. GP's use of `bisect_left` is instructive here:

  In [2]: Solution().findMin([1, 0, 1, 1])
  Out[2]: 4
However, requesting a bug-free implementation of `bsearch()` (to say nothing of the actual problem being solved) during a timed, in-person interview is less a structured rehearsal of an individual's unique capacities, and more of a jumping-in ritual proving only a willingness to die for their cybergang.