- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 100 lines of Python from the credited upstream file create-sorted-array-through-instructions.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 4class BIT(object): 5 def __init__(self, n):6 self.__bit = [0]*(n+1) 7 8 def add(self, i, val):9 i += 1 10 while i < len(self.__bit):11 self.__bit[i] += val12 i += (i & -i)13 14 def query(self, i):15 i += 1 16 ret = 017 while i > 0:18 ret += self.__bit[i]19 i -= (i & -i)20 return ret21 22class Solution(object):23 def createSortedArray(self, instructions):24 """25 :type instructions: List[int]26 :rtype: int27 """28 MOD = 10**9 + 729 bit = BIT(max(instructions))30 result = 031 for i, inst in enumerate(instructions):32 inst -= 133 result += min(bit.query(inst-1), i-bit.query(inst))34 bit.add(inst, 1)35 return result % MOD36 37 383940import itertools41class Solution_TLE(object):42 def createSortedArray(self, instructions):43 """44 :type instructions: List[int]45 :rtype: int46 """47 MOD = 10**9 + 748 def smallerMergeSort(idxs, start, end, counts):49 if end - start <= 0: 50 return 051 52 mid = start + (end - start) 253 smallerMergeSort(idxs, start, mid, counts)54 smallerMergeSort(idxs, mid + 1, end, counts)55 r = start56 tmp = []57 for i in xrange(mid+1, end + 1):58 59 while r <= mid and idxs[r][0] < idxs[i][0]:60 tmp.append(idxs[r])61 r += 162 tmp.append(idxs[i])63 counts[idxs[i][1]] += r - start64 while r <= mid:65 tmp.append(idxs[r])66 r += 167 68 idxs[start:start+len(tmp)] = tmp69 70 def largerMergeSort(idxs, start, end, counts):71 if end - start <= 0: 72 return 073 74 mid = start + (end - start) 275 largerMergeSort(idxs, start, mid, counts)76 largerMergeSort(idxs, mid + 1, end, counts)77 r = start78 tmp = []79 for i in xrange(mid+1, end + 1):80 81 while r <= mid and idxs[r][0] <= idxs[i][0]:82 tmp.append(idxs[r])83 r += 184 if r <= mid:85 tmp.append(idxs[i])86 counts[idxs[i][1]] += mid - r + 187 while r <= mid:88 tmp.append(idxs[r])89 r += 190 91 idxs[start:start+len(tmp)] = tmp92 93 idxs = []94 smaller_counts, larger_counts = [[0] * len(instructions) for _ in xrange(2)]95 for i, inst in enumerate(instructions):96 idxs.append((inst, i))97 smallerMergeSort(idxs[:], 0, len(idxs)-1, smaller_counts)98 largerMergeSort(idxs, 0, len(idxs)-1, larger_counts)99 return sum(min(s, l) for s, l in itertools.izip(smaller_counts, larger_counts)) % MOD100