Skip to content

Instantly share code, notes, and snippets.

@primaryobjects
Last active December 28, 2023 16:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save primaryobjects/e662022bbed4702d44c2cdc718f6c0e1 to your computer and use it in GitHub Desktop.
Save primaryobjects/e662022bbed4702d44c2cdc718f6c0e1 to your computer and use it in GitHub Desktop.
Insertion sort in Python with list history. https://neetcode.io/problems/insertionSort
from typing import List
from collections import namedtuple
Pair = namedtuple('Pair', ['key', 'value'])
# Definition for a pair.
# class Pair:
# def __init__(self, key: int, value: str):
# self.key = key
# self.value = value
class Solution:
def insertionSort(self, pairs: List[Pair]) -> List[List[Pair]]:
history = [pairs.copy()] if pairs else []
sorted_pairs = pairs
for i in range(0, len(sorted_pairs) - 1):
a = sorted_pairs[i].key
b = sorted_pairs[i+1].key
j = i
while b < a and j > -1:
# Swap positions.
temp = sorted_pairs[j+1]
sorted_pairs[j+1] = sorted_pairs[j]
sorted_pairs[j] = temp
a = sorted_pairs[j - 1].key
b = sorted_pairs[j].key
j = j - 1
history.append(sorted_pairs.copy())
return history
client = Solution()
result = client.insertionSort([Pair(3, "cat"), Pair(3, "bird"), Pair(2, "dog")])
print(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment