Short but bad Python

  • 1
    def __init__(self):
        vals = set()
        self.addNum = vals.add
        self.getIntervals = lambda: [[g[0][1], g[-1][1]] for g in
                                     (list(g) for _, g in itertools.groupby(
                                      enumerate(sorted(vals)), lambda (i, val): val - i))]

  • 0

    OMG, why does it work? The getIntervals function even doesnt return a list of Intervals-type obj

  • 0

    @weiheng4 Yeah here I exploit how LeetCode does the checking. Normally I don't. Did I mention that this solution is bad? :-D

  • 0

    @StefanPochmann , it takes me a while to understand your code. You really are a code golfer!
    From my understanding, your solution has O(1) addNum and O(n) getIntervals. The "bad" you mentioned about is when compared with BST O(logN) solution?

  • 0

    @ra1den I think I called it "bad" because of that complexity, because of the unusual and perhaps bad style of setting the methods in the constructor, and because of the wrong output format (I return Python lists instead of Interval objects).

  • 0

    Hi @StefanPochmann

    How do you know how LeetCode does the checking?

  • 1

    @ra1den He calls sorted on vals, that makes getIntervals O(nlg(n)), doesn't it?

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.