How did your solutions become more elegant over time?

What did you do to help make your solutions more elegant over time?

I'm reviewing mediums and my solutions are noticeably easier to read and more intuitive than they used to be because I can come up with my own stuff now. I never thought my old code would be so ugly! For example, on

https://leetcode.com/problems/insert-interval/

my approach (after doing hundreds of questions) looks like

	def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
        bisect.insort(intervals, 
                      newInterval, 
                      key=lambda x: x[0])
        ans = [intervals[0]]
        
        # https://leetcode.com/problems/merge-intervals/
        for start, end in intervals:
            prev = ans[-1]
            
            if prev[1] >= start:
                prev[1] = max(prev[1], end)
            else:
                ans.append([start, end])
                
        return ans

whereas my old code from when I first started overcomplicates things to an embarrassing degree with lots of edge cases that just aren't in the spirit of the problem...

	def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
        result = []
        
        def appendLefts(value):
            idx = 0
            while idx < len(intervals):
                if intervals[idx][0] >= value:
                    return idx
                
                result.append(intervals[idx])
                
                idx += 1
                
            return idx
        
        def appendRights(idx):
            while idx < len(intervals):
                if result[-1][1] >= intervals[idx][1]:
                    idx += 1
                    continue
                
                if result[-1][1] < intervals[idx][0]:
                    result.append(intervals[idx])
                else:
                    result[-1][1] = intervals[idx][1]
                
                idx += 1
                
        if not intervals:
            return [newInterval]
        
        idx = appendLefts(newInterval[0])
        
        if not result or result[-1][1] < newInterval[0]:
            result.append(newInterval)
        else:
            result[-1][1] = max(result[-1][1], newInterval[1])
        
        appendRights(idx)
        
        return result
Comments (0)