Given a string of a million numbers, return all repeating 3 digit numbers

前端 未结 13 1516
误落风尘
误落风尘 2020-12-22 15:41

I had an interview with a hedge fund company in New York a few months ago and unfortunately, I did not get the internship offer as a data/software engineer. (They also asked

13条回答
  •  暖寄归人
    2020-12-22 16:04

    I would solve the problem as follows:

    def find_numbers(str_num):
        final_dict = {}
        buffer = {}
        for idx in range(len(str_num) - 3):
            num = int(str_num[idx:idx + 3])
            if num not in buffer:
                buffer[num] = 0
            buffer[num] += 1
            if buffer[num] > 1:
                final_dict[num] = buffer[num]
        return final_dict
    

    Applied to your example string, this yields:

    >>> find_numbers("123412345123456")
    {345: 2, 234: 3, 123: 3}
    

    This solution runs in O(n) for n being the length of the provided string, and is, I guess, the best you can get.

提交回复
热议问题