[{"data":1,"prerenderedAt":19261},["ShallowReactive",2],{"learn-articles":3},[4,875,2084,2470,3120,3997,4448,5760,6057,6568,7084,8176,9186,9646,10106,11068,12653,13309,13731,14005,14392,15475,15895,16812,17293,18034,18494],{"id":5,"title":6,"body":7,"category":861,"complexity":862,"date":862,"description":863,"difficulty":864,"extension":865,"meta":866,"navigation":221,"order":85,"path":869,"publishedAt":870,"relatedAlgorithmId":871,"seo":872,"stem":873,"__hash__":874},"learn\u002Flearn\u002Fastar.md","A* Search Algorithm",{"type":8,"value":9,"toc":853},"minimark",[10,14,23,28,31,42,64,67,71,74,689,693,700,703,723,726,730,808,812,815,828,831,835,849],[11,12,6],"h1",{"id":13},"a-search-algorithm",[15,16,17,18,22],"p",{},"A* (pronounced \"A-star\") improves on Dijkstra by using a ",[19,20,21],"strong",{},"heuristic"," — an estimate of the remaining cost to the goal. This guides the search toward the goal, exploring fewer nodes while still guaranteeing the cheapest path.",[24,25,27],"h2",{"id":26},"the-formula","The Formula",[15,29,30],{},"A* evaluates each node using:",[32,33,38],"pre",{"className":34,"code":36,"language":37},[35],"language-text","f(node) = g(node) + h(node)\n","text",[39,40,36],"code",{"__ignoreMap":41},"",[43,44,45,52,58],"ul",{},[46,47,48,51],"li",{},[19,49,50],{},"g(node)"," = actual cost from start to this node (same as Dijkstra tracks)",[46,53,54,57],{},[19,55,56],{},"h(node)"," = estimated cost from this node to the goal (the heuristic)",[46,59,60,63],{},[19,61,62],{},"f(node)"," = total estimated cost of the best path through this node",[15,65,66],{},"The priority queue orders by f(node) instead of just g(node).",[24,68,70],{"id":69},"code-snippet","Code Snippet",[15,72,73],{},"Uses the WeightedGraph class from the Graphs and Weighted Graphs article:",[32,75,79],{"className":76,"code":77,"language":78,"meta":41,"style":41},"language-python shiki shiki-themes github-dark","def astar_search(graph, start_node: int, goal_node: int, heuristic) -> tuple[list[int], int]:\n    \"\"\"Find cheapest path using actual cost + heuristic estimate.\n    heuristic(node, goal) must never overestimate true cost.\"\"\"\n    num_nodes = graph.num_nodes\n    cost_to_reach = [float('inf')] * num_nodes\n    parent_of = [-1] * num_nodes\n    visited = [False] * num_nodes\n\n    cost_to_reach[start_node] = 0\n    estimated_total = heuristic(start_node, goal_node)\n    frontier = [(estimated_total, start_node)]  # (f_score, node)\n\n    while frontier:\n        frontier.sort()\n        current_f_score, current_node = frontier.pop(0)\n\n        if visited[current_node]:\n            continue\n        visited[current_node] = True\n\n        if current_node == goal_node:\n            break\n\n        for neighbor_node, edge_weight in graph.get_neighbors(current_node):\n            if visited[neighbor_node]:\n                continue\n\n            new_cost = cost_to_reach[current_node] + edge_weight\n\n            if new_cost \u003C cost_to_reach[neighbor_node]:\n                cost_to_reach[neighbor_node] = new_cost\n                parent_of[neighbor_node] = current_node\n                f_score = new_cost + heuristic(neighbor_node, goal_node)\n                frontier.append((f_score, neighbor_node))\n\n    # Reconstruct path\n    path = []\n    node = goal_node\n    while node != -1:\n        path.append(node)\n        node = parent_of[node]\n    path.reverse()\n\n    total_cost = cost_to_reach[goal_node]\n    return path, total_cost\n\n\ndef manhattan_distance(node_a: int, node_b: int, grid_columns: int) -> int:\n    \"\"\"Admissible heuristic for grid-based movement (no diagonal moves).\"\"\"\n    row_a, col_a = node_a \u002F\u002F grid_columns, node_a % grid_columns\n    row_b, col_b = node_b \u002F\u002F grid_columns, node_b % grid_columns\n    return abs(row_a - row_b) + abs(col_a - col_b)\n","python",[39,80,81,120,127,133,145,174,197,216,223,234,245,260,265,274,280,297,302,311,317,328,333,347,353,358,373,382,388,393,410,415,429,440,451,466,472,477,483,494,505,524,530,541,547,552,563,572,577,582,612,618,641,661],{"__ignoreMap":41},[82,83,86,90,94,98,102,105,107,110,112,115,117],"span",{"class":84,"line":85},"line",1,[82,87,89],{"class":88},"snl16","def",[82,91,93],{"class":92},"svObZ"," astar_search",[82,95,97],{"class":96},"s95oV","(graph, start_node: ",[82,99,101],{"class":100},"sDLfK","int",[82,103,104],{"class":96},", goal_node: ",[82,106,101],{"class":100},[82,108,109],{"class":96},", heuristic) -> tuple[list[",[82,111,101],{"class":100},[82,113,114],{"class":96},"], ",[82,116,101],{"class":100},[82,118,119],{"class":96},"]:\n",[82,121,123],{"class":84,"line":122},2,[82,124,126],{"class":125},"sU2Wk","    \"\"\"Find cheapest path using actual cost + heuristic estimate.\n",[82,128,130],{"class":84,"line":129},3,[82,131,132],{"class":125},"    heuristic(node, goal) must never overestimate true cost.\"\"\"\n",[82,134,136,139,142],{"class":84,"line":135},4,[82,137,138],{"class":96},"    num_nodes ",[82,140,141],{"class":88},"=",[82,143,144],{"class":96}," graph.num_nodes\n",[82,146,148,151,153,156,159,162,165,168,171],{"class":84,"line":147},5,[82,149,150],{"class":96},"    cost_to_reach ",[82,152,141],{"class":88},[82,154,155],{"class":96}," [",[82,157,158],{"class":100},"float",[82,160,161],{"class":96},"(",[82,163,164],{"class":125},"'inf'",[82,166,167],{"class":96},")] ",[82,169,170],{"class":88},"*",[82,172,173],{"class":96}," num_nodes\n",[82,175,177,180,182,184,187,190,193,195],{"class":84,"line":176},6,[82,178,179],{"class":96},"    parent_of ",[82,181,141],{"class":88},[82,183,155],{"class":96},[82,185,186],{"class":88},"-",[82,188,189],{"class":100},"1",[82,191,192],{"class":96},"] ",[82,194,170],{"class":88},[82,196,173],{"class":96},[82,198,200,203,205,207,210,212,214],{"class":84,"line":199},7,[82,201,202],{"class":96},"    visited ",[82,204,141],{"class":88},[82,206,155],{"class":96},[82,208,209],{"class":100},"False",[82,211,192],{"class":96},[82,213,170],{"class":88},[82,215,173],{"class":96},[82,217,219],{"class":84,"line":218},8,[82,220,222],{"emptyLinePlaceholder":221},true,"\n",[82,224,226,229,231],{"class":84,"line":225},9,[82,227,228],{"class":96},"    cost_to_reach[start_node] ",[82,230,141],{"class":88},[82,232,233],{"class":100}," 0\n",[82,235,237,240,242],{"class":84,"line":236},10,[82,238,239],{"class":96},"    estimated_total ",[82,241,141],{"class":88},[82,243,244],{"class":96}," heuristic(start_node, goal_node)\n",[82,246,248,251,253,256],{"class":84,"line":247},11,[82,249,250],{"class":96},"    frontier ",[82,252,141],{"class":88},[82,254,255],{"class":96}," [(estimated_total, start_node)]  ",[82,257,259],{"class":258},"sAwPA","# (f_score, node)\n",[82,261,263],{"class":84,"line":262},12,[82,264,222],{"emptyLinePlaceholder":221},[82,266,268,271],{"class":84,"line":267},13,[82,269,270],{"class":88},"    while",[82,272,273],{"class":96}," frontier:\n",[82,275,277],{"class":84,"line":276},14,[82,278,279],{"class":96},"        frontier.sort()\n",[82,281,283,286,288,291,294],{"class":84,"line":282},15,[82,284,285],{"class":96},"        current_f_score, current_node ",[82,287,141],{"class":88},[82,289,290],{"class":96}," frontier.pop(",[82,292,293],{"class":100},"0",[82,295,296],{"class":96},")\n",[82,298,300],{"class":84,"line":299},16,[82,301,222],{"emptyLinePlaceholder":221},[82,303,305,308],{"class":84,"line":304},17,[82,306,307],{"class":88},"        if",[82,309,310],{"class":96}," visited[current_node]:\n",[82,312,314],{"class":84,"line":313},18,[82,315,316],{"class":88},"            continue\n",[82,318,320,323,325],{"class":84,"line":319},19,[82,321,322],{"class":96},"        visited[current_node] ",[82,324,141],{"class":88},[82,326,327],{"class":100}," True\n",[82,329,331],{"class":84,"line":330},20,[82,332,222],{"emptyLinePlaceholder":221},[82,334,336,338,341,344],{"class":84,"line":335},21,[82,337,307],{"class":88},[82,339,340],{"class":96}," current_node ",[82,342,343],{"class":88},"==",[82,345,346],{"class":96}," goal_node:\n",[82,348,350],{"class":84,"line":349},22,[82,351,352],{"class":88},"            break\n",[82,354,356],{"class":84,"line":355},23,[82,357,222],{"emptyLinePlaceholder":221},[82,359,361,364,367,370],{"class":84,"line":360},24,[82,362,363],{"class":88},"        for",[82,365,366],{"class":96}," neighbor_node, edge_weight ",[82,368,369],{"class":88},"in",[82,371,372],{"class":96}," graph.get_neighbors(current_node):\n",[82,374,376,379],{"class":84,"line":375},25,[82,377,378],{"class":88},"            if",[82,380,381],{"class":96}," visited[neighbor_node]:\n",[82,383,385],{"class":84,"line":384},26,[82,386,387],{"class":88},"                continue\n",[82,389,391],{"class":84,"line":390},27,[82,392,222],{"emptyLinePlaceholder":221},[82,394,396,399,401,404,407],{"class":84,"line":395},28,[82,397,398],{"class":96},"            new_cost ",[82,400,141],{"class":88},[82,402,403],{"class":96}," cost_to_reach[current_node] ",[82,405,406],{"class":88},"+",[82,408,409],{"class":96}," edge_weight\n",[82,411,413],{"class":84,"line":412},29,[82,414,222],{"emptyLinePlaceholder":221},[82,416,418,420,423,426],{"class":84,"line":417},30,[82,419,378],{"class":88},[82,421,422],{"class":96}," new_cost ",[82,424,425],{"class":88},"\u003C",[82,427,428],{"class":96}," cost_to_reach[neighbor_node]:\n",[82,430,432,435,437],{"class":84,"line":431},31,[82,433,434],{"class":96},"                cost_to_reach[neighbor_node] ",[82,436,141],{"class":88},[82,438,439],{"class":96}," new_cost\n",[82,441,443,446,448],{"class":84,"line":442},32,[82,444,445],{"class":96},"                parent_of[neighbor_node] ",[82,447,141],{"class":88},[82,449,450],{"class":96}," current_node\n",[82,452,454,457,459,461,463],{"class":84,"line":453},33,[82,455,456],{"class":96},"                f_score ",[82,458,141],{"class":88},[82,460,422],{"class":96},[82,462,406],{"class":88},[82,464,465],{"class":96}," heuristic(neighbor_node, goal_node)\n",[82,467,469],{"class":84,"line":468},34,[82,470,471],{"class":96},"                frontier.append((f_score, neighbor_node))\n",[82,473,475],{"class":84,"line":474},35,[82,476,222],{"emptyLinePlaceholder":221},[82,478,480],{"class":84,"line":479},36,[82,481,482],{"class":258},"    # Reconstruct path\n",[82,484,486,489,491],{"class":84,"line":485},37,[82,487,488],{"class":96},"    path ",[82,490,141],{"class":88},[82,492,493],{"class":96}," []\n",[82,495,497,500,502],{"class":84,"line":496},38,[82,498,499],{"class":96},"    node ",[82,501,141],{"class":88},[82,503,504],{"class":96}," goal_node\n",[82,506,508,510,513,516,519,521],{"class":84,"line":507},39,[82,509,270],{"class":88},[82,511,512],{"class":96}," node ",[82,514,515],{"class":88},"!=",[82,517,518],{"class":88}," -",[82,520,189],{"class":100},[82,522,523],{"class":96},":\n",[82,525,527],{"class":84,"line":526},40,[82,528,529],{"class":96},"        path.append(node)\n",[82,531,533,536,538],{"class":84,"line":532},41,[82,534,535],{"class":96},"        node ",[82,537,141],{"class":88},[82,539,540],{"class":96}," parent_of[node]\n",[82,542,544],{"class":84,"line":543},42,[82,545,546],{"class":96},"    path.reverse()\n",[82,548,550],{"class":84,"line":549},43,[82,551,222],{"emptyLinePlaceholder":221},[82,553,555,558,560],{"class":84,"line":554},44,[82,556,557],{"class":96},"    total_cost ",[82,559,141],{"class":88},[82,561,562],{"class":96}," cost_to_reach[goal_node]\n",[82,564,566,569],{"class":84,"line":565},45,[82,567,568],{"class":88},"    return",[82,570,571],{"class":96}," path, total_cost\n",[82,573,575],{"class":84,"line":574},46,[82,576,222],{"emptyLinePlaceholder":221},[82,578,580],{"class":84,"line":579},47,[82,581,222],{"emptyLinePlaceholder":221},[82,583,585,587,590,593,595,598,600,603,605,608,610],{"class":84,"line":584},48,[82,586,89],{"class":88},[82,588,589],{"class":92}," manhattan_distance",[82,591,592],{"class":96},"(node_a: ",[82,594,101],{"class":100},[82,596,597],{"class":96},", node_b: ",[82,599,101],{"class":100},[82,601,602],{"class":96},", grid_columns: ",[82,604,101],{"class":100},[82,606,607],{"class":96},") -> ",[82,609,101],{"class":100},[82,611,523],{"class":96},[82,613,615],{"class":84,"line":614},49,[82,616,617],{"class":125},"    \"\"\"Admissible heuristic for grid-based movement (no diagonal moves).\"\"\"\n",[82,619,621,624,626,629,632,635,638],{"class":84,"line":620},50,[82,622,623],{"class":96},"    row_a, col_a ",[82,625,141],{"class":88},[82,627,628],{"class":96}," node_a ",[82,630,631],{"class":88},"\u002F\u002F",[82,633,634],{"class":96}," grid_columns, node_a ",[82,636,637],{"class":88},"%",[82,639,640],{"class":96}," grid_columns\n",[82,642,644,647,649,652,654,657,659],{"class":84,"line":643},51,[82,645,646],{"class":96},"    row_b, col_b ",[82,648,141],{"class":88},[82,650,651],{"class":96}," node_b ",[82,653,631],{"class":88},[82,655,656],{"class":96}," grid_columns, node_b ",[82,658,637],{"class":88},[82,660,640],{"class":96},[82,662,664,666,669,672,674,677,679,681,684,686],{"class":84,"line":663},52,[82,665,568],{"class":88},[82,667,668],{"class":100}," abs",[82,670,671],{"class":96},"(row_a ",[82,673,186],{"class":88},[82,675,676],{"class":96}," row_b) ",[82,678,406],{"class":88},[82,680,668],{"class":100},[82,682,683],{"class":96},"(col_a ",[82,685,186],{"class":88},[82,687,688],{"class":96}," col_b)\n",[24,690,692],{"id":691},"admissibility-the-key-requirement","Admissibility: The Key Requirement",[15,694,695,696,699],{},"A heuristic is ",[19,697,698],{},"admissible"," if it never overestimates the true remaining cost. When admissible, A* guarantees the optimal (cheapest) path.",[15,701,702],{},"Common admissible heuristics for grids:",[43,704,705,711,717],{},[46,706,707,710],{},[19,708,709],{},"Manhattan distance",": for 4-directional movement (no diagonals)",[46,712,713,716],{},[19,714,715],{},"Euclidean distance",": for any-direction movement",[46,718,719,722],{},[19,720,721],{},"Zero",": always admissible, but makes A* behave like Dijkstra (no guidance)",[15,724,725],{},"If the heuristic overestimates, A* may find a suboptimal path but runs faster — this trade-off is sometimes acceptable.",[24,727,729],{"id":728},"a-vs-dijkstra","A* vs Dijkstra",[731,732,733,749],"table",{},[734,735,736],"thead",{},[737,738,739,743,746],"tr",{},[740,741,742],"th",{},"Property",[740,744,745],{},"Dijkstra",[740,747,748],{},"A*",[750,751,752,764,775,786,797],"tbody",{},[737,753,754,758,761],{},[755,756,757],"td",{},"Expansion order",[755,759,760],{},"By g(node) only",[755,762,763],{},"By g(node) + h(node)",[737,765,766,769,772],{},[755,767,768],{},"Nodes explored",[755,770,771],{},"More (explores all directions)",[755,773,774],{},"Fewer (guided toward goal)",[737,776,777,780,783],{},[755,778,779],{},"Optimal path",[755,781,782],{},"Yes",[755,784,785],{},"Yes (if heuristic is admissible)",[737,787,788,791,794],{},[755,789,790],{},"Requires",[755,792,793],{},"Non-negative weights",[755,795,796],{},"Non-negative weights + heuristic",[737,798,799,802,805],{},[755,800,801],{},"Best for",[755,803,804],{},"Unknown goal position",[755,806,807],{},"Known goal position",[24,809,811],{"id":810},"the-visual-difference","The Visual Difference",[15,813,814],{},"On a weighted maze:",[43,816,817,822],{},[46,818,819,821],{},[19,820,745],{}," expands in concentric cost-circles outward from the start",[46,823,824,827],{},[19,825,826],{},"A","* expands preferentially toward the goal, skipping expensive dead ends",[15,829,830],{},"Both find the same cheapest path. A* just explores fewer cells to get there.",[24,832,834],{"id":833},"when-to-use-a","When to Use A*",[43,836,837,840,843,846],{},[46,838,839],{},"Pathfinding in games (grid-based movement, known target position)",[46,841,842],{},"Robot navigation (known map, known destination)",[46,844,845],{},"Any weighted shortest-path problem where you have a good heuristic for remaining cost",[46,847,848],{},"When Dijkstra is too slow because it explores too many irrelevant nodes",[850,851,852],"style",{},"html pre.shiki code .snl16, html code.shiki .snl16{--shiki-default:#F97583}html pre.shiki code .svObZ, html code.shiki .svObZ{--shiki-default:#B392F0}html pre.shiki code .s95oV, html code.shiki .s95oV{--shiki-default:#E1E4E8}html pre.shiki code .sDLfK, html code.shiki .sDLfK{--shiki-default:#79B8FF}html pre.shiki code .sU2Wk, html code.shiki .sU2Wk{--shiki-default:#9ECBFF}html pre.shiki code .sAwPA, html code.shiki .sAwPA{--shiki-default:#6A737D}html .default .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}",{"title":41,"searchDepth":122,"depth":122,"links":854},[855,856,857,858,859,860],{"id":26,"depth":122,"text":27},{"id":69,"depth":122,"text":70},{"id":691,"depth":122,"text":692},{"id":728,"depth":122,"text":729},{"id":810,"depth":122,"text":811},{"id":833,"depth":122,"text":834},"pathfinding",null,"Learn how A* combines actual cost with a heuristic estimate to find the cheapest path while exploring fewer nodes than Dijkstra.","intermediate","md",{"timeComplexity":867,"spaceComplexity":868},"O((V + E) log V)","O(V)","\u002Flearn\u002Fastar","2026-08-15","astar",{"title":6,"description":863},"learn\u002Fastar","zGSns3Ko2TZYx0Ih91Y_TyN_WPPNP4CWhnOExKPPx54",{"id":876,"title":877,"body":878,"category":2073,"complexity":862,"date":862,"description":2074,"difficulty":864,"extension":865,"meta":2075,"navigation":221,"order":85,"path":2078,"publishedAt":2079,"relatedAlgorithmId":2080,"seo":2081,"stem":2082,"__hash__":2083},"learn\u002Flearn\u002Fbacktracking.md","Backtracking",{"type":8,"value":879,"toc":2055},[880,883,890,894,927,934,938,941,1016,1020,1023,1028,1031,1037,1044,1046,1408,1412,1416,1609,1613,1813,1817,1822,1825,1839,1842,1847,1850,1854,1892,1899,1903,1935,1939,1965,1969,1995,1999,2052],[11,881,877],{"id":882},"backtracking",[15,884,885,886,889],{},"Backtracking is an algorithmic technique for solving problems incrementally by building candidates one step at a time and ",[19,887,888],{},"abandoning"," (backtracking from) a candidate as soon as it's determined that it cannot lead to a valid solution. It's a refined form of brute force that prunes entire branches of the search space, making it far more efficient than generating all possible candidates.",[24,891,893],{"id":892},"how-it-works","How It Works",[895,896,897,903,909,915,921],"ol",{},[46,898,899,902],{},[19,900,901],{},"Choose",": Make a choice (place a queen, pick a number, take a path)",[46,904,905,908],{},[19,906,907],{},"Constraint check",": Verify the choice doesn't violate any constraints",[46,910,911,914],{},[19,912,913],{},"Recurse",": If valid, move to the next decision point and repeat",[46,916,917,920],{},[19,918,919],{},"Backtrack",": If we reach a dead end (no valid choice available), undo the last choice and try the next alternative",[46,922,923,926],{},[19,924,925],{},"Base case",": If all decisions have been made successfully, record the solution",[15,928,929,930,933],{},"The algorithm explores a ",[19,931,932],{},"decision tree"," using depth-first search, pruning branches that violate constraints.",[24,935,937],{"id":936},"the-backtracking-template","The Backtracking Template",[15,939,940],{},"Almost every backtracking problem follows this pattern:",[32,942,944],{"className":76,"code":943,"language":78,"meta":41,"style":41},"def backtrack(state, choices):\n    if is_solution(state):\n        record_solution(state)\n        return\n\n    for choice in choices:\n        if is_valid(state, choice):\n            make_choice(state, choice)\n            backtrack(state, remaining_choices)\n            undo_choice(state, choice)  # backtrack\n",[39,945,946,956,964,969,974,978,991,998,1003,1008],{"__ignoreMap":41},[82,947,948,950,953],{"class":84,"line":85},[82,949,89],{"class":88},[82,951,952],{"class":92}," backtrack",[82,954,955],{"class":96},"(state, choices):\n",[82,957,958,961],{"class":84,"line":122},[82,959,960],{"class":88},"    if",[82,962,963],{"class":96}," is_solution(state):\n",[82,965,966],{"class":84,"line":129},[82,967,968],{"class":96},"        record_solution(state)\n",[82,970,971],{"class":84,"line":135},[82,972,973],{"class":88},"        return\n",[82,975,976],{"class":84,"line":147},[82,977,222],{"emptyLinePlaceholder":221},[82,979,980,983,986,988],{"class":84,"line":176},[82,981,982],{"class":88},"    for",[82,984,985],{"class":96}," choice ",[82,987,369],{"class":88},[82,989,990],{"class":96}," choices:\n",[82,992,993,995],{"class":84,"line":199},[82,994,307],{"class":88},[82,996,997],{"class":96}," is_valid(state, choice):\n",[82,999,1000],{"class":84,"line":218},[82,1001,1002],{"class":96},"            make_choice(state, choice)\n",[82,1004,1005],{"class":84,"line":225},[82,1006,1007],{"class":96},"            backtrack(state, remaining_choices)\n",[82,1009,1010,1013],{"class":84,"line":236},[82,1011,1012],{"class":96},"            undo_choice(state, choice)  ",[82,1014,1015],{"class":258},"# backtrack\n",[24,1017,1019],{"id":1018},"n-queens-problem","N-Queens Problem",[15,1021,1022],{},"The classic backtracking example: place N queens on an N×N chessboard so that no two queens threaten each other (no shared row, column, or diagonal).",[1024,1025,1027],"h3",{"id":1026},"step-by-step-4-queens","Step-by-Step (4-Queens)",[15,1029,1030],{},"The search places one queen per row, left to right. When a column is\nrejected, the reason is shown in parentheses. When a row runs out of valid\ncolumns, the algorithm backtracks to the previous row and tries the next\noption.",[32,1032,1035],{"className":1033,"code":1034,"language":37,"meta":41},[35],"Row 0: place queen at column 0\n  Row 1: column 0 rejected (same column)\n         column 1 rejected (diagonal)\n         column 2 placed\n    Row 2: columns 0-3 all rejected  ->  backtrack to Row 1\n  Row 1: column 3 placed\n    Row 2: column 1 placed\n      Row 3: columns 0-3 all rejected  ->  backtrack to Row 2\n    Row 2: no further valid column     ->  backtrack to Row 1\n  Row 1: no further valid column       ->  backtrack to Row 0\n\nRow 0: place queen at column 1\n  Row 1: column 3 placed\n    Row 2: column 0 placed\n      Row 3: column 2 placed           ->  solution found\n",[39,1036,1034],{"__ignoreMap":41},[15,1038,1039,1040,1043],{},"Solution: ",[39,1041,1042],{},"[1, 3, 0, 2]"," — the value at each index is the column of the\nqueen in that row (row 0 → column 1, row 1 → column 3, and so on).",[24,1045,70],{"id":69},[32,1047,1049],{"className":76,"code":1048,"language":78,"meta":41,"style":41},"def solve_n_queens(n: int) -> list[list[int]]:\n    \"\"\"Find all valid N-Queens configurations.\n\n    Returns list of solutions. Each solution is a list where\n    solution[row] = column of the queen in that row.\n    \"\"\"\n    solutions = []\n    queens = []  # queens[i] = column of queen in row i\n\n    # Track attacked columns and diagonals for O(1) constraint checking\n    columns = set()\n    diag_positive = set()  # row + col (identifies \u002F diagonals)\n    diag_negative = set()  # row - col (identifies \\ diagonals)\n\n    def backtrack(row: int) -> None:\n        if row == n:\n            solutions.append(queens[:])\n            return\n\n        for col in range(n):\n            # Check if this position is under attack\n            if col in columns:\n                continue\n            if (row + col) in diag_positive:\n                continue\n            if (row - col) in diag_negative:\n                continue\n\n            # Make choice\n            queens.append(col)\n            columns.add(col)\n            diag_positive.add(row + col)\n            diag_negative.add(row - col)\n\n            # Recurse to next row\n            backtrack(row + 1)\n\n            # Undo choice (backtrack)\n            queens.pop()\n            columns.remove(col)\n            diag_positive.remove(row + col)\n            diag_negative.remove(row - col)\n\n    backtrack(0)\n    return solutions\n",[39,1050,1051,1071,1076,1080,1085,1090,1095,1104,1117,1121,1126,1139,1154,1168,1172,1191,1203,1208,1213,1217,1232,1237,1248,1252,1269,1273,1288,1292,1296,1301,1306,1311,1321,1330,1334,1339,1351,1355,1360,1365,1370,1379,1388,1392,1401],{"__ignoreMap":41},[82,1052,1053,1055,1058,1061,1063,1066,1068],{"class":84,"line":85},[82,1054,89],{"class":88},[82,1056,1057],{"class":92}," solve_n_queens",[82,1059,1060],{"class":96},"(n: ",[82,1062,101],{"class":100},[82,1064,1065],{"class":96},") -> list[list[",[82,1067,101],{"class":100},[82,1069,1070],{"class":96},"]]:\n",[82,1072,1073],{"class":84,"line":122},[82,1074,1075],{"class":125},"    \"\"\"Find all valid N-Queens configurations.\n",[82,1077,1078],{"class":84,"line":129},[82,1079,222],{"emptyLinePlaceholder":221},[82,1081,1082],{"class":84,"line":135},[82,1083,1084],{"class":125},"    Returns list of solutions. Each solution is a list where\n",[82,1086,1087],{"class":84,"line":147},[82,1088,1089],{"class":125},"    solution[row] = column of the queen in that row.\n",[82,1091,1092],{"class":84,"line":176},[82,1093,1094],{"class":125},"    \"\"\"\n",[82,1096,1097,1100,1102],{"class":84,"line":199},[82,1098,1099],{"class":96},"    solutions ",[82,1101,141],{"class":88},[82,1103,493],{"class":96},[82,1105,1106,1109,1111,1114],{"class":84,"line":218},[82,1107,1108],{"class":96},"    queens ",[82,1110,141],{"class":88},[82,1112,1113],{"class":96}," []  ",[82,1115,1116],{"class":258},"# queens[i] = column of queen in row i\n",[82,1118,1119],{"class":84,"line":225},[82,1120,222],{"emptyLinePlaceholder":221},[82,1122,1123],{"class":84,"line":236},[82,1124,1125],{"class":258},"    # Track attacked columns and diagonals for O(1) constraint checking\n",[82,1127,1128,1131,1133,1136],{"class":84,"line":247},[82,1129,1130],{"class":96},"    columns ",[82,1132,141],{"class":88},[82,1134,1135],{"class":100}," set",[82,1137,1138],{"class":96},"()\n",[82,1140,1141,1144,1146,1148,1151],{"class":84,"line":262},[82,1142,1143],{"class":96},"    diag_positive ",[82,1145,141],{"class":88},[82,1147,1135],{"class":100},[82,1149,1150],{"class":96},"()  ",[82,1152,1153],{"class":258},"# row + col (identifies \u002F diagonals)\n",[82,1155,1156,1159,1161,1163,1165],{"class":84,"line":267},[82,1157,1158],{"class":96},"    diag_negative ",[82,1160,141],{"class":88},[82,1162,1135],{"class":100},[82,1164,1150],{"class":96},[82,1166,1167],{"class":258},"# row - col (identifies \\ diagonals)\n",[82,1169,1170],{"class":84,"line":276},[82,1171,222],{"emptyLinePlaceholder":221},[82,1173,1174,1177,1179,1182,1184,1186,1189],{"class":84,"line":282},[82,1175,1176],{"class":88},"    def",[82,1178,952],{"class":92},[82,1180,1181],{"class":96},"(row: ",[82,1183,101],{"class":100},[82,1185,607],{"class":96},[82,1187,1188],{"class":100},"None",[82,1190,523],{"class":96},[82,1192,1193,1195,1198,1200],{"class":84,"line":299},[82,1194,307],{"class":88},[82,1196,1197],{"class":96}," row ",[82,1199,343],{"class":88},[82,1201,1202],{"class":96}," n:\n",[82,1204,1205],{"class":84,"line":304},[82,1206,1207],{"class":96},"            solutions.append(queens[:])\n",[82,1209,1210],{"class":84,"line":313},[82,1211,1212],{"class":88},"            return\n",[82,1214,1215],{"class":84,"line":319},[82,1216,222],{"emptyLinePlaceholder":221},[82,1218,1219,1221,1224,1226,1229],{"class":84,"line":330},[82,1220,363],{"class":88},[82,1222,1223],{"class":96}," col ",[82,1225,369],{"class":88},[82,1227,1228],{"class":100}," range",[82,1230,1231],{"class":96},"(n):\n",[82,1233,1234],{"class":84,"line":335},[82,1235,1236],{"class":258},"            # Check if this position is under attack\n",[82,1238,1239,1241,1243,1245],{"class":84,"line":349},[82,1240,378],{"class":88},[82,1242,1223],{"class":96},[82,1244,369],{"class":88},[82,1246,1247],{"class":96}," columns:\n",[82,1249,1250],{"class":84,"line":355},[82,1251,387],{"class":88},[82,1253,1254,1256,1259,1261,1264,1266],{"class":84,"line":360},[82,1255,378],{"class":88},[82,1257,1258],{"class":96}," (row ",[82,1260,406],{"class":88},[82,1262,1263],{"class":96}," col) ",[82,1265,369],{"class":88},[82,1267,1268],{"class":96}," diag_positive:\n",[82,1270,1271],{"class":84,"line":375},[82,1272,387],{"class":88},[82,1274,1275,1277,1279,1281,1283,1285],{"class":84,"line":384},[82,1276,378],{"class":88},[82,1278,1258],{"class":96},[82,1280,186],{"class":88},[82,1282,1263],{"class":96},[82,1284,369],{"class":88},[82,1286,1287],{"class":96}," diag_negative:\n",[82,1289,1290],{"class":84,"line":390},[82,1291,387],{"class":88},[82,1293,1294],{"class":84,"line":395},[82,1295,222],{"emptyLinePlaceholder":221},[82,1297,1298],{"class":84,"line":412},[82,1299,1300],{"class":258},"            # Make choice\n",[82,1302,1303],{"class":84,"line":417},[82,1304,1305],{"class":96},"            queens.append(col)\n",[82,1307,1308],{"class":84,"line":431},[82,1309,1310],{"class":96},"            columns.add(col)\n",[82,1312,1313,1316,1318],{"class":84,"line":442},[82,1314,1315],{"class":96},"            diag_positive.add(row ",[82,1317,406],{"class":88},[82,1319,1320],{"class":96}," col)\n",[82,1322,1323,1326,1328],{"class":84,"line":453},[82,1324,1325],{"class":96},"            diag_negative.add(row ",[82,1327,186],{"class":88},[82,1329,1320],{"class":96},[82,1331,1332],{"class":84,"line":468},[82,1333,222],{"emptyLinePlaceholder":221},[82,1335,1336],{"class":84,"line":474},[82,1337,1338],{"class":258},"            # Recurse to next row\n",[82,1340,1341,1344,1346,1349],{"class":84,"line":479},[82,1342,1343],{"class":96},"            backtrack(row ",[82,1345,406],{"class":88},[82,1347,1348],{"class":100}," 1",[82,1350,296],{"class":96},[82,1352,1353],{"class":84,"line":485},[82,1354,222],{"emptyLinePlaceholder":221},[82,1356,1357],{"class":84,"line":496},[82,1358,1359],{"class":258},"            # Undo choice (backtrack)\n",[82,1361,1362],{"class":84,"line":507},[82,1363,1364],{"class":96},"            queens.pop()\n",[82,1366,1367],{"class":84,"line":526},[82,1368,1369],{"class":96},"            columns.remove(col)\n",[82,1371,1372,1375,1377],{"class":84,"line":532},[82,1373,1374],{"class":96},"            diag_positive.remove(row ",[82,1376,406],{"class":88},[82,1378,1320],{"class":96},[82,1380,1381,1384,1386],{"class":84,"line":543},[82,1382,1383],{"class":96},"            diag_negative.remove(row ",[82,1385,186],{"class":88},[82,1387,1320],{"class":96},[82,1389,1390],{"class":84,"line":549},[82,1391,222],{"emptyLinePlaceholder":221},[82,1393,1394,1397,1399],{"class":84,"line":554},[82,1395,1396],{"class":96},"    backtrack(",[82,1398,293],{"class":100},[82,1400,296],{"class":96},[82,1402,1403,1405],{"class":84,"line":565},[82,1404,568],{"class":88},[82,1406,1407],{"class":96}," solutions\n",[24,1409,1411],{"id":1410},"more-examples","More Examples",[1024,1413,1415],{"id":1414},"generate-all-permutations","Generate All Permutations",[32,1417,1419],{"className":76,"code":1418,"language":78,"meta":41,"style":41},"def permutations(nums: list[int]) -> list[list[int]]:\n    \"\"\"Generate all permutations of the input list.\"\"\"\n    result = []\n    used = [False] * len(nums)\n    current = []\n\n    def backtrack() -> None:\n        if len(current) == len(nums):\n            result.append(current[:])\n            return\n\n        for i in range(len(nums)):\n            if used[i]:\n                continue\n            used[i] = True\n            current.append(nums[i])\n            backtrack()\n            current.pop()\n            used[i] = False\n\n    backtrack()\n    return result\n",[39,1420,1421,1440,1445,1454,1475,1484,1488,1501,1517,1522,1526,1530,1549,1556,1560,1569,1574,1579,1584,1593,1597,1602],{"__ignoreMap":41},[82,1422,1423,1425,1428,1431,1433,1436,1438],{"class":84,"line":85},[82,1424,89],{"class":88},[82,1426,1427],{"class":92}," permutations",[82,1429,1430],{"class":96},"(nums: list[",[82,1432,101],{"class":100},[82,1434,1435],{"class":96},"]) -> list[list[",[82,1437,101],{"class":100},[82,1439,1070],{"class":96},[82,1441,1442],{"class":84,"line":122},[82,1443,1444],{"class":125},"    \"\"\"Generate all permutations of the input list.\"\"\"\n",[82,1446,1447,1450,1452],{"class":84,"line":129},[82,1448,1449],{"class":96},"    result ",[82,1451,141],{"class":88},[82,1453,493],{"class":96},[82,1455,1456,1459,1461,1463,1465,1467,1469,1472],{"class":84,"line":135},[82,1457,1458],{"class":96},"    used ",[82,1460,141],{"class":88},[82,1462,155],{"class":96},[82,1464,209],{"class":100},[82,1466,192],{"class":96},[82,1468,170],{"class":88},[82,1470,1471],{"class":100}," len",[82,1473,1474],{"class":96},"(nums)\n",[82,1476,1477,1480,1482],{"class":84,"line":147},[82,1478,1479],{"class":96},"    current ",[82,1481,141],{"class":88},[82,1483,493],{"class":96},[82,1485,1486],{"class":84,"line":176},[82,1487,222],{"emptyLinePlaceholder":221},[82,1489,1490,1492,1494,1497,1499],{"class":84,"line":199},[82,1491,1176],{"class":88},[82,1493,952],{"class":92},[82,1495,1496],{"class":96},"() -> ",[82,1498,1188],{"class":100},[82,1500,523],{"class":96},[82,1502,1503,1505,1507,1510,1512,1514],{"class":84,"line":218},[82,1504,307],{"class":88},[82,1506,1471],{"class":100},[82,1508,1509],{"class":96},"(current) ",[82,1511,343],{"class":88},[82,1513,1471],{"class":100},[82,1515,1516],{"class":96},"(nums):\n",[82,1518,1519],{"class":84,"line":225},[82,1520,1521],{"class":96},"            result.append(current[:])\n",[82,1523,1524],{"class":84,"line":236},[82,1525,1212],{"class":88},[82,1527,1528],{"class":84,"line":247},[82,1529,222],{"emptyLinePlaceholder":221},[82,1531,1532,1534,1537,1539,1541,1543,1546],{"class":84,"line":262},[82,1533,363],{"class":88},[82,1535,1536],{"class":96}," i ",[82,1538,369],{"class":88},[82,1540,1228],{"class":100},[82,1542,161],{"class":96},[82,1544,1545],{"class":100},"len",[82,1547,1548],{"class":96},"(nums)):\n",[82,1550,1551,1553],{"class":84,"line":267},[82,1552,378],{"class":88},[82,1554,1555],{"class":96}," used[i]:\n",[82,1557,1558],{"class":84,"line":276},[82,1559,387],{"class":88},[82,1561,1562,1565,1567],{"class":84,"line":282},[82,1563,1564],{"class":96},"            used[i] ",[82,1566,141],{"class":88},[82,1568,327],{"class":100},[82,1570,1571],{"class":84,"line":299},[82,1572,1573],{"class":96},"            current.append(nums[i])\n",[82,1575,1576],{"class":84,"line":304},[82,1577,1578],{"class":96},"            backtrack()\n",[82,1580,1581],{"class":84,"line":313},[82,1582,1583],{"class":96},"            current.pop()\n",[82,1585,1586,1588,1590],{"class":84,"line":319},[82,1587,1564],{"class":96},[82,1589,141],{"class":88},[82,1591,1592],{"class":100}," False\n",[82,1594,1595],{"class":84,"line":330},[82,1596,222],{"emptyLinePlaceholder":221},[82,1598,1599],{"class":84,"line":335},[82,1600,1601],{"class":96},"    backtrack()\n",[82,1603,1604,1606],{"class":84,"line":349},[82,1605,568],{"class":88},[82,1607,1608],{"class":96}," result\n",[1024,1610,1612],{"id":1611},"subset-sum","Subset Sum",[32,1614,1616],{"className":76,"code":1615,"language":78,"meta":41,"style":41},"def subset_sum(numbers: list[int], target: int) -> list[list[int]]:\n    \"\"\"Find all subsets that sum to target.\"\"\"\n    result = []\n    current = []\n\n    def backtrack(index: int, remaining: int) -> None:\n        if remaining == 0:\n            result.append(current[:])\n            return\n        if remaining \u003C 0 or index >= len(numbers):\n            return\n\n        # Include numbers[index]\n        current.append(numbers[index])\n        backtrack(index + 1, remaining - numbers[index])\n        current.pop()\n\n        # Exclude numbers[index]\n        backtrack(index + 1, remaining)\n\n    backtrack(0, target)\n    return result\n",[39,1617,1618,1641,1646,1654,1662,1666,1688,1702,1706,1710,1734,1738,1742,1747,1752,1769,1774,1778,1783,1794,1798,1807],{"__ignoreMap":41},[82,1619,1620,1622,1625,1628,1630,1633,1635,1637,1639],{"class":84,"line":85},[82,1621,89],{"class":88},[82,1623,1624],{"class":92}," subset_sum",[82,1626,1627],{"class":96},"(numbers: list[",[82,1629,101],{"class":100},[82,1631,1632],{"class":96},"], target: ",[82,1634,101],{"class":100},[82,1636,1065],{"class":96},[82,1638,101],{"class":100},[82,1640,1070],{"class":96},[82,1642,1643],{"class":84,"line":122},[82,1644,1645],{"class":125},"    \"\"\"Find all subsets that sum to target.\"\"\"\n",[82,1647,1648,1650,1652],{"class":84,"line":129},[82,1649,1449],{"class":96},[82,1651,141],{"class":88},[82,1653,493],{"class":96},[82,1655,1656,1658,1660],{"class":84,"line":135},[82,1657,1479],{"class":96},[82,1659,141],{"class":88},[82,1661,493],{"class":96},[82,1663,1664],{"class":84,"line":147},[82,1665,222],{"emptyLinePlaceholder":221},[82,1667,1668,1670,1672,1675,1677,1680,1682,1684,1686],{"class":84,"line":176},[82,1669,1176],{"class":88},[82,1671,952],{"class":92},[82,1673,1674],{"class":96},"(index: ",[82,1676,101],{"class":100},[82,1678,1679],{"class":96},", remaining: ",[82,1681,101],{"class":100},[82,1683,607],{"class":96},[82,1685,1188],{"class":100},[82,1687,523],{"class":96},[82,1689,1690,1692,1695,1697,1700],{"class":84,"line":199},[82,1691,307],{"class":88},[82,1693,1694],{"class":96}," remaining ",[82,1696,343],{"class":88},[82,1698,1699],{"class":100}," 0",[82,1701,523],{"class":96},[82,1703,1704],{"class":84,"line":218},[82,1705,1521],{"class":96},[82,1707,1708],{"class":84,"line":225},[82,1709,1212],{"class":88},[82,1711,1712,1714,1716,1718,1720,1723,1726,1729,1731],{"class":84,"line":236},[82,1713,307],{"class":88},[82,1715,1694],{"class":96},[82,1717,425],{"class":88},[82,1719,1699],{"class":100},[82,1721,1722],{"class":88}," or",[82,1724,1725],{"class":96}," index ",[82,1727,1728],{"class":88},">=",[82,1730,1471],{"class":100},[82,1732,1733],{"class":96},"(numbers):\n",[82,1735,1736],{"class":84,"line":247},[82,1737,1212],{"class":88},[82,1739,1740],{"class":84,"line":262},[82,1741,222],{"emptyLinePlaceholder":221},[82,1743,1744],{"class":84,"line":267},[82,1745,1746],{"class":258},"        # Include numbers[index]\n",[82,1748,1749],{"class":84,"line":276},[82,1750,1751],{"class":96},"        current.append(numbers[index])\n",[82,1753,1754,1757,1759,1761,1764,1766],{"class":84,"line":282},[82,1755,1756],{"class":96},"        backtrack(index ",[82,1758,406],{"class":88},[82,1760,1348],{"class":100},[82,1762,1763],{"class":96},", remaining ",[82,1765,186],{"class":88},[82,1767,1768],{"class":96}," numbers[index])\n",[82,1770,1771],{"class":84,"line":299},[82,1772,1773],{"class":96},"        current.pop()\n",[82,1775,1776],{"class":84,"line":304},[82,1777,222],{"emptyLinePlaceholder":221},[82,1779,1780],{"class":84,"line":313},[82,1781,1782],{"class":258},"        # Exclude numbers[index]\n",[82,1784,1785,1787,1789,1791],{"class":84,"line":319},[82,1786,1756],{"class":96},[82,1788,406],{"class":88},[82,1790,1348],{"class":100},[82,1792,1793],{"class":96},", remaining)\n",[82,1795,1796],{"class":84,"line":330},[82,1797,222],{"emptyLinePlaceholder":221},[82,1799,1800,1802,1804],{"class":84,"line":335},[82,1801,1396],{"class":96},[82,1803,293],{"class":100},[82,1805,1806],{"class":96},", target)\n",[82,1808,1809,1811],{"class":84,"line":349},[82,1810,568],{"class":88},[82,1812,1608],{"class":96},[24,1814,1816],{"id":1815},"complexity-analysis","Complexity Analysis",[15,1818,1819],{},[19,1820,1821],{},"Time Complexity: O(n!)",[15,1823,1824],{},"For the N-Queens problem:",[43,1826,1827,1830,1833,1836],{},[46,1828,1829],{},"Row 0 has n choices",[46,1831,1832],{},"Row 1 has at most n-1 valid choices (one column blocked)",[46,1834,1835],{},"Row 2 has at most n-2 valid choices",[46,1837,1838],{},"Total: approximately n × (n-1) × (n-2) × ... = O(n!)",[15,1840,1841],{},"In practice, pruning eliminates many branches early, so the actual number of nodes explored is much less than n!. For 8-Queens, instead of checking all 8^8 = 16 million placements, backtracking explores only about 15,000 nodes.",[15,1843,1844],{},[19,1845,1846],{},"Space Complexity: O(n)",[15,1848,1849],{},"The recursion depth is at most n (one level per row\u002Fdecision). The constraint tracking sets use O(n) space. Total auxiliary space is O(n).",[24,1851,1853],{"id":1852},"backtracking-vs-brute-force","Backtracking vs. Brute Force",[731,1855,1856,1869],{},[734,1857,1858],{},[737,1859,1860,1863,1866],{},[740,1861,1862],{},"Approach",[740,1864,1865],{},"Strategy",[740,1867,1868],{},"N-Queens (n=8)",[750,1870,1871,1882],{},[737,1872,1873,1876,1879],{},[755,1874,1875],{},"Brute Force",[755,1877,1878],{},"Try all n^n placements",[755,1880,1881],{},"16,777,216 checks",[737,1883,1884,1886,1889],{},[755,1885,877],{},[755,1887,1888],{},"Prune invalid branches early",[755,1890,1891],{},"~15,000 nodes",[15,1893,1894,1895,1898],{},"Backtracking's power is in ",[19,1896,1897],{},"early pruning",". As soon as a partial solution violates a constraint, the entire subtree is skipped.",[24,1900,1902],{"id":1901},"when-to-use-backtracking","When to Use Backtracking",[43,1904,1905,1911,1917,1923,1929],{},[46,1906,1907,1910],{},[19,1908,1909],{},"Constraint satisfaction",": Sudoku, crossword puzzles, graph coloring.",[46,1912,1913,1916],{},[19,1914,1915],{},"Combinatorial search",": Permutations, combinations, subsets.",[46,1918,1919,1922],{},[19,1920,1921],{},"Optimization with constraints",": Find best solution among valid candidates (e.g., knapsack).",[46,1924,1925,1928],{},[19,1926,1927],{},"Puzzle solving",": N-Queens, mazes, word search, cryptarithmetic.",[46,1930,1931,1934],{},[19,1932,1933],{},"Game trees",": Chess\u002Fcheckers move exploration (with alpha-beta pruning).",[24,1936,1938],{"id":1937},"when-to-avoid-it","When to Avoid It",[43,1940,1941,1947,1953,1959],{},[46,1942,1943,1946],{},[19,1944,1945],{},"Greedy works",": If a greedy algorithm gives the optimal solution, it's faster than exploring all branches.",[46,1948,1949,1952],{},[19,1950,1951],{},"Dynamic programming applies",": If subproblems overlap, DP avoids redundant computation.",[46,1954,1955,1958],{},[19,1956,1957],{},"No constraints to prune",": If every branch must be explored anyway, backtracking degenerates to brute force.",[46,1960,1961,1964],{},[19,1962,1963],{},"Tight time limits",": For very large n, even pruned backtracking may be too slow. Consider approximation algorithms.",[24,1966,1968],{"id":1967},"optimization-techniques","Optimization Techniques",[43,1970,1971,1977,1983,1989],{},[46,1972,1973,1976],{},[19,1974,1975],{},"Constraint propagation",": Maintain sets of valid choices to prune faster.",[46,1978,1979,1982],{},[19,1980,1981],{},"Variable ordering",": Choose the most constrained variable first (most restricted row\u002Fcolumn).",[46,1984,1985,1988],{},[19,1986,1987],{},"Symmetry breaking",": Avoid exploring mirror\u002Frotated solutions (reduces work by up to 8x for N-Queens).",[46,1990,1991,1994],{},[19,1992,1993],{},"Memoization",": Cache explored states if the same subproblem can be reached via different paths.",[24,1996,1998],{"id":1997},"key-properties","Key Properties",[731,2000,2001,2010],{},[734,2002,2003],{},[737,2004,2005,2007],{},[740,2006,742],{},[740,2008,2009],{},"Value",[750,2011,2012,2020,2028,2036,2044],{},[737,2013,2014,2017],{},[755,2015,2016],{},"Paradigm",[755,2018,2019],{},"Exhaustive search with pruning",[737,2021,2022,2025],{},[755,2023,2024],{},"Explores",[755,2026,2027],{},"Decision tree (DFS)",[737,2029,2030,2033],{},[755,2031,2032],{},"Pruning",[755,2034,2035],{},"Yes — skips invalid branches",[737,2037,2038,2041],{},[755,2039,2040],{},"Guarantees optimal",[755,2042,2043],{},"Yes (finds all\u002Fbest solutions)",[737,2045,2046,2049],{},[755,2047,2048],{},"Time",[755,2050,2051],{},"Exponential worst case (O(n!) or O(2^n))",[850,2053,2054],{},"html pre.shiki code .snl16, html code.shiki .snl16{--shiki-default:#F97583}html pre.shiki code .svObZ, html code.shiki .svObZ{--shiki-default:#B392F0}html pre.shiki code .s95oV, html code.shiki .s95oV{--shiki-default:#E1E4E8}html pre.shiki code .sAwPA, html code.shiki .sAwPA{--shiki-default:#6A737D}html .default .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html pre.shiki code .sDLfK, html code.shiki .sDLfK{--shiki-default:#79B8FF}html pre.shiki code .sU2Wk, html code.shiki .sU2Wk{--shiki-default:#9ECBFF}",{"title":41,"searchDepth":122,"depth":122,"links":2056},[2057,2058,2059,2062,2063,2067,2068,2069,2070,2071,2072],{"id":892,"depth":122,"text":893},{"id":936,"depth":122,"text":937},{"id":1018,"depth":122,"text":1019,"children":2060},[2061],{"id":1026,"depth":129,"text":1027},{"id":69,"depth":122,"text":70},{"id":1410,"depth":122,"text":1411,"children":2064},[2065,2066],{"id":1414,"depth":129,"text":1415},{"id":1611,"depth":129,"text":1612},{"id":1815,"depth":122,"text":1816},{"id":1852,"depth":122,"text":1853},{"id":1901,"depth":122,"text":1902},{"id":1937,"depth":122,"text":1938},{"id":1967,"depth":122,"text":1968},{"id":1997,"depth":122,"text":1998},"algorithms","Learn the backtracking algorithm technique for solving constraint satisfaction problems like N-Queens, permutations, and sudoku.",{"timeComplexity":2076,"spaceComplexity":2077},"O(n!)","O(n)","\u002Flearn\u002Fbacktracking","2026-08-23","n-queens",{"title":877,"description":2074},"learn\u002Fbacktracking","DRvJUBqTEY3QTRUacrZpfKnLA60WXtXBmQgUN4447Rc",{"id":2085,"title":2086,"body":2087,"category":861,"complexity":862,"date":862,"description":2461,"difficulty":2462,"extension":865,"meta":2463,"navigation":221,"order":122,"path":2465,"publishedAt":870,"relatedAlgorithmId":2466,"seo":2467,"stem":2468,"__hash__":2469},"learn\u002Flearn\u002Fbfs.md","Breadth-First Search (BFS)",{"type":8,"value":2088,"toc":2454},[2089,2092,2095,2097,2111,2114,2116,2119,2389,2393,2396,2407,2414,2418,2431,2435,2452],[11,2090,2086],{"id":2091},"breadth-first-search-bfs",[15,2093,2094],{},"BFS explores a graph layer by layer — it visits all nodes at distance 1 before any node at distance 2, all at distance 2 before distance 3, and so on. This level-order exploration guarantees that the first time BFS reaches any node, it has found the shortest path (fewest edges) to it.",[24,2096,893],{"id":892},[895,2098,2099,2102,2105,2108],{},[46,2100,2101],{},"Start at the source node, mark it visited, add it to the queue",[46,2103,2104],{},"Take the front node from the queue",[46,2106,2107],{},"Visit all its unvisited neighbors, mark them visited, add them to the queue",[46,2109,2110],{},"Repeat until the queue is empty or the goal is found",[15,2112,2113],{},"The queue (FIFO) is what creates the level-order property — nodes discovered earlier are processed earlier.",[24,2115,70],{"id":69},[15,2117,2118],{},"Uses the Graph class from the Graphs and Weighted Graphs article:",[32,2120,2122],{"className":76,"code":2121,"language":78,"meta":41,"style":41},"def breadth_first_search(graph, start_node: int, goal_node: int) -> list[int]:\n    \"\"\"Find shortest path (fewest hops) from start to goal.\"\"\"\n    visited = [False] * graph.num_nodes\n    parent_of = [-1] * graph.num_nodes\n    visited[start_node] = True\n\n    # Queue implemented as list with head pointer\n    queue = [start_node]\n    head = 0\n\n    while head \u003C len(queue):\n        current_node = queue[head]\n        head += 1\n\n        if current_node == goal_node:\n            break\n\n        for neighbor in graph.get_neighbors(current_node):\n            if not visited[neighbor]:\n                visited[neighbor] = True\n                parent_of[neighbor] = current_node\n                queue.append(neighbor)\n\n    # Reconstruct path from goal back to start\n    path = []\n    node = goal_node\n    while node != -1:\n        path.append(node)\n        node = parent_of[node]\n    path.reverse()\n    return path\n",[39,2123,2124,2146,2151,2167,2185,2194,2198,2203,2213,2222,2226,2240,2250,2261,2265,2275,2279,2283,2294,2304,2313,2322,2327,2331,2336,2344,2352,2366,2370,2378,2382],{"__ignoreMap":41},[82,2125,2126,2128,2131,2133,2135,2137,2139,2142,2144],{"class":84,"line":85},[82,2127,89],{"class":88},[82,2129,2130],{"class":92}," breadth_first_search",[82,2132,97],{"class":96},[82,2134,101],{"class":100},[82,2136,104],{"class":96},[82,2138,101],{"class":100},[82,2140,2141],{"class":96},") -> list[",[82,2143,101],{"class":100},[82,2145,119],{"class":96},[82,2147,2148],{"class":84,"line":122},[82,2149,2150],{"class":125},"    \"\"\"Find shortest path (fewest hops) from start to goal.\"\"\"\n",[82,2152,2153,2155,2157,2159,2161,2163,2165],{"class":84,"line":129},[82,2154,202],{"class":96},[82,2156,141],{"class":88},[82,2158,155],{"class":96},[82,2160,209],{"class":100},[82,2162,192],{"class":96},[82,2164,170],{"class":88},[82,2166,144],{"class":96},[82,2168,2169,2171,2173,2175,2177,2179,2181,2183],{"class":84,"line":135},[82,2170,179],{"class":96},[82,2172,141],{"class":88},[82,2174,155],{"class":96},[82,2176,186],{"class":88},[82,2178,189],{"class":100},[82,2180,192],{"class":96},[82,2182,170],{"class":88},[82,2184,144],{"class":96},[82,2186,2187,2190,2192],{"class":84,"line":147},[82,2188,2189],{"class":96},"    visited[start_node] ",[82,2191,141],{"class":88},[82,2193,327],{"class":100},[82,2195,2196],{"class":84,"line":176},[82,2197,222],{"emptyLinePlaceholder":221},[82,2199,2200],{"class":84,"line":199},[82,2201,2202],{"class":258},"    # Queue implemented as list with head pointer\n",[82,2204,2205,2208,2210],{"class":84,"line":218},[82,2206,2207],{"class":96},"    queue ",[82,2209,141],{"class":88},[82,2211,2212],{"class":96}," [start_node]\n",[82,2214,2215,2218,2220],{"class":84,"line":225},[82,2216,2217],{"class":96},"    head ",[82,2219,141],{"class":88},[82,2221,233],{"class":100},[82,2223,2224],{"class":84,"line":236},[82,2225,222],{"emptyLinePlaceholder":221},[82,2227,2228,2230,2233,2235,2237],{"class":84,"line":247},[82,2229,270],{"class":88},[82,2231,2232],{"class":96}," head ",[82,2234,425],{"class":88},[82,2236,1471],{"class":100},[82,2238,2239],{"class":96},"(queue):\n",[82,2241,2242,2245,2247],{"class":84,"line":262},[82,2243,2244],{"class":96},"        current_node ",[82,2246,141],{"class":88},[82,2248,2249],{"class":96}," queue[head]\n",[82,2251,2252,2255,2258],{"class":84,"line":267},[82,2253,2254],{"class":96},"        head ",[82,2256,2257],{"class":88},"+=",[82,2259,2260],{"class":100}," 1\n",[82,2262,2263],{"class":84,"line":276},[82,2264,222],{"emptyLinePlaceholder":221},[82,2266,2267,2269,2271,2273],{"class":84,"line":282},[82,2268,307],{"class":88},[82,2270,340],{"class":96},[82,2272,343],{"class":88},[82,2274,346],{"class":96},[82,2276,2277],{"class":84,"line":299},[82,2278,352],{"class":88},[82,2280,2281],{"class":84,"line":304},[82,2282,222],{"emptyLinePlaceholder":221},[82,2284,2285,2287,2290,2292],{"class":84,"line":313},[82,2286,363],{"class":88},[82,2288,2289],{"class":96}," neighbor ",[82,2291,369],{"class":88},[82,2293,372],{"class":96},[82,2295,2296,2298,2301],{"class":84,"line":319},[82,2297,378],{"class":88},[82,2299,2300],{"class":88}," not",[82,2302,2303],{"class":96}," visited[neighbor]:\n",[82,2305,2306,2309,2311],{"class":84,"line":330},[82,2307,2308],{"class":96},"                visited[neighbor] ",[82,2310,141],{"class":88},[82,2312,327],{"class":100},[82,2314,2315,2318,2320],{"class":84,"line":335},[82,2316,2317],{"class":96},"                parent_of[neighbor] ",[82,2319,141],{"class":88},[82,2321,450],{"class":96},[82,2323,2324],{"class":84,"line":349},[82,2325,2326],{"class":96},"                queue.append(neighbor)\n",[82,2328,2329],{"class":84,"line":355},[82,2330,222],{"emptyLinePlaceholder":221},[82,2332,2333],{"class":84,"line":360},[82,2334,2335],{"class":258},"    # Reconstruct path from goal back to start\n",[82,2337,2338,2340,2342],{"class":84,"line":375},[82,2339,488],{"class":96},[82,2341,141],{"class":88},[82,2343,493],{"class":96},[82,2345,2346,2348,2350],{"class":84,"line":384},[82,2347,499],{"class":96},[82,2349,141],{"class":88},[82,2351,504],{"class":96},[82,2353,2354,2356,2358,2360,2362,2364],{"class":84,"line":390},[82,2355,270],{"class":88},[82,2357,512],{"class":96},[82,2359,515],{"class":88},[82,2361,518],{"class":88},[82,2363,189],{"class":100},[82,2365,523],{"class":96},[82,2367,2368],{"class":84,"line":395},[82,2369,529],{"class":96},[82,2371,2372,2374,2376],{"class":84,"line":412},[82,2373,535],{"class":96},[82,2375,141],{"class":88},[82,2377,540],{"class":96},[82,2379,2380],{"class":84,"line":417},[82,2381,546],{"class":96},[82,2383,2384,2386],{"class":84,"line":431},[82,2385,568],{"class":88},[82,2387,2388],{"class":96}," path\n",[24,2390,2392],{"id":2391},"why-bfs-guarantees-shortest-path","Why BFS Guarantees Shortest Path",[15,2394,2395],{},"When BFS discovers a node, it has arrived via the fewest possible edges. This is because:",[43,2397,2398,2401,2404],{},[46,2399,2400],{},"All distance-1 nodes are enqueued before any distance-2 node",[46,2402,2403],{},"All distance-2 nodes are processed before any distance-3 node",[46,2405,2406],{},"A node is never re-visited (marked visited on discovery, not processing)",[15,2408,2409,2410,2413],{},"This only holds for ",[19,2411,2412],{},"unweighted"," graphs. On weighted graphs, fewer hops does not mean lower cost — use Dijkstra instead.",[24,2415,2417],{"id":2416},"time-and-space-complexity","Time and Space Complexity",[43,2419,2420,2425],{},[46,2421,2422,2424],{},[19,2423,2048],{},": O(V + E) — visits each node once, checks each edge once",[46,2426,2427,2430],{},[19,2428,2429],{},"Space",": O(V) — the queue can hold up to V nodes (entire frontier at maximum width)",[24,2432,2434],{"id":2433},"when-to-use-bfs","When to Use BFS",[43,2436,2437,2440,2443,2446,2449],{},[46,2438,2439],{},"Finding shortest path on unweighted graphs",[46,2441,2442],{},"Level-order tree traversal",[46,2444,2445],{},"Finding all nodes within k steps of a source",[46,2447,2448],{},"Checking if two nodes are connected (reachability)",[46,2450,2451],{},"Social network degree-of-separation queries",[850,2453,852],{},{"title":41,"searchDepth":122,"depth":122,"links":2455},[2456,2457,2458,2459,2460],{"id":892,"depth":122,"text":893},{"id":69,"depth":122,"text":70},{"id":2391,"depth":122,"text":2392},{"id":2416,"depth":122,"text":2417},{"id":2433,"depth":122,"text":2434},"Learn how BFS explores graphs level by level using a queue, guaranteeing the shortest path on unweighted graphs.","beginner",{"timeComplexity":2464,"spaceComplexity":868},"O(V + E)","\u002Flearn\u002Fbfs","bfs",{"title":2086,"description":2461},"learn\u002Fbfs","TgWCRntLMi0fJSLV5KrrWafUUPLO2kLU1pivAEULsQ0",{"id":2471,"title":2472,"body":2473,"category":3113,"complexity":862,"date":862,"description":3114,"difficulty":2462,"extension":865,"meta":3115,"navigation":221,"order":129,"path":3116,"publishedAt":870,"relatedAlgorithmId":862,"seo":3117,"stem":3118,"__hash__":3119},"learn\u002Flearn\u002Fbfs-vs-dfs.md","BFS vs DFS: When to Use Each",{"type":8,"value":2474,"toc":3100},[2475,2478,2481,2485,2492,2499,2503,2510,2517,2521,2525,2662,2666,2828,2832,2971,2975,2978,2981,2985,3005,3009,3035,3039,3097],[11,2476,2472],{"id":2477},"bfs-vs-dfs-when-to-use-each",[15,2479,2480],{},"Breadth-First Search (BFS) and Depth-First Search (DFS) are the two fundamental ways to explore a graph or tree. They both visit every reachable node exactly once, both run in O(V + E) time, but they explore in completely different orders — and that difference determines which problems each one solves well.",[24,2482,2484],{"id":2483},"how-bfs-works","How BFS Works",[15,2486,2487,2488,2491],{},"BFS uses a ",[19,2489,2490],{},"queue"," (FIFO). It visits all neighbors of the current node before moving deeper. Think of it like ripples expanding outward from a stone dropped in water — layer by layer, level by level.",[15,2493,2494,2495,2498],{},"Because BFS explores nodes in order of their distance from the source, it ",[19,2496,2497],{},"guarantees the shortest path"," on unweighted graphs.",[24,2500,2502],{"id":2501},"how-dfs-works","How DFS Works",[15,2504,2505,2506,2509],{},"DFS uses a ",[19,2507,2508],{},"stack"," (LIFO) — either explicitly or through recursion's call stack. It plunges as deep as possible along one branch before backtracking.",[15,2511,2512,2513,2516],{},"DFS does ",[19,2514,2515],{},"not"," guarantee shortest paths. It might find a path that takes 50 steps when a 3-step path exists.",[24,2518,2520],{"id":2519},"code-snippets","Code Snippets",[1024,2522,2524],{"id":2523},"graph-setup","Graph Setup",[32,2526,2528],{"className":76,"code":2527,"language":78,"meta":41,"style":41},"class Graph:\n    def __init__(self, num_nodes: int):\n        self.num_nodes = num_nodes\n        self.adjacency_list = [[] for _ in range(num_nodes)]\n\n    def add_edge(self, from_node: int, to_node: int):\n        self.adjacency_list[from_node].append(to_node)\n        self.adjacency_list[to_node].append(from_node)\n\n    def get_neighbors(self, node: int) -> list[int]:\n        return self.adjacency_list[node]\n",[39,2529,2530,2540,2555,2567,2592,2596,2615,2622,2629,2633,2651],{"__ignoreMap":41},[82,2531,2532,2535,2538],{"class":84,"line":85},[82,2533,2534],{"class":88},"class",[82,2536,2537],{"class":92}," Graph",[82,2539,523],{"class":96},[82,2541,2542,2544,2547,2550,2552],{"class":84,"line":122},[82,2543,1176],{"class":88},[82,2545,2546],{"class":100}," __init__",[82,2548,2549],{"class":96},"(self, num_nodes: ",[82,2551,101],{"class":100},[82,2553,2554],{"class":96},"):\n",[82,2556,2557,2560,2563,2565],{"class":84,"line":129},[82,2558,2559],{"class":100},"        self",[82,2561,2562],{"class":96},".num_nodes ",[82,2564,141],{"class":88},[82,2566,173],{"class":96},[82,2568,2569,2571,2574,2576,2579,2582,2585,2587,2589],{"class":84,"line":135},[82,2570,2559],{"class":100},[82,2572,2573],{"class":96},".adjacency_list ",[82,2575,141],{"class":88},[82,2577,2578],{"class":96}," [[] ",[82,2580,2581],{"class":88},"for",[82,2583,2584],{"class":96}," _ ",[82,2586,369],{"class":88},[82,2588,1228],{"class":100},[82,2590,2591],{"class":96},"(num_nodes)]\n",[82,2593,2594],{"class":84,"line":147},[82,2595,222],{"emptyLinePlaceholder":221},[82,2597,2598,2600,2603,2606,2608,2611,2613],{"class":84,"line":176},[82,2599,1176],{"class":88},[82,2601,2602],{"class":92}," add_edge",[82,2604,2605],{"class":96},"(self, from_node: ",[82,2607,101],{"class":100},[82,2609,2610],{"class":96},", to_node: ",[82,2612,101],{"class":100},[82,2614,2554],{"class":96},[82,2616,2617,2619],{"class":84,"line":199},[82,2618,2559],{"class":100},[82,2620,2621],{"class":96},".adjacency_list[from_node].append(to_node)\n",[82,2623,2624,2626],{"class":84,"line":218},[82,2625,2559],{"class":100},[82,2627,2628],{"class":96},".adjacency_list[to_node].append(from_node)\n",[82,2630,2631],{"class":84,"line":225},[82,2632,222],{"emptyLinePlaceholder":221},[82,2634,2635,2637,2640,2643,2645,2647,2649],{"class":84,"line":236},[82,2636,1176],{"class":88},[82,2638,2639],{"class":92}," get_neighbors",[82,2641,2642],{"class":96},"(self, node: ",[82,2644,101],{"class":100},[82,2646,2141],{"class":96},[82,2648,101],{"class":100},[82,2650,119],{"class":96},[82,2652,2653,2656,2659],{"class":84,"line":247},[82,2654,2655],{"class":88},"        return",[82,2657,2658],{"class":100}," self",[82,2660,2661],{"class":96},".adjacency_list[node]\n",[1024,2663,2665],{"id":2664},"breadth-first-search","Breadth-First Search",[32,2667,2669],{"className":76,"code":2668,"language":78,"meta":41,"style":41},"def breadth_first_search(graph: Graph, start_node: int) -> list[int]:\n    \"\"\"Explore graph level by level using a queue.\"\"\"\n    visited = [False] * graph.num_nodes\n    visited[start_node] = True\n\n    queue = [start_node]\n    head = 0\n    visit_order = []\n\n    while head \u003C len(queue):\n        current_node = queue[head]\n        head += 1\n        visit_order.append(current_node)\n\n        for neighbor in graph.get_neighbors(current_node):\n            if not visited[neighbor]:\n                visited[neighbor] = True\n                queue.append(neighbor)\n\n    return visit_order\n",[39,2670,2671,2688,2693,2709,2717,2721,2729,2737,2746,2750,2762,2770,2778,2783,2787,2797,2805,2813,2817,2821],{"__ignoreMap":41},[82,2672,2673,2675,2677,2680,2682,2684,2686],{"class":84,"line":85},[82,2674,89],{"class":88},[82,2676,2130],{"class":92},[82,2678,2679],{"class":96},"(graph: Graph, start_node: ",[82,2681,101],{"class":100},[82,2683,2141],{"class":96},[82,2685,101],{"class":100},[82,2687,119],{"class":96},[82,2689,2690],{"class":84,"line":122},[82,2691,2692],{"class":125},"    \"\"\"Explore graph level by level using a queue.\"\"\"\n",[82,2694,2695,2697,2699,2701,2703,2705,2707],{"class":84,"line":129},[82,2696,202],{"class":96},[82,2698,141],{"class":88},[82,2700,155],{"class":96},[82,2702,209],{"class":100},[82,2704,192],{"class":96},[82,2706,170],{"class":88},[82,2708,144],{"class":96},[82,2710,2711,2713,2715],{"class":84,"line":135},[82,2712,2189],{"class":96},[82,2714,141],{"class":88},[82,2716,327],{"class":100},[82,2718,2719],{"class":84,"line":147},[82,2720,222],{"emptyLinePlaceholder":221},[82,2722,2723,2725,2727],{"class":84,"line":176},[82,2724,2207],{"class":96},[82,2726,141],{"class":88},[82,2728,2212],{"class":96},[82,2730,2731,2733,2735],{"class":84,"line":199},[82,2732,2217],{"class":96},[82,2734,141],{"class":88},[82,2736,233],{"class":100},[82,2738,2739,2742,2744],{"class":84,"line":218},[82,2740,2741],{"class":96},"    visit_order ",[82,2743,141],{"class":88},[82,2745,493],{"class":96},[82,2747,2748],{"class":84,"line":225},[82,2749,222],{"emptyLinePlaceholder":221},[82,2751,2752,2754,2756,2758,2760],{"class":84,"line":236},[82,2753,270],{"class":88},[82,2755,2232],{"class":96},[82,2757,425],{"class":88},[82,2759,1471],{"class":100},[82,2761,2239],{"class":96},[82,2763,2764,2766,2768],{"class":84,"line":247},[82,2765,2244],{"class":96},[82,2767,141],{"class":88},[82,2769,2249],{"class":96},[82,2771,2772,2774,2776],{"class":84,"line":262},[82,2773,2254],{"class":96},[82,2775,2257],{"class":88},[82,2777,2260],{"class":100},[82,2779,2780],{"class":84,"line":267},[82,2781,2782],{"class":96},"        visit_order.append(current_node)\n",[82,2784,2785],{"class":84,"line":276},[82,2786,222],{"emptyLinePlaceholder":221},[82,2788,2789,2791,2793,2795],{"class":84,"line":282},[82,2790,363],{"class":88},[82,2792,2289],{"class":96},[82,2794,369],{"class":88},[82,2796,372],{"class":96},[82,2798,2799,2801,2803],{"class":84,"line":299},[82,2800,378],{"class":88},[82,2802,2300],{"class":88},[82,2804,2303],{"class":96},[82,2806,2807,2809,2811],{"class":84,"line":304},[82,2808,2308],{"class":96},[82,2810,141],{"class":88},[82,2812,327],{"class":100},[82,2814,2815],{"class":84,"line":313},[82,2816,2326],{"class":96},[82,2818,2819],{"class":84,"line":319},[82,2820,222],{"emptyLinePlaceholder":221},[82,2822,2823,2825],{"class":84,"line":330},[82,2824,568],{"class":88},[82,2826,2827],{"class":96}," visit_order\n",[1024,2829,2831],{"id":2830},"depth-first-search","Depth-First Search",[32,2833,2835],{"className":76,"code":2834,"language":78,"meta":41,"style":41},"def depth_first_search(graph: Graph, start_node: int) -> list[int]:\n    \"\"\"Explore graph branch by branch using a stack.\"\"\"\n    visited = [False] * graph.num_nodes\n    stack = [start_node]\n    visit_order = []\n\n    while stack:\n        current_node = stack.pop()\n        if visited[current_node]:\n            continue\n        visited[current_node] = True\n        visit_order.append(current_node)\n\n        for neighbor in graph.get_neighbors(current_node):\n            if not visited[neighbor]:\n                stack.append(neighbor)\n\n    return visit_order\n",[39,2836,2837,2854,2859,2875,2884,2892,2896,2903,2912,2918,2922,2930,2934,2938,2948,2956,2961,2965],{"__ignoreMap":41},[82,2838,2839,2841,2844,2846,2848,2850,2852],{"class":84,"line":85},[82,2840,89],{"class":88},[82,2842,2843],{"class":92}," depth_first_search",[82,2845,2679],{"class":96},[82,2847,101],{"class":100},[82,2849,2141],{"class":96},[82,2851,101],{"class":100},[82,2853,119],{"class":96},[82,2855,2856],{"class":84,"line":122},[82,2857,2858],{"class":125},"    \"\"\"Explore graph branch by branch using a stack.\"\"\"\n",[82,2860,2861,2863,2865,2867,2869,2871,2873],{"class":84,"line":129},[82,2862,202],{"class":96},[82,2864,141],{"class":88},[82,2866,155],{"class":96},[82,2868,209],{"class":100},[82,2870,192],{"class":96},[82,2872,170],{"class":88},[82,2874,144],{"class":96},[82,2876,2877,2880,2882],{"class":84,"line":135},[82,2878,2879],{"class":96},"    stack ",[82,2881,141],{"class":88},[82,2883,2212],{"class":96},[82,2885,2886,2888,2890],{"class":84,"line":147},[82,2887,2741],{"class":96},[82,2889,141],{"class":88},[82,2891,493],{"class":96},[82,2893,2894],{"class":84,"line":176},[82,2895,222],{"emptyLinePlaceholder":221},[82,2897,2898,2900],{"class":84,"line":199},[82,2899,270],{"class":88},[82,2901,2902],{"class":96}," stack:\n",[82,2904,2905,2907,2909],{"class":84,"line":218},[82,2906,2244],{"class":96},[82,2908,141],{"class":88},[82,2910,2911],{"class":96}," stack.pop()\n",[82,2913,2914,2916],{"class":84,"line":225},[82,2915,307],{"class":88},[82,2917,310],{"class":96},[82,2919,2920],{"class":84,"line":236},[82,2921,316],{"class":88},[82,2923,2924,2926,2928],{"class":84,"line":247},[82,2925,322],{"class":96},[82,2927,141],{"class":88},[82,2929,327],{"class":100},[82,2931,2932],{"class":84,"line":262},[82,2933,2782],{"class":96},[82,2935,2936],{"class":84,"line":267},[82,2937,222],{"emptyLinePlaceholder":221},[82,2939,2940,2942,2944,2946],{"class":84,"line":276},[82,2941,363],{"class":88},[82,2943,2289],{"class":96},[82,2945,369],{"class":88},[82,2947,372],{"class":96},[82,2949,2950,2952,2954],{"class":84,"line":282},[82,2951,378],{"class":88},[82,2953,2300],{"class":88},[82,2955,2303],{"class":96},[82,2957,2958],{"class":84,"line":299},[82,2959,2960],{"class":96},"                stack.append(neighbor)\n",[82,2962,2963],{"class":84,"line":304},[82,2964,222],{"emptyLinePlaceholder":221},[82,2966,2967,2969],{"class":84,"line":313},[82,2968,568],{"class":88},[82,2970,2827],{"class":96},[24,2972,2974],{"id":2973},"the-key-trade-off-memory","The Key Trade-Off: Memory",[15,2976,2977],{},"BFS must store the entire frontier — all nodes at the current depth level. For wide graphs, this memory cost is enormous.",[15,2979,2980],{},"DFS only stores the current path. For a tree with depth 20 and branching factor 10, DFS holds ~20 nodes in memory while BFS might hold millions.",[24,2982,2984],{"id":2983},"when-to-choose-bfs","When to Choose BFS",[43,2986,2987,2993,2999],{},[46,2988,2989,2992],{},[19,2990,2991],{},"Shortest path on unweighted graphs"," — BFS is optimal here",[46,2994,2995,2998],{},[19,2996,2997],{},"Level-order traversal"," — processing nodes layer by layer",[46,3000,3001,3004],{},[19,3002,3003],{},"Finding nodes within k steps"," — BFS naturally explores by distance",[24,3006,3008],{"id":3007},"when-to-choose-dfs","When to Choose DFS",[43,3010,3011,3017,3023,3029],{},[46,3012,3013,3016],{},[19,3014,3015],{},"Detecting cycles"," — DFS back-edges reveal cycles naturally",[46,3018,3019,3022],{},[19,3020,3021],{},"Topological sorting"," — DFS post-order gives reverse topological order",[46,3024,3025,3028],{},[19,3026,3027],{},"Backtracking problems"," (Sudoku, N-Queens) — DFS is the natural recursive approach",[46,3030,3031,3034],{},[19,3032,3033],{},"Memory-constrained scenarios"," — DFS uses O(depth) vs BFS O(branching^depth)",[24,3036,3038],{"id":3037},"summary-table","Summary Table",[731,3040,3041,3053],{},[734,3042,3043],{},[737,3044,3045,3047,3050],{},[740,3046,742],{},[740,3048,3049],{},"BFS",[740,3051,3052],{},"DFS",[750,3054,3055,3066,3076,3087],{},[737,3056,3057,3060,3063],{},[755,3058,3059],{},"Data structure",[755,3061,3062],{},"Queue",[755,3064,3065],{},"Stack",[737,3067,3068,3071,3073],{},[755,3069,3070],{},"Shortest path (unweighted)",[755,3072,782],{},[755,3074,3075],{},"No",[737,3077,3078,3081,3084],{},[755,3079,3080],{},"Memory usage",[755,3082,3083],{},"O(branching^depth)",[755,3085,3086],{},"O(depth)",[737,3088,3089,3091,3094],{},[755,3090,801],{},[755,3092,3093],{},"Shortest path, levels",[755,3095,3096],{},"Cycles, topological sort, backtracking",[850,3098,3099],{},"html pre.shiki code .snl16, html code.shiki .snl16{--shiki-default:#F97583}html pre.shiki code .svObZ, html code.shiki .svObZ{--shiki-default:#B392F0}html pre.shiki code .s95oV, html code.shiki .s95oV{--shiki-default:#E1E4E8}html pre.shiki code .sDLfK, html code.shiki .sDLfK{--shiki-default:#79B8FF}html .default .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html pre.shiki code .sU2Wk, html code.shiki .sU2Wk{--shiki-default:#9ECBFF}",{"title":41,"searchDepth":122,"depth":122,"links":3101},[3102,3103,3104,3109,3110,3111,3112],{"id":2483,"depth":122,"text":2484},{"id":2501,"depth":122,"text":2502},{"id":2519,"depth":122,"text":2520,"children":3105},[3106,3107,3108],{"id":2523,"depth":129,"text":2524},{"id":2664,"depth":129,"text":2665},{"id":2830,"depth":129,"text":2831},{"id":2973,"depth":122,"text":2974},{"id":2983,"depth":122,"text":2984},{"id":3007,"depth":122,"text":3008},{"id":3037,"depth":122,"text":3038},"general","Compare breadth-first and depth-first search to understand when each graph traversal strategy is the right choice.",{"timeComplexity":2464,"spaceComplexity":868},"\u002Flearn\u002Fbfs-vs-dfs",{"title":2472,"description":3114},"learn\u002Fbfs-vs-dfs","L-gh-r7b86fSi5XPRuLv9oQFFArjcmC6L8VZI6NOLjo",{"id":3121,"title":3122,"body":3123,"category":3113,"complexity":862,"date":862,"description":3991,"difficulty":2462,"extension":865,"meta":3992,"navigation":221,"order":85,"path":3993,"publishedAt":870,"relatedAlgorithmId":862,"seo":3994,"stem":3995,"__hash__":3996},"learn\u002Flearn\u002Fbig-o-basics.md","Big-O Basics",{"type":8,"value":3124,"toc":3972},[3125,3128,3131,3135,3138,3142,3146,3149,3153,3156,3160,3163,3167,3170,3174,3177,3179,3183,3225,3228,3396,3399,3482,3485,3742,3745,3878,3882,3951,3955,3969],[11,3126,3122],{"id":3127},"big-o-basics",[15,3129,3130],{},"Big-O notation describes how an algorithm's runtime grows as the input size increases. It's the standard language for comparing algorithm efficiency — it tells you how well an algorithm scales.",[24,3132,3134],{"id":3133},"why-it-matters","Why It Matters",[15,3136,3137],{},"Two algorithms might both solve the same problem, but one might take 1 second for 1,000 items while the other takes 1 hour. Big-O helps you predict this before running the code.",[24,3139,3141],{"id":3140},"common-complexities","Common Complexities",[1024,3143,3145],{"id":3144},"o1-constant-time","O(1) — Constant Time",[15,3147,3148],{},"The runtime doesn't depend on input size. No matter how large the data, it takes the same time.",[1024,3150,3152],{"id":3151},"olog-n-logarithmic","O(log n) — Logarithmic",[15,3154,3155],{},"Each step eliminates half the remaining data. Extremely efficient for large inputs.",[1024,3157,3159],{"id":3158},"on-linear","O(n) — Linear",[15,3161,3162],{},"You look at every element once. Runtime grows directly with input size.",[1024,3164,3166],{"id":3165},"on-log-n-linearithmic","O(n log n) — Linearithmic",[15,3168,3169],{},"The sweet spot for comparison-based sorting. Slightly worse than linear, far better than quadratic.",[1024,3171,3173],{"id":3172},"on2-quadratic","O(n^2) — Quadratic",[15,3175,3176],{},"Nested loops over the same data. Becomes painfully slow around n = 10,000.",[24,3178,2520],{"id":2519},[1024,3180,3182],{"id":3181},"o1-constant","O(1) — Constant",[32,3184,3186],{"className":76,"code":3185,"language":78,"meta":41,"style":41},"def get_first_element(items: list) -> any:\n    \"\"\"Access by index — always one operation regardless of list size.\"\"\"\n    return items[0]\n",[39,3187,3188,3208,3213],{"__ignoreMap":41},[82,3189,3190,3192,3195,3198,3201,3203,3206],{"class":84,"line":85},[82,3191,89],{"class":88},[82,3193,3194],{"class":92}," get_first_element",[82,3196,3197],{"class":96},"(items: ",[82,3199,3200],{"class":100},"list",[82,3202,607],{"class":96},[82,3204,3205],{"class":100},"any",[82,3207,523],{"class":96},[82,3209,3210],{"class":84,"line":122},[82,3211,3212],{"class":125},"    \"\"\"Access by index — always one operation regardless of list size.\"\"\"\n",[82,3214,3215,3217,3220,3222],{"class":84,"line":129},[82,3216,568],{"class":88},[82,3218,3219],{"class":96}," items[",[82,3221,293],{"class":100},[82,3223,3224],{"class":96},"]\n",[1024,3226,3152],{"id":3227},"olog-n-logarithmic-1",[32,3229,3231],{"className":76,"code":3230,"language":78,"meta":41,"style":41},"def binary_search(sorted_numbers: list[int], target: int) -> int:\n    \"\"\"Halve the search space each step.\"\"\"\n    left_bound = 0\n    right_bound = len(sorted_numbers) - 1\n\n    while left_bound \u003C= right_bound:\n        middle_index = (left_bound + right_bound) \u002F\u002F 2\n        if sorted_numbers[middle_index] == target:\n            return middle_index\n        elif sorted_numbers[middle_index] \u003C target:\n            left_bound = middle_index + 1\n        else:\n            right_bound = middle_index - 1\n    return -1\n",[39,3232,3233,3255,3260,3269,3285,3289,3302,3322,3334,3342,3353,3367,3374,3387],{"__ignoreMap":41},[82,3234,3235,3237,3240,3243,3245,3247,3249,3251,3253],{"class":84,"line":85},[82,3236,89],{"class":88},[82,3238,3239],{"class":92}," binary_search",[82,3241,3242],{"class":96},"(sorted_numbers: list[",[82,3244,101],{"class":100},[82,3246,1632],{"class":96},[82,3248,101],{"class":100},[82,3250,607],{"class":96},[82,3252,101],{"class":100},[82,3254,523],{"class":96},[82,3256,3257],{"class":84,"line":122},[82,3258,3259],{"class":125},"    \"\"\"Halve the search space each step.\"\"\"\n",[82,3261,3262,3265,3267],{"class":84,"line":129},[82,3263,3264],{"class":96},"    left_bound ",[82,3266,141],{"class":88},[82,3268,233],{"class":100},[82,3270,3271,3274,3276,3278,3281,3283],{"class":84,"line":135},[82,3272,3273],{"class":96},"    right_bound ",[82,3275,141],{"class":88},[82,3277,1471],{"class":100},[82,3279,3280],{"class":96},"(sorted_numbers) ",[82,3282,186],{"class":88},[82,3284,2260],{"class":100},[82,3286,3287],{"class":84,"line":147},[82,3288,222],{"emptyLinePlaceholder":221},[82,3290,3291,3293,3296,3299],{"class":84,"line":176},[82,3292,270],{"class":88},[82,3294,3295],{"class":96}," left_bound ",[82,3297,3298],{"class":88},"\u003C=",[82,3300,3301],{"class":96}," right_bound:\n",[82,3303,3304,3307,3309,3312,3314,3317,3319],{"class":84,"line":199},[82,3305,3306],{"class":96},"        middle_index ",[82,3308,141],{"class":88},[82,3310,3311],{"class":96}," (left_bound ",[82,3313,406],{"class":88},[82,3315,3316],{"class":96}," right_bound) ",[82,3318,631],{"class":88},[82,3320,3321],{"class":100}," 2\n",[82,3323,3324,3326,3329,3331],{"class":84,"line":218},[82,3325,307],{"class":88},[82,3327,3328],{"class":96}," sorted_numbers[middle_index] ",[82,3330,343],{"class":88},[82,3332,3333],{"class":96}," target:\n",[82,3335,3336,3339],{"class":84,"line":225},[82,3337,3338],{"class":88},"            return",[82,3340,3341],{"class":96}," middle_index\n",[82,3343,3344,3347,3349,3351],{"class":84,"line":236},[82,3345,3346],{"class":88},"        elif",[82,3348,3328],{"class":96},[82,3350,425],{"class":88},[82,3352,3333],{"class":96},[82,3354,3355,3358,3360,3363,3365],{"class":84,"line":247},[82,3356,3357],{"class":96},"            left_bound ",[82,3359,141],{"class":88},[82,3361,3362],{"class":96}," middle_index ",[82,3364,406],{"class":88},[82,3366,2260],{"class":100},[82,3368,3369,3372],{"class":84,"line":262},[82,3370,3371],{"class":88},"        else",[82,3373,523],{"class":96},[82,3375,3376,3379,3381,3383,3385],{"class":84,"line":267},[82,3377,3378],{"class":96},"            right_bound ",[82,3380,141],{"class":88},[82,3382,3362],{"class":96},[82,3384,186],{"class":88},[82,3386,2260],{"class":100},[82,3388,3389,3391,3393],{"class":84,"line":276},[82,3390,568],{"class":88},[82,3392,518],{"class":88},[82,3394,3395],{"class":100},"1\n",[1024,3397,3159],{"id":3398},"on-linear-1",[32,3400,3402],{"className":76,"code":3401,"language":78,"meta":41,"style":41},"def find_maximum(numbers: list[int]) -> int:\n    \"\"\"Single pass through all elements.\"\"\"\n    largest = numbers[0]\n    for current_number in numbers:\n        if current_number > largest:\n            largest = current_number\n    return largest\n",[39,3403,3404,3422,3427,3441,3453,3465,3475],{"__ignoreMap":41},[82,3405,3406,3408,3411,3413,3415,3418,3420],{"class":84,"line":85},[82,3407,89],{"class":88},[82,3409,3410],{"class":92}," find_maximum",[82,3412,1627],{"class":96},[82,3414,101],{"class":100},[82,3416,3417],{"class":96},"]) -> ",[82,3419,101],{"class":100},[82,3421,523],{"class":96},[82,3423,3424],{"class":84,"line":122},[82,3425,3426],{"class":125},"    \"\"\"Single pass through all elements.\"\"\"\n",[82,3428,3429,3432,3434,3437,3439],{"class":84,"line":129},[82,3430,3431],{"class":96},"    largest ",[82,3433,141],{"class":88},[82,3435,3436],{"class":96}," numbers[",[82,3438,293],{"class":100},[82,3440,3224],{"class":96},[82,3442,3443,3445,3448,3450],{"class":84,"line":135},[82,3444,982],{"class":88},[82,3446,3447],{"class":96}," current_number ",[82,3449,369],{"class":88},[82,3451,3452],{"class":96}," numbers:\n",[82,3454,3455,3457,3459,3462],{"class":84,"line":147},[82,3456,307],{"class":88},[82,3458,3447],{"class":96},[82,3460,3461],{"class":88},">",[82,3463,3464],{"class":96}," largest:\n",[82,3466,3467,3470,3472],{"class":84,"line":176},[82,3468,3469],{"class":96},"            largest ",[82,3471,141],{"class":88},[82,3473,3474],{"class":96}," current_number\n",[82,3476,3477,3479],{"class":84,"line":199},[82,3478,568],{"class":88},[82,3480,3481],{"class":96}," largest\n",[1024,3483,3166],{"id":3484},"on-log-n-linearithmic-1",[32,3486,3488],{"className":76,"code":3487,"language":78,"meta":41,"style":41},"def merge_sort(numbers: list[int]) -> list[int]:\n    \"\"\"Divide-and-conquer: split, sort halves, merge.\"\"\"\n    if len(numbers) \u003C= 1:\n        return numbers\n\n    midpoint = len(numbers) \u002F\u002F 2\n    left_half = merge_sort(numbers[:midpoint])\n    right_half = merge_sort(numbers[midpoint:])\n    return merge_halves(left_half, right_half)\n\n\ndef merge_halves(left: list[int], right: list[int]) -> list[int]:\n    \"\"\"Merge two sorted lists into one.\"\"\"\n    merged_result = []\n    left_index = 0\n    right_index = 0\n\n    while left_index \u003C len(left) and right_index \u003C len(right):\n        if left[left_index] \u003C= right[right_index]:\n            merged_result.append(left[left_index])\n            left_index += 1\n        else:\n            merged_result.append(right[right_index])\n            right_index += 1\n\n    merged_result.extend(left[left_index:])\n    merged_result.extend(right[right_index:])\n    return merged_result\n",[39,3489,3490,3508,3513,3528,3535,3539,3554,3564,3574,3581,3585,3589,3612,3617,3626,3635,3644,3648,3675,3687,3692,3701,3707,3712,3721,3725,3730,3735],{"__ignoreMap":41},[82,3491,3492,3494,3497,3499,3501,3504,3506],{"class":84,"line":85},[82,3493,89],{"class":88},[82,3495,3496],{"class":92}," merge_sort",[82,3498,1627],{"class":96},[82,3500,101],{"class":100},[82,3502,3503],{"class":96},"]) -> list[",[82,3505,101],{"class":100},[82,3507,119],{"class":96},[82,3509,3510],{"class":84,"line":122},[82,3511,3512],{"class":125},"    \"\"\"Divide-and-conquer: split, sort halves, merge.\"\"\"\n",[82,3514,3515,3517,3519,3522,3524,3526],{"class":84,"line":129},[82,3516,960],{"class":88},[82,3518,1471],{"class":100},[82,3520,3521],{"class":96},"(numbers) ",[82,3523,3298],{"class":88},[82,3525,1348],{"class":100},[82,3527,523],{"class":96},[82,3529,3530,3532],{"class":84,"line":135},[82,3531,2655],{"class":88},[82,3533,3534],{"class":96}," numbers\n",[82,3536,3537],{"class":84,"line":147},[82,3538,222],{"emptyLinePlaceholder":221},[82,3540,3541,3544,3546,3548,3550,3552],{"class":84,"line":176},[82,3542,3543],{"class":96},"    midpoint ",[82,3545,141],{"class":88},[82,3547,1471],{"class":100},[82,3549,3521],{"class":96},[82,3551,631],{"class":88},[82,3553,3321],{"class":100},[82,3555,3556,3559,3561],{"class":84,"line":199},[82,3557,3558],{"class":96},"    left_half ",[82,3560,141],{"class":88},[82,3562,3563],{"class":96}," merge_sort(numbers[:midpoint])\n",[82,3565,3566,3569,3571],{"class":84,"line":218},[82,3567,3568],{"class":96},"    right_half ",[82,3570,141],{"class":88},[82,3572,3573],{"class":96}," merge_sort(numbers[midpoint:])\n",[82,3575,3576,3578],{"class":84,"line":225},[82,3577,568],{"class":88},[82,3579,3580],{"class":96}," merge_halves(left_half, right_half)\n",[82,3582,3583],{"class":84,"line":236},[82,3584,222],{"emptyLinePlaceholder":221},[82,3586,3587],{"class":84,"line":247},[82,3588,222],{"emptyLinePlaceholder":221},[82,3590,3591,3593,3596,3599,3601,3604,3606,3608,3610],{"class":84,"line":262},[82,3592,89],{"class":88},[82,3594,3595],{"class":92}," merge_halves",[82,3597,3598],{"class":96},"(left: list[",[82,3600,101],{"class":100},[82,3602,3603],{"class":96},"], right: list[",[82,3605,101],{"class":100},[82,3607,3503],{"class":96},[82,3609,101],{"class":100},[82,3611,119],{"class":96},[82,3613,3614],{"class":84,"line":267},[82,3615,3616],{"class":125},"    \"\"\"Merge two sorted lists into one.\"\"\"\n",[82,3618,3619,3622,3624],{"class":84,"line":276},[82,3620,3621],{"class":96},"    merged_result ",[82,3623,141],{"class":88},[82,3625,493],{"class":96},[82,3627,3628,3631,3633],{"class":84,"line":282},[82,3629,3630],{"class":96},"    left_index ",[82,3632,141],{"class":88},[82,3634,233],{"class":100},[82,3636,3637,3640,3642],{"class":84,"line":299},[82,3638,3639],{"class":96},"    right_index ",[82,3641,141],{"class":88},[82,3643,233],{"class":100},[82,3645,3646],{"class":84,"line":304},[82,3647,222],{"emptyLinePlaceholder":221},[82,3649,3650,3652,3655,3657,3659,3662,3665,3668,3670,3672],{"class":84,"line":313},[82,3651,270],{"class":88},[82,3653,3654],{"class":96}," left_index ",[82,3656,425],{"class":88},[82,3658,1471],{"class":100},[82,3660,3661],{"class":96},"(left) ",[82,3663,3664],{"class":88},"and",[82,3666,3667],{"class":96}," right_index ",[82,3669,425],{"class":88},[82,3671,1471],{"class":100},[82,3673,3674],{"class":96},"(right):\n",[82,3676,3677,3679,3682,3684],{"class":84,"line":319},[82,3678,307],{"class":88},[82,3680,3681],{"class":96}," left[left_index] ",[82,3683,3298],{"class":88},[82,3685,3686],{"class":96}," right[right_index]:\n",[82,3688,3689],{"class":84,"line":330},[82,3690,3691],{"class":96},"            merged_result.append(left[left_index])\n",[82,3693,3694,3697,3699],{"class":84,"line":335},[82,3695,3696],{"class":96},"            left_index ",[82,3698,2257],{"class":88},[82,3700,2260],{"class":100},[82,3702,3703,3705],{"class":84,"line":349},[82,3704,3371],{"class":88},[82,3706,523],{"class":96},[82,3708,3709],{"class":84,"line":355},[82,3710,3711],{"class":96},"            merged_result.append(right[right_index])\n",[82,3713,3714,3717,3719],{"class":84,"line":360},[82,3715,3716],{"class":96},"            right_index ",[82,3718,2257],{"class":88},[82,3720,2260],{"class":100},[82,3722,3723],{"class":84,"line":375},[82,3724,222],{"emptyLinePlaceholder":221},[82,3726,3727],{"class":84,"line":384},[82,3728,3729],{"class":96},"    merged_result.extend(left[left_index:])\n",[82,3731,3732],{"class":84,"line":390},[82,3733,3734],{"class":96},"    merged_result.extend(right[right_index:])\n",[82,3736,3737,3739],{"class":84,"line":395},[82,3738,568],{"class":88},[82,3740,3741],{"class":96}," merged_result\n",[1024,3743,3173],{"id":3744},"on2-quadratic-1",[32,3746,3748],{"className":76,"code":3747,"language":78,"meta":41,"style":41},"def bubble_sort(numbers: list[int]) -> list[int]:\n    \"\"\"Nested loops comparing every adjacent pair.\"\"\"\n    array_length = len(numbers)\n    for pass_number in range(array_length):\n        for current_index in range(array_length - 1 - pass_number):\n            if numbers[current_index] > numbers[current_index + 1]:\n                numbers[current_index], numbers[current_index + 1] = (\n                    numbers[current_index + 1], numbers[current_index]\n                )\n    return numbers\n",[39,3749,3750,3767,3772,3784,3798,3821,3839,3855,3867,3872],{"__ignoreMap":41},[82,3751,3752,3754,3757,3759,3761,3763,3765],{"class":84,"line":85},[82,3753,89],{"class":88},[82,3755,3756],{"class":92}," bubble_sort",[82,3758,1627],{"class":96},[82,3760,101],{"class":100},[82,3762,3503],{"class":96},[82,3764,101],{"class":100},[82,3766,119],{"class":96},[82,3768,3769],{"class":84,"line":122},[82,3770,3771],{"class":125},"    \"\"\"Nested loops comparing every adjacent pair.\"\"\"\n",[82,3773,3774,3777,3779,3781],{"class":84,"line":129},[82,3775,3776],{"class":96},"    array_length ",[82,3778,141],{"class":88},[82,3780,1471],{"class":100},[82,3782,3783],{"class":96},"(numbers)\n",[82,3785,3786,3788,3791,3793,3795],{"class":84,"line":135},[82,3787,982],{"class":88},[82,3789,3790],{"class":96}," pass_number ",[82,3792,369],{"class":88},[82,3794,1228],{"class":100},[82,3796,3797],{"class":96},"(array_length):\n",[82,3799,3800,3802,3805,3807,3809,3812,3814,3816,3818],{"class":84,"line":147},[82,3801,363],{"class":88},[82,3803,3804],{"class":96}," current_index ",[82,3806,369],{"class":88},[82,3808,1228],{"class":100},[82,3810,3811],{"class":96},"(array_length ",[82,3813,186],{"class":88},[82,3815,1348],{"class":100},[82,3817,518],{"class":88},[82,3819,3820],{"class":96}," pass_number):\n",[82,3822,3823,3825,3828,3830,3833,3835,3837],{"class":84,"line":176},[82,3824,378],{"class":88},[82,3826,3827],{"class":96}," numbers[current_index] ",[82,3829,3461],{"class":88},[82,3831,3832],{"class":96}," numbers[current_index ",[82,3834,406],{"class":88},[82,3836,1348],{"class":100},[82,3838,119],{"class":96},[82,3840,3841,3844,3846,3848,3850,3852],{"class":84,"line":199},[82,3842,3843],{"class":96},"                numbers[current_index], numbers[current_index ",[82,3845,406],{"class":88},[82,3847,1348],{"class":100},[82,3849,192],{"class":96},[82,3851,141],{"class":88},[82,3853,3854],{"class":96}," (\n",[82,3856,3857,3860,3862,3864],{"class":84,"line":218},[82,3858,3859],{"class":96},"                    numbers[current_index ",[82,3861,406],{"class":88},[82,3863,1348],{"class":100},[82,3865,3866],{"class":96},"], numbers[current_index]\n",[82,3868,3869],{"class":84,"line":225},[82,3870,3871],{"class":96},"                )\n",[82,3873,3874,3876],{"class":84,"line":236},[82,3875,568],{"class":88},[82,3877,3534],{"class":96},[24,3879,3881],{"id":3880},"how-to-identify-complexity","How to Identify Complexity",[731,3883,3884,3894],{},[734,3885,3886],{},[737,3887,3888,3891],{},[740,3889,3890],{},"Pattern in Code",[740,3892,3893],{},"Complexity",[750,3895,3896,3904,3912,3919,3927,3935,3943],{},[737,3897,3898,3901],{},[755,3899,3900],{},"No loops, direct access",[755,3902,3903],{},"O(1)",[737,3905,3906,3909],{},[755,3907,3908],{},"Halving the problem each step",[755,3910,3911],{},"O(log n)",[737,3913,3914,3917],{},[755,3915,3916],{},"Single loop through n items",[755,3918,2077],{},[737,3920,3921,3924],{},[755,3922,3923],{},"Divide in half then process each half",[755,3925,3926],{},"O(n log n)",[737,3928,3929,3932],{},[755,3930,3931],{},"Nested loop over same data",[755,3933,3934],{},"O(n^2)",[737,3936,3937,3940],{},[755,3938,3939],{},"Three nested loops",[755,3941,3942],{},"O(n^3)",[737,3944,3945,3948],{},[755,3946,3947],{},"All subsets or permutations",[755,3949,3950],{},"O(2^n) or O(n!)",[24,3952,3954],{"id":3953},"practical-rules","Practical Rules",[43,3956,3957,3960,3963,3966],{},[46,3958,3959],{},"Drop constants: O(2n) is just O(n)",[46,3961,3962],{},"Drop lower-order terms: O(n^2 + n) is just O(n^2)",[46,3964,3965],{},"Worst case is what Big-O describes by default",[46,3967,3968],{},"Space complexity counts extra memory used (not the input itself)",[850,3970,3971],{},"html pre.shiki code .snl16, html code.shiki .snl16{--shiki-default:#F97583}html pre.shiki code .svObZ, html code.shiki .svObZ{--shiki-default:#B392F0}html pre.shiki code .s95oV, html code.shiki .s95oV{--shiki-default:#E1E4E8}html pre.shiki code .sDLfK, html code.shiki .sDLfK{--shiki-default:#79B8FF}html pre.shiki code .sU2Wk, html code.shiki .sU2Wk{--shiki-default:#9ECBFF}html .default .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}",{"title":41,"searchDepth":122,"depth":122,"links":3973},[3974,3975,3982,3989,3990],{"id":3133,"depth":122,"text":3134},{"id":3140,"depth":122,"text":3141,"children":3976},[3977,3978,3979,3980,3981],{"id":3144,"depth":129,"text":3145},{"id":3151,"depth":129,"text":3152},{"id":3158,"depth":129,"text":3159},{"id":3165,"depth":129,"text":3166},{"id":3172,"depth":129,"text":3173},{"id":2519,"depth":122,"text":2520,"children":3983},[3984,3985,3986,3987,3988],{"id":3181,"depth":129,"text":3182},{"id":3227,"depth":129,"text":3152},{"id":3398,"depth":129,"text":3159},{"id":3484,"depth":129,"text":3166},{"id":3744,"depth":129,"text":3173},{"id":3880,"depth":122,"text":3881},{"id":3953,"depth":122,"text":3954},"Understand time complexity notation and learn to identify common patterns in your code.",{},"\u002Flearn\u002Fbig-o-basics",{"title":3122,"description":3991},"learn\u002Fbig-o-basics","RJBMTJ0Or-lUADxaUG1Gz0JKQ5GRzjuhyHZx06x2gwM",{"id":3998,"title":3999,"body":4000,"category":4440,"complexity":3911,"date":870,"description":4441,"difficulty":2462,"extension":865,"meta":4442,"navigation":221,"order":85,"path":4443,"publishedAt":862,"relatedAlgorithmId":4444,"seo":4445,"stem":4446,"__hash__":4447},"learn\u002Flearn\u002Fbinary-search.md","Binary Search",{"type":8,"value":4001,"toc":4430},[4002,4006,4013,4015,4035,4037,4041,4223,4227,4230,4366,4370,4376,4379,4383,4397,4401,4428],[11,4003,4005],{"id":4004},"understanding-binary-search","Understanding Binary Search",[15,4007,4008,4009,4012],{},"Binary search is one of the most fundamental algorithms in computer science. It efficiently finds a target value within a ",[19,4010,4011],{},"sorted array"," by repeatedly dividing the search interval in half.",[24,4014,893],{"id":892},[895,4016,4017,4020,4023,4026,4029,4032],{},[46,4018,4019],{},"Start with the entire sorted array",[46,4021,4022],{},"Find the middle element",[46,4024,4025],{},"If the middle element equals the target, we're done",[46,4027,4028],{},"If the target is less than the middle, search the left half",[46,4030,4031],{},"If the target is greater than the middle, search the right half",[46,4033,4034],{},"Repeat until the target is found or the range is empty",[24,4036,2520],{"id":2519},[1024,4038,4040],{"id":4039},"standard-binary-search","Standard Binary Search",[32,4042,4044],{"className":76,"code":4043,"language":78,"meta":41,"style":41},"def binary_search(sorted_array: list[int], target: int) -> int:\n    \"\"\"Find target in a sorted array. Returns index or -1 if not found.\"\"\"\n    left_bound = 0\n    right_bound = len(sorted_array) - 1\n\n    while left_bound \u003C= right_bound:\n        middle_index = left_bound + (right_bound - left_bound) \u002F\u002F 2\n        middle_value = sorted_array[middle_index]\n\n        if middle_value == target:\n            return middle_index\n        elif middle_value \u003C target:\n            left_bound = middle_index + 1  # target is in the right half\n        else:\n            right_bound = middle_index - 1  # target is in the left half\n\n    return -1  # target not found\n",[39,4045,4046,4067,4072,4080,4095,4099,4109,4131,4141,4145,4156,4162,4172,4187,4193,4208,4212],{"__ignoreMap":41},[82,4047,4048,4050,4052,4055,4057,4059,4061,4063,4065],{"class":84,"line":85},[82,4049,89],{"class":88},[82,4051,3239],{"class":92},[82,4053,4054],{"class":96},"(sorted_array: list[",[82,4056,101],{"class":100},[82,4058,1632],{"class":96},[82,4060,101],{"class":100},[82,4062,607],{"class":96},[82,4064,101],{"class":100},[82,4066,523],{"class":96},[82,4068,4069],{"class":84,"line":122},[82,4070,4071],{"class":125},"    \"\"\"Find target in a sorted array. Returns index or -1 if not found.\"\"\"\n",[82,4073,4074,4076,4078],{"class":84,"line":129},[82,4075,3264],{"class":96},[82,4077,141],{"class":88},[82,4079,233],{"class":100},[82,4081,4082,4084,4086,4088,4091,4093],{"class":84,"line":135},[82,4083,3273],{"class":96},[82,4085,141],{"class":88},[82,4087,1471],{"class":100},[82,4089,4090],{"class":96},"(sorted_array) ",[82,4092,186],{"class":88},[82,4094,2260],{"class":100},[82,4096,4097],{"class":84,"line":147},[82,4098,222],{"emptyLinePlaceholder":221},[82,4100,4101,4103,4105,4107],{"class":84,"line":176},[82,4102,270],{"class":88},[82,4104,3295],{"class":96},[82,4106,3298],{"class":88},[82,4108,3301],{"class":96},[82,4110,4111,4113,4115,4117,4119,4122,4124,4127,4129],{"class":84,"line":199},[82,4112,3306],{"class":96},[82,4114,141],{"class":88},[82,4116,3295],{"class":96},[82,4118,406],{"class":88},[82,4120,4121],{"class":96}," (right_bound ",[82,4123,186],{"class":88},[82,4125,4126],{"class":96}," left_bound) ",[82,4128,631],{"class":88},[82,4130,3321],{"class":100},[82,4132,4133,4136,4138],{"class":84,"line":218},[82,4134,4135],{"class":96},"        middle_value ",[82,4137,141],{"class":88},[82,4139,4140],{"class":96}," sorted_array[middle_index]\n",[82,4142,4143],{"class":84,"line":225},[82,4144,222],{"emptyLinePlaceholder":221},[82,4146,4147,4149,4152,4154],{"class":84,"line":236},[82,4148,307],{"class":88},[82,4150,4151],{"class":96}," middle_value ",[82,4153,343],{"class":88},[82,4155,3333],{"class":96},[82,4157,4158,4160],{"class":84,"line":247},[82,4159,3338],{"class":88},[82,4161,3341],{"class":96},[82,4163,4164,4166,4168,4170],{"class":84,"line":262},[82,4165,3346],{"class":88},[82,4167,4151],{"class":96},[82,4169,425],{"class":88},[82,4171,3333],{"class":96},[82,4173,4174,4176,4178,4180,4182,4184],{"class":84,"line":267},[82,4175,3357],{"class":96},[82,4177,141],{"class":88},[82,4179,3362],{"class":96},[82,4181,406],{"class":88},[82,4183,1348],{"class":100},[82,4185,4186],{"class":258},"  # target is in the right half\n",[82,4188,4189,4191],{"class":84,"line":276},[82,4190,3371],{"class":88},[82,4192,523],{"class":96},[82,4194,4195,4197,4199,4201,4203,4205],{"class":84,"line":282},[82,4196,3378],{"class":96},[82,4198,141],{"class":88},[82,4200,3362],{"class":96},[82,4202,186],{"class":88},[82,4204,1348],{"class":100},[82,4206,4207],{"class":258},"  # target is in the left half\n",[82,4209,4210],{"class":84,"line":299},[82,4211,222],{"emptyLinePlaceholder":221},[82,4213,4214,4216,4218,4220],{"class":84,"line":304},[82,4215,568],{"class":88},[82,4217,518],{"class":88},[82,4219,189],{"class":100},[82,4221,4222],{"class":258},"  # target not found\n",[1024,4224,4226],{"id":4225},"lower-bound-variation","Lower Bound Variation",[15,4228,4229],{},"Find the first position where a value could be inserted to maintain sorted order:",[32,4231,4233],{"className":76,"code":4232,"language":78,"meta":41,"style":41},"def lower_bound(sorted_array: list[int], target: int) -> int:\n    \"\"\"Find the leftmost position where target could be inserted.\"\"\"\n    left_bound = 0\n    right_bound = len(sorted_array)\n\n    while left_bound \u003C right_bound:\n        middle_index = left_bound + (right_bound - left_bound) \u002F\u002F 2\n\n        if sorted_array[middle_index] \u003C target:\n            left_bound = middle_index + 1\n        else:\n            right_bound = middle_index\n\n    return left_bound\n",[39,4234,4235,4256,4261,4269,4280,4284,4294,4314,4318,4329,4341,4347,4355,4359],{"__ignoreMap":41},[82,4236,4237,4239,4242,4244,4246,4248,4250,4252,4254],{"class":84,"line":85},[82,4238,89],{"class":88},[82,4240,4241],{"class":92}," lower_bound",[82,4243,4054],{"class":96},[82,4245,101],{"class":100},[82,4247,1632],{"class":96},[82,4249,101],{"class":100},[82,4251,607],{"class":96},[82,4253,101],{"class":100},[82,4255,523],{"class":96},[82,4257,4258],{"class":84,"line":122},[82,4259,4260],{"class":125},"    \"\"\"Find the leftmost position where target could be inserted.\"\"\"\n",[82,4262,4263,4265,4267],{"class":84,"line":129},[82,4264,3264],{"class":96},[82,4266,141],{"class":88},[82,4268,233],{"class":100},[82,4270,4271,4273,4275,4277],{"class":84,"line":135},[82,4272,3273],{"class":96},[82,4274,141],{"class":88},[82,4276,1471],{"class":100},[82,4278,4279],{"class":96},"(sorted_array)\n",[82,4281,4282],{"class":84,"line":147},[82,4283,222],{"emptyLinePlaceholder":221},[82,4285,4286,4288,4290,4292],{"class":84,"line":176},[82,4287,270],{"class":88},[82,4289,3295],{"class":96},[82,4291,425],{"class":88},[82,4293,3301],{"class":96},[82,4295,4296,4298,4300,4302,4304,4306,4308,4310,4312],{"class":84,"line":199},[82,4297,3306],{"class":96},[82,4299,141],{"class":88},[82,4301,3295],{"class":96},[82,4303,406],{"class":88},[82,4305,4121],{"class":96},[82,4307,186],{"class":88},[82,4309,4126],{"class":96},[82,4311,631],{"class":88},[82,4313,3321],{"class":100},[82,4315,4316],{"class":84,"line":218},[82,4317,222],{"emptyLinePlaceholder":221},[82,4319,4320,4322,4325,4327],{"class":84,"line":225},[82,4321,307],{"class":88},[82,4323,4324],{"class":96}," sorted_array[middle_index] ",[82,4326,425],{"class":88},[82,4328,3333],{"class":96},[82,4330,4331,4333,4335,4337,4339],{"class":84,"line":236},[82,4332,3357],{"class":96},[82,4334,141],{"class":88},[82,4336,3362],{"class":96},[82,4338,406],{"class":88},[82,4340,2260],{"class":100},[82,4342,4343,4345],{"class":84,"line":247},[82,4344,3371],{"class":88},[82,4346,523],{"class":96},[82,4348,4349,4351,4353],{"class":84,"line":262},[82,4350,3378],{"class":96},[82,4352,141],{"class":88},[82,4354,3341],{"class":96},[82,4356,4357],{"class":84,"line":267},[82,4358,222],{"emptyLinePlaceholder":221},[82,4360,4361,4363],{"class":84,"line":276},[82,4362,568],{"class":88},[82,4364,4365],{"class":96}," left_bound\n",[24,4367,4369],{"id":4368},"time-complexity","Time Complexity",[15,4371,4372,4373,4375],{},"Binary search runs in ",[19,4374,3911],{}," time because each comparison eliminates half of the remaining elements.",[15,4377,4378],{},"For an array of 1,000,000 elements, binary search needs at most ~20 comparisons.",[24,4380,4382],{"id":4381},"when-to-use","When to Use",[43,4384,4385,4391,4394],{},[46,4386,4387,4388],{},"The array must be ",[19,4389,4390],{},"sorted",[46,4392,4393],{},"You need to find a specific element",[46,4395,4396],{},"You want better than O(n) performance",[24,4398,4400],{"id":4399},"common-pitfalls","Common Pitfalls",[43,4402,4403,4406,4417],{},[46,4404,4405],{},"Forgetting the array needs to be sorted first",[46,4407,4408,4409,4412,4413,4416],{},"Integer overflow when calculating ",[39,4410,4411],{},"middle = (left + right) \u002F 2"," — use ",[39,4414,4415],{},"middle = left + (right - left) \u002F\u002F 2"," instead",[46,4418,4419,4420,4423,4424,4427],{},"Off-by-one errors: use ",[39,4421,4422],{},"left_bound \u003C= right_bound"," for finding exact values, ",[39,4425,4426],{},"left_bound \u003C right_bound"," for bounds",[850,4429,852],{},{"title":41,"searchDepth":122,"depth":122,"links":4431},[4432,4433,4437,4438,4439],{"id":892,"depth":122,"text":893},{"id":2519,"depth":122,"text":2520,"children":4434},[4435,4436],{"id":4039,"depth":129,"text":4040},{"id":4225,"depth":129,"text":4226},{"id":4368,"depth":122,"text":4369},{"id":4381,"depth":122,"text":4382},{"id":4399,"depth":122,"text":4400},"searching","Learn how binary search efficiently finds elements in sorted arrays using divide-and-conquer.",{},"\u002Flearn\u002Fbinary-search","binary",{"title":3999,"description":4441},"learn\u002Fbinary-search","DwvIU-wluJP7lGdslDUhLMnTfmHTS_XXI7bIKY-8EIc",{"id":4449,"title":4450,"body":4451,"category":5751,"complexity":862,"date":862,"description":5752,"difficulty":864,"extension":865,"meta":5753,"navigation":221,"order":135,"path":5755,"publishedAt":2079,"relatedAlgorithmId":5756,"seo":5757,"stem":5758,"__hash__":5759},"learn\u002Flearn\u002Fbinary-search-tree.md","Binary Search Tree",{"type":8,"value":4452,"toc":5734},[4453,4456,4459,4463,4470,4490,4493,4497,4559,4561,4564,4581,4585,4593,4597,4600,4620,4624,4630,4636,4646,4648,5441,5443,5448,5464,5468,5471,5475,5531,5534,5554,5558,5619,5623,5655,5659,5679,5681,5731],[11,4454,4450],{"id":4455},"binary-search-tree",[15,4457,4458],{},"A Binary Search Tree (BST) is a hierarchical data structure where each node has at most two children, and for every node: all values in its left subtree are smaller, and all values in its right subtree are larger. This ordering property enables efficient searching, insertion, and deletion in O(log n) average time — similar to binary search on a sorted array, but with the flexibility to insert and delete without shifting elements.",[24,4460,4462],{"id":4461},"the-bst-property","The BST Property",[15,4464,4465,4466,4469],{},"For every node with value ",[39,4467,4468],{},"v",":",[43,4471,4472,4482],{},[46,4473,4474,4475,4478,4479],{},"All nodes in the ",[19,4476,4477],{},"left subtree"," have values ",[19,4480,4481],{},"\u003C v",[46,4483,4474,4484,4478,4487],{},[19,4485,4486],{},"right subtree",[19,4488,4489],{},"> v",[15,4491,4492],{},"This invariant holds recursively for every subtree in the tree.",[24,4494,4496],{"id":4495},"core-operations","Core Operations",[731,4498,4499,4512],{},[734,4500,4501],{},[737,4502,4503,4506,4509],{},[740,4504,4505],{},"Operation",[740,4507,4508],{},"Average",[740,4510,4511],{},"Worst (unbalanced)",[750,4513,4514,4523,4532,4541,4550],{},[737,4515,4516,4519,4521],{},[755,4517,4518],{},"Search",[755,4520,3911],{},[755,4522,2077],{},[737,4524,4525,4528,4530],{},[755,4526,4527],{},"Insert",[755,4529,3911],{},[755,4531,2077],{},[737,4533,4534,4537,4539],{},[755,4535,4536],{},"Delete",[755,4538,3911],{},[755,4540,2077],{},[737,4542,4543,4546,4548],{},[755,4544,4545],{},"Min\u002FMax",[755,4547,3911],{},[755,4549,2077],{},[737,4551,4552,4555,4557],{},[755,4553,4554],{},"In-order traversal",[755,4556,2077],{},[755,4558,2077],{},[24,4560,893],{"id":892},[1024,4562,4518],{"id":4563},"search",[895,4565,4566,4569,4572,4575,4578],{},[46,4567,4568],{},"Start at the root",[46,4570,4571],{},"If the target equals the current node, return it",[46,4573,4574],{},"If the target is less, go left",[46,4576,4577],{},"If the target is greater, go right",[46,4579,4580],{},"If you reach a null node, the target doesn't exist",[1024,4582,4584],{"id":4583},"insertion","Insertion",[895,4586,4587,4590],{},[46,4588,4589],{},"Search for where the value should go",[46,4591,4592],{},"When you reach a null position, create a new node there",[1024,4594,4596],{"id":4595},"deletion","Deletion",[15,4598,4599],{},"Three cases:",[895,4601,4602,4608,4614],{},[46,4603,4604,4607],{},[19,4605,4606],{},"Leaf node",": Simply remove it",[46,4609,4610,4613],{},[19,4611,4612],{},"One child",": Replace the node with its child",[46,4615,4616,4619],{},[19,4617,4618],{},"Two children",": Find the in-order successor (smallest in right subtree), copy its value, then delete the successor",[24,4621,4623],{"id":4622},"step-by-step-example","Step-by-Step Example",[15,4625,4626,4627,4469],{},"Insert ",[39,4628,4629],{},"[8, 3, 10, 1, 6, 14, 4, 7]",[32,4631,4634],{"className":4632,"code":4633,"language":37},[35],"        8\n       \u002F \\\n      3   10\n     \u002F \\    \\\n    1   6   14\n       \u002F \\\n      4   7\n",[39,4635,4633],{"__ignoreMap":41},[15,4637,4638,4641,4642,4645],{},[19,4639,4640],{},"Search for 6",": 8 → left → 3 → right → 6 ✓ (3 comparisons)\n",[19,4643,4644],{},"Search for 5",": 8 → left → 3 → right → 6 → left → 4 → right → null ✗ (not found)",[24,4647,70],{"id":69},[32,4649,4651],{"className":76,"code":4650,"language":78,"meta":41,"style":41},"class TreeNode:\n    \"\"\"A single node in the binary search tree.\"\"\"\n\n    def __init__(self, value: int):\n        self.value = value\n        self.left = None\n        self.right = None\n\n\nclass BinarySearchTree:\n    \"\"\"Binary Search Tree with search, insert, and delete operations.\"\"\"\n\n    def __init__(self):\n        self.root = None\n\n    def insert(self, value: int) -> None:\n        \"\"\"Insert a value into the BST.\"\"\"\n        self.root = self._insert_recursive(self.root, value)\n\n    def _insert_recursive(self, node, value: int):\n        if node is None:\n            return TreeNode(value)\n        if value \u003C node.value:\n            node.left = self._insert_recursive(node.left, value)\n        elif value > node.value:\n            node.right = self._insert_recursive(node.right, value)\n        return node\n\n    def search(self, value: int) -> bool:\n        \"\"\"Check if a value exists in the BST.\"\"\"\n        current = self.root\n        while current is not None:\n            if value == current.value:\n                return True\n            elif value \u003C current.value:\n                current = current.left\n            else:\n                current = current.right\n        return False\n\n    def delete(self, value: int) -> None:\n        \"\"\"Remove a value from the BST.\"\"\"\n        self.root = self._delete_recursive(self.root, value)\n\n    def _delete_recursive(self, node, value: int):\n        if node is None:\n            return None\n\n        if value \u003C node.value:\n            node.left = self._delete_recursive(node.left, value)\n        elif value > node.value:\n            node.right = self._delete_recursive(node.right, value)\n        else:\n            # Node found — handle three cases\n            if node.left is None:\n                return node.right\n            if node.right is None:\n                return node.left\n\n            # Two children: find in-order successor\n            successor = self._find_min(node.right)\n            node.value = successor.value\n            node.right = self._delete_recursive(node.right, successor.value)\n\n        return node\n\n    def _find_min(self, node):\n        \"\"\"Find the node with the minimum value in a subtree.\"\"\"\n        current = node\n        while current.left is not None:\n            current = current.left\n        return current\n\n    def inorder_traversal(self) -> list[int]:\n        \"\"\"Return all values in sorted order.\"\"\"\n        result = []\n        self._inorder(self.root, result)\n        return result\n\n    def _inorder(self, node, result: list) -> None:\n        if node is not None:\n            self._inorder(node.left, result)\n            result.append(node.value)\n            self._inorder(node.right, result)\n",[39,4652,4653,4662,4667,4671,4684,4696,4708,4719,4723,4727,4736,4741,4745,4754,4765,4769,4786,4791,4810,4814,4828,4842,4849,4861,4873,4883,4895,4902,4906,4924,4929,4941,4957,4968,4975,4986,4996,5003,5012,5018,5022,5039,5044,5061,5065,5078,5090,5096,5100,5110,5121,5131,5142,5149,5155,5169,5177,5191,5199,5204,5210,5223,5234,5246,5251,5258,5263,5274,5280,5289,5305,5315,5323,5328,5343,5349,5359,5372,5379,5384,5403,5418,5427,5433],{"__ignoreMap":41},[82,4654,4655,4657,4660],{"class":84,"line":85},[82,4656,2534],{"class":88},[82,4658,4659],{"class":92}," TreeNode",[82,4661,523],{"class":96},[82,4663,4664],{"class":84,"line":122},[82,4665,4666],{"class":125},"    \"\"\"A single node in the binary search tree.\"\"\"\n",[82,4668,4669],{"class":84,"line":129},[82,4670,222],{"emptyLinePlaceholder":221},[82,4672,4673,4675,4677,4680,4682],{"class":84,"line":135},[82,4674,1176],{"class":88},[82,4676,2546],{"class":100},[82,4678,4679],{"class":96},"(self, value: ",[82,4681,101],{"class":100},[82,4683,2554],{"class":96},[82,4685,4686,4688,4691,4693],{"class":84,"line":147},[82,4687,2559],{"class":100},[82,4689,4690],{"class":96},".value ",[82,4692,141],{"class":88},[82,4694,4695],{"class":96}," value\n",[82,4697,4698,4700,4703,4705],{"class":84,"line":176},[82,4699,2559],{"class":100},[82,4701,4702],{"class":96},".left ",[82,4704,141],{"class":88},[82,4706,4707],{"class":100}," None\n",[82,4709,4710,4712,4715,4717],{"class":84,"line":199},[82,4711,2559],{"class":100},[82,4713,4714],{"class":96},".right ",[82,4716,141],{"class":88},[82,4718,4707],{"class":100},[82,4720,4721],{"class":84,"line":218},[82,4722,222],{"emptyLinePlaceholder":221},[82,4724,4725],{"class":84,"line":225},[82,4726,222],{"emptyLinePlaceholder":221},[82,4728,4729,4731,4734],{"class":84,"line":236},[82,4730,2534],{"class":88},[82,4732,4733],{"class":92}," BinarySearchTree",[82,4735,523],{"class":96},[82,4737,4738],{"class":84,"line":247},[82,4739,4740],{"class":125},"    \"\"\"Binary Search Tree with search, insert, and delete operations.\"\"\"\n",[82,4742,4743],{"class":84,"line":262},[82,4744,222],{"emptyLinePlaceholder":221},[82,4746,4747,4749,4751],{"class":84,"line":267},[82,4748,1176],{"class":88},[82,4750,2546],{"class":100},[82,4752,4753],{"class":96},"(self):\n",[82,4755,4756,4758,4761,4763],{"class":84,"line":276},[82,4757,2559],{"class":100},[82,4759,4760],{"class":96},".root ",[82,4762,141],{"class":88},[82,4764,4707],{"class":100},[82,4766,4767],{"class":84,"line":282},[82,4768,222],{"emptyLinePlaceholder":221},[82,4770,4771,4773,4776,4778,4780,4782,4784],{"class":84,"line":299},[82,4772,1176],{"class":88},[82,4774,4775],{"class":92}," insert",[82,4777,4679],{"class":96},[82,4779,101],{"class":100},[82,4781,607],{"class":96},[82,4783,1188],{"class":100},[82,4785,523],{"class":96},[82,4787,4788],{"class":84,"line":304},[82,4789,4790],{"class":125},"        \"\"\"Insert a value into the BST.\"\"\"\n",[82,4792,4793,4795,4797,4799,4801,4804,4807],{"class":84,"line":313},[82,4794,2559],{"class":100},[82,4796,4760],{"class":96},[82,4798,141],{"class":88},[82,4800,2658],{"class":100},[82,4802,4803],{"class":96},"._insert_recursive(",[82,4805,4806],{"class":100},"self",[82,4808,4809],{"class":96},".root, value)\n",[82,4811,4812],{"class":84,"line":319},[82,4813,222],{"emptyLinePlaceholder":221},[82,4815,4816,4818,4821,4824,4826],{"class":84,"line":330},[82,4817,1176],{"class":88},[82,4819,4820],{"class":92}," _insert_recursive",[82,4822,4823],{"class":96},"(self, node, value: ",[82,4825,101],{"class":100},[82,4827,2554],{"class":96},[82,4829,4830,4832,4834,4837,4840],{"class":84,"line":335},[82,4831,307],{"class":88},[82,4833,512],{"class":96},[82,4835,4836],{"class":88},"is",[82,4838,4839],{"class":100}," None",[82,4841,523],{"class":96},[82,4843,4844,4846],{"class":84,"line":349},[82,4845,3338],{"class":88},[82,4847,4848],{"class":96}," TreeNode(value)\n",[82,4850,4851,4853,4856,4858],{"class":84,"line":355},[82,4852,307],{"class":88},[82,4854,4855],{"class":96}," value ",[82,4857,425],{"class":88},[82,4859,4860],{"class":96}," node.value:\n",[82,4862,4863,4866,4868,4870],{"class":84,"line":360},[82,4864,4865],{"class":96},"            node.left ",[82,4867,141],{"class":88},[82,4869,2658],{"class":100},[82,4871,4872],{"class":96},"._insert_recursive(node.left, value)\n",[82,4874,4875,4877,4879,4881],{"class":84,"line":375},[82,4876,3346],{"class":88},[82,4878,4855],{"class":96},[82,4880,3461],{"class":88},[82,4882,4860],{"class":96},[82,4884,4885,4888,4890,4892],{"class":84,"line":384},[82,4886,4887],{"class":96},"            node.right ",[82,4889,141],{"class":88},[82,4891,2658],{"class":100},[82,4893,4894],{"class":96},"._insert_recursive(node.right, value)\n",[82,4896,4897,4899],{"class":84,"line":390},[82,4898,2655],{"class":88},[82,4900,4901],{"class":96}," node\n",[82,4903,4904],{"class":84,"line":395},[82,4905,222],{"emptyLinePlaceholder":221},[82,4907,4908,4910,4913,4915,4917,4919,4922],{"class":84,"line":412},[82,4909,1176],{"class":88},[82,4911,4912],{"class":92}," search",[82,4914,4679],{"class":96},[82,4916,101],{"class":100},[82,4918,607],{"class":96},[82,4920,4921],{"class":100},"bool",[82,4923,523],{"class":96},[82,4925,4926],{"class":84,"line":417},[82,4927,4928],{"class":125},"        \"\"\"Check if a value exists in the BST.\"\"\"\n",[82,4930,4931,4934,4936,4938],{"class":84,"line":431},[82,4932,4933],{"class":96},"        current ",[82,4935,141],{"class":88},[82,4937,2658],{"class":100},[82,4939,4940],{"class":96},".root\n",[82,4942,4943,4946,4949,4951,4953,4955],{"class":84,"line":442},[82,4944,4945],{"class":88},"        while",[82,4947,4948],{"class":96}," current ",[82,4950,4836],{"class":88},[82,4952,2300],{"class":88},[82,4954,4839],{"class":100},[82,4956,523],{"class":96},[82,4958,4959,4961,4963,4965],{"class":84,"line":453},[82,4960,378],{"class":88},[82,4962,4855],{"class":96},[82,4964,343],{"class":88},[82,4966,4967],{"class":96}," current.value:\n",[82,4969,4970,4973],{"class":84,"line":468},[82,4971,4972],{"class":88},"                return",[82,4974,327],{"class":100},[82,4976,4977,4980,4982,4984],{"class":84,"line":474},[82,4978,4979],{"class":88},"            elif",[82,4981,4855],{"class":96},[82,4983,425],{"class":88},[82,4985,4967],{"class":96},[82,4987,4988,4991,4993],{"class":84,"line":479},[82,4989,4990],{"class":96},"                current ",[82,4992,141],{"class":88},[82,4994,4995],{"class":96}," current.left\n",[82,4997,4998,5001],{"class":84,"line":485},[82,4999,5000],{"class":88},"            else",[82,5002,523],{"class":96},[82,5004,5005,5007,5009],{"class":84,"line":496},[82,5006,4990],{"class":96},[82,5008,141],{"class":88},[82,5010,5011],{"class":96}," current.right\n",[82,5013,5014,5016],{"class":84,"line":507},[82,5015,2655],{"class":88},[82,5017,1592],{"class":100},[82,5019,5020],{"class":84,"line":526},[82,5021,222],{"emptyLinePlaceholder":221},[82,5023,5024,5026,5029,5031,5033,5035,5037],{"class":84,"line":532},[82,5025,1176],{"class":88},[82,5027,5028],{"class":92}," delete",[82,5030,4679],{"class":96},[82,5032,101],{"class":100},[82,5034,607],{"class":96},[82,5036,1188],{"class":100},[82,5038,523],{"class":96},[82,5040,5041],{"class":84,"line":543},[82,5042,5043],{"class":125},"        \"\"\"Remove a value from the BST.\"\"\"\n",[82,5045,5046,5048,5050,5052,5054,5057,5059],{"class":84,"line":549},[82,5047,2559],{"class":100},[82,5049,4760],{"class":96},[82,5051,141],{"class":88},[82,5053,2658],{"class":100},[82,5055,5056],{"class":96},"._delete_recursive(",[82,5058,4806],{"class":100},[82,5060,4809],{"class":96},[82,5062,5063],{"class":84,"line":554},[82,5064,222],{"emptyLinePlaceholder":221},[82,5066,5067,5069,5072,5074,5076],{"class":84,"line":565},[82,5068,1176],{"class":88},[82,5070,5071],{"class":92}," _delete_recursive",[82,5073,4823],{"class":96},[82,5075,101],{"class":100},[82,5077,2554],{"class":96},[82,5079,5080,5082,5084,5086,5088],{"class":84,"line":574},[82,5081,307],{"class":88},[82,5083,512],{"class":96},[82,5085,4836],{"class":88},[82,5087,4839],{"class":100},[82,5089,523],{"class":96},[82,5091,5092,5094],{"class":84,"line":579},[82,5093,3338],{"class":88},[82,5095,4707],{"class":100},[82,5097,5098],{"class":84,"line":584},[82,5099,222],{"emptyLinePlaceholder":221},[82,5101,5102,5104,5106,5108],{"class":84,"line":614},[82,5103,307],{"class":88},[82,5105,4855],{"class":96},[82,5107,425],{"class":88},[82,5109,4860],{"class":96},[82,5111,5112,5114,5116,5118],{"class":84,"line":620},[82,5113,4865],{"class":96},[82,5115,141],{"class":88},[82,5117,2658],{"class":100},[82,5119,5120],{"class":96},"._delete_recursive(node.left, value)\n",[82,5122,5123,5125,5127,5129],{"class":84,"line":643},[82,5124,3346],{"class":88},[82,5126,4855],{"class":96},[82,5128,3461],{"class":88},[82,5130,4860],{"class":96},[82,5132,5133,5135,5137,5139],{"class":84,"line":663},[82,5134,4887],{"class":96},[82,5136,141],{"class":88},[82,5138,2658],{"class":100},[82,5140,5141],{"class":96},"._delete_recursive(node.right, value)\n",[82,5143,5145,5147],{"class":84,"line":5144},53,[82,5146,3371],{"class":88},[82,5148,523],{"class":96},[82,5150,5152],{"class":84,"line":5151},54,[82,5153,5154],{"class":258},"            # Node found — handle three cases\n",[82,5156,5158,5160,5163,5165,5167],{"class":84,"line":5157},55,[82,5159,378],{"class":88},[82,5161,5162],{"class":96}," node.left ",[82,5164,4836],{"class":88},[82,5166,4839],{"class":100},[82,5168,523],{"class":96},[82,5170,5172,5174],{"class":84,"line":5171},56,[82,5173,4972],{"class":88},[82,5175,5176],{"class":96}," node.right\n",[82,5178,5180,5182,5185,5187,5189],{"class":84,"line":5179},57,[82,5181,378],{"class":88},[82,5183,5184],{"class":96}," node.right ",[82,5186,4836],{"class":88},[82,5188,4839],{"class":100},[82,5190,523],{"class":96},[82,5192,5194,5196],{"class":84,"line":5193},58,[82,5195,4972],{"class":88},[82,5197,5198],{"class":96}," node.left\n",[82,5200,5202],{"class":84,"line":5201},59,[82,5203,222],{"emptyLinePlaceholder":221},[82,5205,5207],{"class":84,"line":5206},60,[82,5208,5209],{"class":258},"            # Two children: find in-order successor\n",[82,5211,5213,5216,5218,5220],{"class":84,"line":5212},61,[82,5214,5215],{"class":96},"            successor ",[82,5217,141],{"class":88},[82,5219,2658],{"class":100},[82,5221,5222],{"class":96},"._find_min(node.right)\n",[82,5224,5226,5229,5231],{"class":84,"line":5225},62,[82,5227,5228],{"class":96},"            node.value ",[82,5230,141],{"class":88},[82,5232,5233],{"class":96}," successor.value\n",[82,5235,5237,5239,5241,5243],{"class":84,"line":5236},63,[82,5238,4887],{"class":96},[82,5240,141],{"class":88},[82,5242,2658],{"class":100},[82,5244,5245],{"class":96},"._delete_recursive(node.right, successor.value)\n",[82,5247,5249],{"class":84,"line":5248},64,[82,5250,222],{"emptyLinePlaceholder":221},[82,5252,5254,5256],{"class":84,"line":5253},65,[82,5255,2655],{"class":88},[82,5257,4901],{"class":96},[82,5259,5261],{"class":84,"line":5260},66,[82,5262,222],{"emptyLinePlaceholder":221},[82,5264,5266,5268,5271],{"class":84,"line":5265},67,[82,5267,1176],{"class":88},[82,5269,5270],{"class":92}," _find_min",[82,5272,5273],{"class":96},"(self, node):\n",[82,5275,5277],{"class":84,"line":5276},68,[82,5278,5279],{"class":125},"        \"\"\"Find the node with the minimum value in a subtree.\"\"\"\n",[82,5281,5283,5285,5287],{"class":84,"line":5282},69,[82,5284,4933],{"class":96},[82,5286,141],{"class":88},[82,5288,4901],{"class":96},[82,5290,5292,5294,5297,5299,5301,5303],{"class":84,"line":5291},70,[82,5293,4945],{"class":88},[82,5295,5296],{"class":96}," current.left ",[82,5298,4836],{"class":88},[82,5300,2300],{"class":88},[82,5302,4839],{"class":100},[82,5304,523],{"class":96},[82,5306,5308,5311,5313],{"class":84,"line":5307},71,[82,5309,5310],{"class":96},"            current ",[82,5312,141],{"class":88},[82,5314,4995],{"class":96},[82,5316,5318,5320],{"class":84,"line":5317},72,[82,5319,2655],{"class":88},[82,5321,5322],{"class":96}," current\n",[82,5324,5326],{"class":84,"line":5325},73,[82,5327,222],{"emptyLinePlaceholder":221},[82,5329,5331,5333,5336,5339,5341],{"class":84,"line":5330},74,[82,5332,1176],{"class":88},[82,5334,5335],{"class":92}," inorder_traversal",[82,5337,5338],{"class":96},"(self) -> list[",[82,5340,101],{"class":100},[82,5342,119],{"class":96},[82,5344,5346],{"class":84,"line":5345},75,[82,5347,5348],{"class":125},"        \"\"\"Return all values in sorted order.\"\"\"\n",[82,5350,5352,5355,5357],{"class":84,"line":5351},76,[82,5353,5354],{"class":96},"        result ",[82,5356,141],{"class":88},[82,5358,493],{"class":96},[82,5360,5362,5364,5367,5369],{"class":84,"line":5361},77,[82,5363,2559],{"class":100},[82,5365,5366],{"class":96},"._inorder(",[82,5368,4806],{"class":100},[82,5370,5371],{"class":96},".root, result)\n",[82,5373,5375,5377],{"class":84,"line":5374},78,[82,5376,2655],{"class":88},[82,5378,1608],{"class":96},[82,5380,5382],{"class":84,"line":5381},79,[82,5383,222],{"emptyLinePlaceholder":221},[82,5385,5387,5389,5392,5395,5397,5399,5401],{"class":84,"line":5386},80,[82,5388,1176],{"class":88},[82,5390,5391],{"class":92}," _inorder",[82,5393,5394],{"class":96},"(self, node, result: ",[82,5396,3200],{"class":100},[82,5398,607],{"class":96},[82,5400,1188],{"class":100},[82,5402,523],{"class":96},[82,5404,5406,5408,5410,5412,5414,5416],{"class":84,"line":5405},81,[82,5407,307],{"class":88},[82,5409,512],{"class":96},[82,5411,4836],{"class":88},[82,5413,2300],{"class":88},[82,5415,4839],{"class":100},[82,5417,523],{"class":96},[82,5419,5421,5424],{"class":84,"line":5420},82,[82,5422,5423],{"class":100},"            self",[82,5425,5426],{"class":96},"._inorder(node.left, result)\n",[82,5428,5430],{"class":84,"line":5429},83,[82,5431,5432],{"class":96},"            result.append(node.value)\n",[82,5434,5436,5438],{"class":84,"line":5435},84,[82,5437,5423],{"class":100},[82,5439,5440],{"class":96},"._inorder(node.right, result)\n",[24,5442,1816],{"id":1815},[15,5444,5445],{},[19,5446,5447],{},"Time Complexity: O(log n) average, O(n) worst case",[43,5449,5450,5457],{},[46,5451,5452,5453,5456],{},"In a ",[19,5454,5455],{},"balanced"," BST, the height is O(log n), so search\u002Finsert\u002Fdelete traverse at most log n levels.",[46,5458,5459,5460,5463],{},"In the ",[19,5461,5462],{},"worst case"," (e.g., inserting sorted data: 1, 2, 3, 4, 5), the tree degenerates into a linked list with height n.",[15,5465,5466],{},[19,5467,1846],{},[15,5469,5470],{},"The tree stores n nodes, each with a value and two pointers. Recursive operations use O(h) stack space where h is the height.",[24,5472,5474],{"id":5473},"balanced-vs-unbalanced","Balanced vs. Unbalanced",[731,5476,5477,5493],{},[734,5478,5479],{},[737,5480,5481,5484,5487,5490],{},[740,5482,5483],{},"Input",[740,5485,5486],{},"Tree shape",[740,5488,5489],{},"Height",[740,5491,5492],{},"Operations",[750,5494,5495,5507,5519],{},[737,5496,5497,5500,5503,5505],{},[755,5498,5499],{},"Random",[755,5501,5502],{},"Roughly balanced",[755,5504,3911],{},[755,5506,3911],{},[737,5508,5509,5512,5515,5517],{},[755,5510,5511],{},"Sorted",[755,5513,5514],{},"Linked list",[755,5516,2077],{},[755,5518,2077],{},[737,5520,5521,5524,5527,5529],{},[755,5522,5523],{},"Alternating",[755,5525,5526],{},"Nearly balanced",[755,5528,3911],{},[755,5530,3911],{},[15,5532,5533],{},"To guarantee O(log n) performance, use self-balancing variants:",[43,5535,5536,5542,5548],{},[46,5537,5538,5541],{},[19,5539,5540],{},"AVL Tree",": Strict balance (height difference ≤ 1)",[46,5543,5544,5547],{},[19,5545,5546],{},"Red-Black Tree",": Relaxed balance (used in most standard libraries)",[46,5549,5550,5553],{},[19,5551,5552],{},"B-Tree",": Used in databases and filesystems",[24,5555,5557],{"id":5556},"traversal-orders","Traversal Orders",[731,5559,5560,5573],{},[734,5561,5562],{},[737,5563,5564,5567,5570],{},[740,5565,5566],{},"Order",[740,5568,5569],{},"Sequence",[740,5571,5572],{},"Use case",[750,5574,5575,5586,5597,5608],{},[737,5576,5577,5580,5583],{},[755,5578,5579],{},"In-order",[755,5581,5582],{},"Left → Root → Right",[755,5584,5585],{},"Sorted output",[737,5587,5588,5591,5594],{},[755,5589,5590],{},"Pre-order",[755,5592,5593],{},"Root → Left → Right",[755,5595,5596],{},"Copy\u002Fserialize tree",[737,5598,5599,5602,5605],{},[755,5600,5601],{},"Post-order",[755,5603,5604],{},"Left → Right → Root",[755,5606,5607],{},"Delete tree, evaluate expressions",[737,5609,5610,5613,5616],{},[755,5611,5612],{},"Level-order",[755,5614,5615],{},"BFS by level",[755,5617,5618],{},"Print tree layer by layer",[24,5620,5622],{"id":5621},"when-to-use-bsts","When to Use BSTs",[43,5624,5625,5631,5637,5643,5649],{},[46,5626,5627,5630],{},[19,5628,5629],{},"Dynamic sorted data",": Need to insert, delete, and search while maintaining order.",[46,5632,5633,5636],{},[19,5634,5635],{},"Range queries",": Find all elements between two values efficiently.",[46,5638,5639,5642],{},[19,5640,5641],{},"Ordered iteration",": In-order traversal gives sorted output.",[46,5644,5645,5648],{},[19,5646,5647],{},"Floor\u002FCeiling queries",": Find the largest value ≤ x or smallest value ≥ x.",[46,5650,5651,5654],{},[19,5652,5653],{},"Symbol tables with ordering",": When you need both fast lookup and sorted access.",[24,5656,5658],{"id":5657},"when-to-avoid-bsts","When to Avoid BSTs",[43,5660,5661,5667,5673],{},[46,5662,5663,5666],{},[19,5664,5665],{},"Unordered lookups only",": Hash maps are faster (O(1) vs O(log n)) if you don't need ordering.",[46,5668,5669,5672],{},[19,5670,5671],{},"Static data",": A sorted array with binary search is simpler and uses less memory.",[46,5674,5675,5678],{},[19,5676,5677],{},"Guaranteed worst-case",": Use a self-balancing variant rather than a plain BST.",[24,5680,1998],{"id":1997},[731,5682,5683,5691],{},[734,5684,5685],{},[737,5686,5687,5689],{},[740,5688,742],{},[740,5690,2009],{},[750,5692,5693,5700,5707,5715,5723],{},[737,5694,5695,5698],{},[755,5696,5697],{},"Average search",[755,5699,3911],{},[737,5701,5702,5705],{},[755,5703,5704],{},"Worst-case search",[755,5706,2077],{},[737,5708,5709,5712],{},[755,5710,5711],{},"Ordered",[755,5713,5714],{},"Yes (in-order traversal)",[737,5716,5717,5720],{},[755,5718,5719],{},"Dynamic",[755,5721,5722],{},"Yes (efficient insert\u002Fdelete)",[737,5724,5725,5728],{},[755,5726,5727],{},"Balanced guarantee",[755,5729,5730],{},"No (use AVL\u002FRed-Black for this)",[850,5732,5733],{},"html pre.shiki code .snl16, html code.shiki .snl16{--shiki-default:#F97583}html pre.shiki code .svObZ, html code.shiki .svObZ{--shiki-default:#B392F0}html pre.shiki code .s95oV, html code.shiki .s95oV{--shiki-default:#E1E4E8}html pre.shiki code .sU2Wk, html code.shiki .sU2Wk{--shiki-default:#9ECBFF}html pre.shiki code .sDLfK, html code.shiki .sDLfK{--shiki-default:#79B8FF}html pre.shiki code .sAwPA, html code.shiki .sAwPA{--shiki-default:#6A737D}html .default .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}",{"title":41,"searchDepth":122,"depth":122,"links":5735},[5736,5737,5738,5743,5744,5745,5746,5747,5748,5749,5750],{"id":4461,"depth":122,"text":4462},{"id":4495,"depth":122,"text":4496},{"id":892,"depth":122,"text":893,"children":5739},[5740,5741,5742],{"id":4563,"depth":129,"text":4518},{"id":4583,"depth":129,"text":4584},{"id":4595,"depth":129,"text":4596},{"id":4622,"depth":122,"text":4623},{"id":69,"depth":122,"text":70},{"id":1815,"depth":122,"text":1816},{"id":5473,"depth":122,"text":5474},{"id":5556,"depth":122,"text":5557},{"id":5621,"depth":122,"text":5622},{"id":5657,"depth":122,"text":5658},{"id":1997,"depth":122,"text":1998},"data-structures","Learn how binary search trees organize data for efficient searching, insertion, and deletion with O(log n) average performance.",{"timeComplexity":5754,"spaceComplexity":2077},"O(log n) avg","\u002Flearn\u002Fbinary-search-tree","bst",{"title":4450,"description":5752},"learn\u002Fbinary-search-tree","51ep5zbIjeHMfUmqvX9QCD304T1jfs5G5MXddqfwt6s",{"id":5761,"title":5762,"body":5763,"category":6049,"complexity":862,"date":862,"description":6050,"difficulty":2462,"extension":865,"meta":6051,"navigation":221,"order":85,"path":6052,"publishedAt":870,"relatedAlgorithmId":6053,"seo":6054,"stem":6055,"__hash__":6056},"learn\u002Flearn\u002Fbubble-sort.md","Bubble Sort",{"type":8,"value":5764,"toc":6042},[5765,5768,5771,5773,5790,5792,5993,5997,6008,6011,6015,6035,6037,6040],[11,5766,5762],{"id":5767},"bubble-sort",[15,5769,5770],{},"Bubble sort is the simplest sorting algorithm to understand. It repeatedly steps through the array, compares adjacent elements, and swaps them if they're in the wrong order. Each pass \"bubbles\" the largest unsorted element to its correct position at the end.",[24,5772,893],{"id":892},[895,5774,5775,5778,5781,5784,5787],{},[46,5776,5777],{},"Compare each pair of adjacent elements",[46,5779,5780],{},"If the left element is larger, swap them",[46,5782,5783],{},"After one pass, the largest element is at the end",[46,5785,5786],{},"Repeat for the remaining unsorted portion",[46,5788,5789],{},"Stop early if a pass makes no swaps (array is sorted)",[24,5791,70],{"id":69},[32,5793,5795],{"className":76,"code":5794,"language":78,"meta":41,"style":41},"def bubble_sort(numbers: list[int]) -> list[int]:\n    \"\"\"Sort by repeatedly swapping adjacent out-of-order pairs.\"\"\"\n    array_length = len(numbers)\n\n    for pass_number in range(array_length - 1):\n        swapped_this_pass = False\n\n        for current_position in range(array_length - 1 - pass_number):\n            current_value = numbers[current_position]\n            next_value = numbers[current_position + 1]\n\n            if current_value > next_value:\n                numbers[current_position] = next_value\n                numbers[current_position + 1] = current_value\n                swapped_this_pass = True\n\n        # Early exit: if no swaps occurred, array is already sorted\n        if not swapped_this_pass:\n            break\n\n    return numbers\n",[39,5796,5797,5813,5818,5828,5832,5850,5859,5863,5884,5894,5910,5914,5926,5936,5952,5961,5965,5970,5979,5983,5987],{"__ignoreMap":41},[82,5798,5799,5801,5803,5805,5807,5809,5811],{"class":84,"line":85},[82,5800,89],{"class":88},[82,5802,3756],{"class":92},[82,5804,1627],{"class":96},[82,5806,101],{"class":100},[82,5808,3503],{"class":96},[82,5810,101],{"class":100},[82,5812,119],{"class":96},[82,5814,5815],{"class":84,"line":122},[82,5816,5817],{"class":125},"    \"\"\"Sort by repeatedly swapping adjacent out-of-order pairs.\"\"\"\n",[82,5819,5820,5822,5824,5826],{"class":84,"line":129},[82,5821,3776],{"class":96},[82,5823,141],{"class":88},[82,5825,1471],{"class":100},[82,5827,3783],{"class":96},[82,5829,5830],{"class":84,"line":135},[82,5831,222],{"emptyLinePlaceholder":221},[82,5833,5834,5836,5838,5840,5842,5844,5846,5848],{"class":84,"line":147},[82,5835,982],{"class":88},[82,5837,3790],{"class":96},[82,5839,369],{"class":88},[82,5841,1228],{"class":100},[82,5843,3811],{"class":96},[82,5845,186],{"class":88},[82,5847,1348],{"class":100},[82,5849,2554],{"class":96},[82,5851,5852,5855,5857],{"class":84,"line":176},[82,5853,5854],{"class":96},"        swapped_this_pass ",[82,5856,141],{"class":88},[82,5858,1592],{"class":100},[82,5860,5861],{"class":84,"line":199},[82,5862,222],{"emptyLinePlaceholder":221},[82,5864,5865,5867,5870,5872,5874,5876,5878,5880,5882],{"class":84,"line":218},[82,5866,363],{"class":88},[82,5868,5869],{"class":96}," current_position ",[82,5871,369],{"class":88},[82,5873,1228],{"class":100},[82,5875,3811],{"class":96},[82,5877,186],{"class":88},[82,5879,1348],{"class":100},[82,5881,518],{"class":88},[82,5883,3820],{"class":96},[82,5885,5886,5889,5891],{"class":84,"line":225},[82,5887,5888],{"class":96},"            current_value ",[82,5890,141],{"class":88},[82,5892,5893],{"class":96}," numbers[current_position]\n",[82,5895,5896,5899,5901,5904,5906,5908],{"class":84,"line":236},[82,5897,5898],{"class":96},"            next_value ",[82,5900,141],{"class":88},[82,5902,5903],{"class":96}," numbers[current_position ",[82,5905,406],{"class":88},[82,5907,1348],{"class":100},[82,5909,3224],{"class":96},[82,5911,5912],{"class":84,"line":247},[82,5913,222],{"emptyLinePlaceholder":221},[82,5915,5916,5918,5921,5923],{"class":84,"line":262},[82,5917,378],{"class":88},[82,5919,5920],{"class":96}," current_value ",[82,5922,3461],{"class":88},[82,5924,5925],{"class":96}," next_value:\n",[82,5927,5928,5931,5933],{"class":84,"line":267},[82,5929,5930],{"class":96},"                numbers[current_position] ",[82,5932,141],{"class":88},[82,5934,5935],{"class":96}," next_value\n",[82,5937,5938,5941,5943,5945,5947,5949],{"class":84,"line":276},[82,5939,5940],{"class":96},"                numbers[current_position ",[82,5942,406],{"class":88},[82,5944,1348],{"class":100},[82,5946,192],{"class":96},[82,5948,141],{"class":88},[82,5950,5951],{"class":96}," current_value\n",[82,5953,5954,5957,5959],{"class":84,"line":282},[82,5955,5956],{"class":96},"                swapped_this_pass ",[82,5958,141],{"class":88},[82,5960,327],{"class":100},[82,5962,5963],{"class":84,"line":299},[82,5964,222],{"emptyLinePlaceholder":221},[82,5966,5967],{"class":84,"line":304},[82,5968,5969],{"class":258},"        # Early exit: if no swaps occurred, array is already sorted\n",[82,5971,5972,5974,5976],{"class":84,"line":313},[82,5973,307],{"class":88},[82,5975,2300],{"class":88},[82,5977,5978],{"class":96}," swapped_this_pass:\n",[82,5980,5981],{"class":84,"line":319},[82,5982,352],{"class":88},[82,5984,5985],{"class":84,"line":330},[82,5986,222],{"emptyLinePlaceholder":221},[82,5988,5989,5991],{"class":84,"line":335},[82,5990,568],{"class":88},[82,5992,3534],{"class":96},[24,5994,5996],{"id":5995},"why-on2","Why O(n^2)",[43,5998,5999,6002,6005],{},[46,6000,6001],{},"The outer loop runs up to n-1 times (one pass per element)",[46,6003,6004],{},"The inner loop runs up to n-1-pass comparisons per pass",[46,6006,6007],{},"Total comparisons: approximately n^2 \u002F 2",[15,6009,6010],{},"Even with the early-exit optimization, the worst case (reverse-sorted input) still requires all n^2\u002F2 comparisons.",[24,6012,6014],{"id":6013},"when-bubble-sort-is-acceptable","When Bubble Sort is Acceptable",[43,6016,6017,6023,6029],{},[46,6018,6019,6022],{},[19,6020,6021],{},"Teaching",": It's the easiest sorting algorithm to understand and visualize",[46,6024,6025,6028],{},[19,6026,6027],{},"Nearly sorted data",": With early exit, it's O(n) on already-sorted arrays",[46,6030,6031,6034],{},[19,6032,6033],{},"Tiny arrays",": For n \u003C 10, the simplicity outweighs the performance cost",[24,6036,1938],{"id":1937},[15,6038,6039],{},"For any practical sorting task with more than ~20 elements, use quicksort, merge sort, or your language's built-in sort. Bubble sort's O(n^2) makes it 10,000x slower than O(n log n) algorithms at n = 10,000.",[850,6041,852],{},{"title":41,"searchDepth":122,"depth":122,"links":6043},[6044,6045,6046,6047,6048],{"id":892,"depth":122,"text":893},{"id":69,"depth":122,"text":70},{"id":5995,"depth":122,"text":5996},{"id":6013,"depth":122,"text":6014},{"id":1937,"depth":122,"text":1938},"sorting","Understand the simplest comparison sort: how adjacent swaps bubble elements into place, and why it's O(n^2).",{"timeComplexity":3934,"spaceComplexity":3903},"\u002Flearn\u002Fbubble-sort","bubble",{"title":5762,"description":6050},"learn\u002Fbubble-sort","-8Y4pxUtj7zzO-8KggO0m6lnMwz4Q-xQsO6_GlCP1MA",{"id":6058,"title":6059,"body":6060,"category":861,"complexity":862,"date":862,"description":6561,"difficulty":2462,"extension":865,"meta":6562,"navigation":221,"order":129,"path":6563,"publishedAt":870,"relatedAlgorithmId":6564,"seo":6565,"stem":6566,"__hash__":6567},"learn\u002Flearn\u002Fdfs.md","Depth-First Search (DFS)",{"type":8,"value":6061,"toc":6553},[6062,6065,6068,6070,6087,6090,6092,6094,6355,6359,6362,6495,6499,6510,6512,6524,6527,6531,6551],[11,6063,6059],{"id":6064},"depth-first-search-dfs",[15,6066,6067],{},"DFS explores a graph by going as deep as possible along each branch before backtracking. It follows one path until it reaches a dead end, then backs up to the last unexplored branch. This creates a winding, depth-first exploration pattern.",[24,6069,893],{"id":892},[895,6071,6072,6075,6078,6081,6084],{},[46,6073,6074],{},"Start at the source node, push it onto the stack",[46,6076,6077],{},"Pop the top node from the stack",[46,6079,6080],{},"If not visited, mark it visited and process it",[46,6082,6083],{},"Push all its unvisited neighbors onto the stack",[46,6085,6086],{},"Repeat until the stack is empty or the goal is found",[15,6088,6089],{},"The stack (LIFO) is what creates the depth-first property — the most recently discovered node is explored first.",[24,6091,70],{"id":69},[15,6093,2118],{},[32,6095,6097],{"className":76,"code":6096,"language":78,"meta":41,"style":41},"def depth_first_search(graph, start_node: int, goal_node: int) -> list[int]:\n    \"\"\"Find a path from start to goal (not necessarily shortest).\"\"\"\n    visited = [False] * graph.num_nodes\n    parent_of = [-1] * graph.num_nodes\n    stack = [start_node]\n    found = False\n\n    while stack:\n        current_node = stack.pop()\n\n        if visited[current_node]:\n            continue\n        visited[current_node] = True\n\n        if current_node == goal_node:\n            found = True\n            break\n\n        for neighbor in graph.get_neighbors(current_node):\n            if not visited[neighbor]:\n                parent_of[neighbor] = current_node\n                stack.append(neighbor)\n\n    if not found:\n        return []\n\n    # Reconstruct path\n    path = []\n    node = goal_node\n    while node != -1:\n        path.append(node)\n        node = parent_of[node]\n    path.reverse()\n    return path\n",[39,6098,6099,6119,6124,6140,6158,6166,6175,6179,6185,6193,6197,6203,6207,6215,6219,6229,6238,6242,6246,6256,6264,6272,6276,6280,6289,6295,6299,6303,6311,6319,6333,6337,6345,6349],{"__ignoreMap":41},[82,6100,6101,6103,6105,6107,6109,6111,6113,6115,6117],{"class":84,"line":85},[82,6102,89],{"class":88},[82,6104,2843],{"class":92},[82,6106,97],{"class":96},[82,6108,101],{"class":100},[82,6110,104],{"class":96},[82,6112,101],{"class":100},[82,6114,2141],{"class":96},[82,6116,101],{"class":100},[82,6118,119],{"class":96},[82,6120,6121],{"class":84,"line":122},[82,6122,6123],{"class":125},"    \"\"\"Find a path from start to goal (not necessarily shortest).\"\"\"\n",[82,6125,6126,6128,6130,6132,6134,6136,6138],{"class":84,"line":129},[82,6127,202],{"class":96},[82,6129,141],{"class":88},[82,6131,155],{"class":96},[82,6133,209],{"class":100},[82,6135,192],{"class":96},[82,6137,170],{"class":88},[82,6139,144],{"class":96},[82,6141,6142,6144,6146,6148,6150,6152,6154,6156],{"class":84,"line":135},[82,6143,179],{"class":96},[82,6145,141],{"class":88},[82,6147,155],{"class":96},[82,6149,186],{"class":88},[82,6151,189],{"class":100},[82,6153,192],{"class":96},[82,6155,170],{"class":88},[82,6157,144],{"class":96},[82,6159,6160,6162,6164],{"class":84,"line":147},[82,6161,2879],{"class":96},[82,6163,141],{"class":88},[82,6165,2212],{"class":96},[82,6167,6168,6171,6173],{"class":84,"line":176},[82,6169,6170],{"class":96},"    found ",[82,6172,141],{"class":88},[82,6174,1592],{"class":100},[82,6176,6177],{"class":84,"line":199},[82,6178,222],{"emptyLinePlaceholder":221},[82,6180,6181,6183],{"class":84,"line":218},[82,6182,270],{"class":88},[82,6184,2902],{"class":96},[82,6186,6187,6189,6191],{"class":84,"line":225},[82,6188,2244],{"class":96},[82,6190,141],{"class":88},[82,6192,2911],{"class":96},[82,6194,6195],{"class":84,"line":236},[82,6196,222],{"emptyLinePlaceholder":221},[82,6198,6199,6201],{"class":84,"line":247},[82,6200,307],{"class":88},[82,6202,310],{"class":96},[82,6204,6205],{"class":84,"line":262},[82,6206,316],{"class":88},[82,6208,6209,6211,6213],{"class":84,"line":267},[82,6210,322],{"class":96},[82,6212,141],{"class":88},[82,6214,327],{"class":100},[82,6216,6217],{"class":84,"line":276},[82,6218,222],{"emptyLinePlaceholder":221},[82,6220,6221,6223,6225,6227],{"class":84,"line":282},[82,6222,307],{"class":88},[82,6224,340],{"class":96},[82,6226,343],{"class":88},[82,6228,346],{"class":96},[82,6230,6231,6234,6236],{"class":84,"line":299},[82,6232,6233],{"class":96},"            found ",[82,6235,141],{"class":88},[82,6237,327],{"class":100},[82,6239,6240],{"class":84,"line":304},[82,6241,352],{"class":88},[82,6243,6244],{"class":84,"line":313},[82,6245,222],{"emptyLinePlaceholder":221},[82,6247,6248,6250,6252,6254],{"class":84,"line":319},[82,6249,363],{"class":88},[82,6251,2289],{"class":96},[82,6253,369],{"class":88},[82,6255,372],{"class":96},[82,6257,6258,6260,6262],{"class":84,"line":330},[82,6259,378],{"class":88},[82,6261,2300],{"class":88},[82,6263,2303],{"class":96},[82,6265,6266,6268,6270],{"class":84,"line":335},[82,6267,2317],{"class":96},[82,6269,141],{"class":88},[82,6271,450],{"class":96},[82,6273,6274],{"class":84,"line":349},[82,6275,2960],{"class":96},[82,6277,6278],{"class":84,"line":355},[82,6279,222],{"emptyLinePlaceholder":221},[82,6281,6282,6284,6286],{"class":84,"line":360},[82,6283,960],{"class":88},[82,6285,2300],{"class":88},[82,6287,6288],{"class":96}," found:\n",[82,6290,6291,6293],{"class":84,"line":375},[82,6292,2655],{"class":88},[82,6294,493],{"class":96},[82,6296,6297],{"class":84,"line":384},[82,6298,222],{"emptyLinePlaceholder":221},[82,6300,6301],{"class":84,"line":390},[82,6302,482],{"class":258},[82,6304,6305,6307,6309],{"class":84,"line":395},[82,6306,488],{"class":96},[82,6308,141],{"class":88},[82,6310,493],{"class":96},[82,6312,6313,6315,6317],{"class":84,"line":412},[82,6314,499],{"class":96},[82,6316,141],{"class":88},[82,6318,504],{"class":96},[82,6320,6321,6323,6325,6327,6329,6331],{"class":84,"line":417},[82,6322,270],{"class":88},[82,6324,512],{"class":96},[82,6326,515],{"class":88},[82,6328,518],{"class":88},[82,6330,189],{"class":100},[82,6332,523],{"class":96},[82,6334,6335],{"class":84,"line":431},[82,6336,529],{"class":96},[82,6338,6339,6341,6343],{"class":84,"line":442},[82,6340,535],{"class":96},[82,6342,141],{"class":88},[82,6344,540],{"class":96},[82,6346,6347],{"class":84,"line":453},[82,6348,546],{"class":96},[82,6350,6351,6353],{"class":84,"line":468},[82,6352,568],{"class":88},[82,6354,2388],{"class":96},[24,6356,6358],{"id":6357},"recursive-version","Recursive Version",[15,6360,6361],{},"DFS maps naturally to recursion (the call stack acts as the explicit stack):",[32,6363,6365],{"className":76,"code":6364,"language":78,"meta":41,"style":41},"def dfs_recursive(graph, current_node: int, goal_node: int,\n                  visited: list[bool], path: list[int]) -> bool:\n    \"\"\"Recursive DFS. Returns True if goal is reachable.\"\"\"\n    visited[current_node] = True\n    path.append(current_node)\n\n    if current_node == goal_node:\n        return True\n\n    for neighbor in graph.get_neighbors(current_node):\n        if not visited[neighbor]:\n            if dfs_recursive(graph, neighbor, goal_node, visited, path):\n                return True\n\n    path.pop()  # backtrack\n    return False\n",[39,6366,6367,6386,6404,6409,6418,6423,6427,6437,6443,6447,6457,6465,6472,6478,6482,6489],{"__ignoreMap":41},[82,6368,6369,6371,6374,6377,6379,6381,6383],{"class":84,"line":85},[82,6370,89],{"class":88},[82,6372,6373],{"class":92}," dfs_recursive",[82,6375,6376],{"class":96},"(graph, current_node: ",[82,6378,101],{"class":100},[82,6380,104],{"class":96},[82,6382,101],{"class":100},[82,6384,6385],{"class":96},",\n",[82,6387,6388,6391,6393,6396,6398,6400,6402],{"class":84,"line":122},[82,6389,6390],{"class":96},"                  visited: list[",[82,6392,4921],{"class":100},[82,6394,6395],{"class":96},"], path: list[",[82,6397,101],{"class":100},[82,6399,3417],{"class":96},[82,6401,4921],{"class":100},[82,6403,523],{"class":96},[82,6405,6406],{"class":84,"line":129},[82,6407,6408],{"class":125},"    \"\"\"Recursive DFS. Returns True if goal is reachable.\"\"\"\n",[82,6410,6411,6414,6416],{"class":84,"line":135},[82,6412,6413],{"class":96},"    visited[current_node] ",[82,6415,141],{"class":88},[82,6417,327],{"class":100},[82,6419,6420],{"class":84,"line":147},[82,6421,6422],{"class":96},"    path.append(current_node)\n",[82,6424,6425],{"class":84,"line":176},[82,6426,222],{"emptyLinePlaceholder":221},[82,6428,6429,6431,6433,6435],{"class":84,"line":199},[82,6430,960],{"class":88},[82,6432,340],{"class":96},[82,6434,343],{"class":88},[82,6436,346],{"class":96},[82,6438,6439,6441],{"class":84,"line":218},[82,6440,2655],{"class":88},[82,6442,327],{"class":100},[82,6444,6445],{"class":84,"line":225},[82,6446,222],{"emptyLinePlaceholder":221},[82,6448,6449,6451,6453,6455],{"class":84,"line":236},[82,6450,982],{"class":88},[82,6452,2289],{"class":96},[82,6454,369],{"class":88},[82,6456,372],{"class":96},[82,6458,6459,6461,6463],{"class":84,"line":247},[82,6460,307],{"class":88},[82,6462,2300],{"class":88},[82,6464,2303],{"class":96},[82,6466,6467,6469],{"class":84,"line":262},[82,6468,378],{"class":88},[82,6470,6471],{"class":96}," dfs_recursive(graph, neighbor, goal_node, visited, path):\n",[82,6473,6474,6476],{"class":84,"line":267},[82,6475,4972],{"class":88},[82,6477,327],{"class":100},[82,6479,6480],{"class":84,"line":276},[82,6481,222],{"emptyLinePlaceholder":221},[82,6483,6484,6487],{"class":84,"line":282},[82,6485,6486],{"class":96},"    path.pop()  ",[82,6488,1015],{"class":258},[82,6490,6491,6493],{"class":84,"line":299},[82,6492,568],{"class":88},[82,6494,1592],{"class":100},[24,6496,6498],{"id":6497},"dfs-does-not-guarantee-shortest-path","DFS Does Not Guarantee Shortest Path",[15,6500,6501,6502,6505,6506,6509],{},"DFS explores depth-first, so it might find a long winding path when a short direct path exists. It finds ",[19,6503,6504],{},"a"," path, not the ",[19,6507,6508],{},"shortest"," path.",[24,6511,2417],{"id":2416},[43,6513,6514,6519],{},[46,6515,6516,6518],{},[19,6517,2048],{},": O(V + E) — same as BFS, visits each node and edge once",[46,6520,6521,6523],{},[19,6522,2429],{},": O(V) — the stack stores at most the depth of the graph (O(V) worst case for a long chain)",[15,6525,6526],{},"In practice, DFS uses less memory than BFS on wide graphs because it only stores the current path depth, not the entire frontier width.",[24,6528,6530],{"id":6529},"when-to-use-dfs","When to Use DFS",[43,6532,6533,6536,6539,6542,6545,6548],{},[46,6534,6535],{},"Detecting cycles in a graph",[46,6537,6538],{},"Topological sorting (processing dependencies)",[46,6540,6541],{},"Solving puzzles with backtracking (Sudoku, N-Queens, maze generation)",[46,6543,6544],{},"Finding connected components",[46,6546,6547],{},"When you need any path, not the shortest",[46,6549,6550],{},"When the graph is deep but narrow (memory advantage over BFS)",[850,6552,852],{},{"title":41,"searchDepth":122,"depth":122,"links":6554},[6555,6556,6557,6558,6559,6560],{"id":892,"depth":122,"text":893},{"id":69,"depth":122,"text":70},{"id":6357,"depth":122,"text":6358},{"id":6497,"depth":122,"text":6498},{"id":2416,"depth":122,"text":2417},{"id":6529,"depth":122,"text":6530},"Learn how DFS explores graphs by diving deep into branches before backtracking, using a stack for traversal.",{"timeComplexity":2464,"spaceComplexity":868},"\u002Flearn\u002Fdfs","dfs",{"title":6059,"description":6561},"learn\u002Fdfs","Us5MWXxxGrUoeo1q_cnf5WXGY49Qo7iG3TLOi3rWQp8",{"id":6569,"title":6570,"body":6571,"category":861,"complexity":862,"date":862,"description":7077,"difficulty":864,"extension":865,"meta":7078,"navigation":221,"order":135,"path":7079,"publishedAt":870,"relatedAlgorithmId":7080,"seo":7081,"stem":7082,"__hash__":7083},"learn\u002Flearn\u002Fdijkstra.md","Dijkstra's Algorithm",{"type":8,"value":6572,"toc":7069},[6573,6576,6579,6581,6601,6603,6605,6957,6961,6964,6970,6974,7030,7033,7035,7046,7049,7053,7067],[11,6574,6570],{"id":6575},"dijkstras-algorithm",[15,6577,6578],{},"Dijkstra's algorithm finds the cheapest path (minimum total edge weight) from a source to a destination on a weighted graph. It always expands the unvisited node with the lowest total cost so far, guaranteeing optimality.",[24,6580,893],{"id":892},[895,6582,6583,6586,6589,6592,6595,6598],{},[46,6584,6585],{},"Set the cost to reach the start node as 0, all others as infinity",[46,6587,6588],{},"Pick the unvisited node with the lowest cost (use a priority queue)",[46,6590,6591],{},"For each neighbor, calculate the cost through the current node",[46,6593,6594],{},"If this new cost is cheaper than the known cost, update it",[46,6596,6597],{},"Mark the current node as visited",[46,6599,6600],{},"Repeat until the goal is visited or all reachable nodes are processed",[24,6602,70],{"id":69},[15,6604,73],{},[32,6606,6608],{"className":76,"code":6607,"language":78,"meta":41,"style":41},"def dijkstra(graph, start_node: int, goal_node: int) -> tuple[list[int], int]:\n    \"\"\"Find cheapest path from start to goal on a weighted graph.\n    Returns (path, total_cost).\"\"\"\n    num_nodes = graph.num_nodes\n    cost_to_reach = [float('inf')] * num_nodes\n    parent_of = [-1] * num_nodes\n    visited = [False] * num_nodes\n\n    cost_to_reach[start_node] = 0\n    frontier = [(0, start_node)]  # (cost, node) pairs\n\n    while frontier:\n        # Pick the unvisited node with lowest cost\n        frontier.sort()\n        current_cost, current_node = frontier.pop(0)\n\n        if visited[current_node]:\n            continue\n        visited[current_node] = True\n\n        if current_node == goal_node:\n            break\n\n        for neighbor_node, edge_weight in graph.get_neighbors(current_node):\n            if visited[neighbor_node]:\n                continue\n\n            new_cost = current_cost + edge_weight\n\n            if new_cost \u003C cost_to_reach[neighbor_node]:\n                cost_to_reach[neighbor_node] = new_cost\n                parent_of[neighbor_node] = current_node\n                frontier.append((new_cost, neighbor_node))\n\n    # Reconstruct path\n    path = []\n    node = goal_node\n    while node != -1:\n        path.append(node)\n        node = parent_of[node]\n    path.reverse()\n\n    total_cost = cost_to_reach[goal_node]\n    return path, total_cost\n",[39,6609,6610,6636,6641,6646,6654,6674,6692,6708,6712,6720,6737,6741,6747,6752,6756,6769,6773,6779,6783,6791,6795,6805,6809,6813,6823,6829,6833,6837,6850,6854,6864,6872,6880,6885,6889,6893,6901,6909,6923,6927,6935,6939,6943,6951],{"__ignoreMap":41},[82,6611,6612,6614,6617,6619,6621,6623,6625,6628,6630,6632,6634],{"class":84,"line":85},[82,6613,89],{"class":88},[82,6615,6616],{"class":92}," dijkstra",[82,6618,97],{"class":96},[82,6620,101],{"class":100},[82,6622,104],{"class":96},[82,6624,101],{"class":100},[82,6626,6627],{"class":96},") -> tuple[list[",[82,6629,101],{"class":100},[82,6631,114],{"class":96},[82,6633,101],{"class":100},[82,6635,119],{"class":96},[82,6637,6638],{"class":84,"line":122},[82,6639,6640],{"class":125},"    \"\"\"Find cheapest path from start to goal on a weighted graph.\n",[82,6642,6643],{"class":84,"line":129},[82,6644,6645],{"class":125},"    Returns (path, total_cost).\"\"\"\n",[82,6647,6648,6650,6652],{"class":84,"line":135},[82,6649,138],{"class":96},[82,6651,141],{"class":88},[82,6653,144],{"class":96},[82,6655,6656,6658,6660,6662,6664,6666,6668,6670,6672],{"class":84,"line":147},[82,6657,150],{"class":96},[82,6659,141],{"class":88},[82,6661,155],{"class":96},[82,6663,158],{"class":100},[82,6665,161],{"class":96},[82,6667,164],{"class":125},[82,6669,167],{"class":96},[82,6671,170],{"class":88},[82,6673,173],{"class":96},[82,6675,6676,6678,6680,6682,6684,6686,6688,6690],{"class":84,"line":176},[82,6677,179],{"class":96},[82,6679,141],{"class":88},[82,6681,155],{"class":96},[82,6683,186],{"class":88},[82,6685,189],{"class":100},[82,6687,192],{"class":96},[82,6689,170],{"class":88},[82,6691,173],{"class":96},[82,6693,6694,6696,6698,6700,6702,6704,6706],{"class":84,"line":199},[82,6695,202],{"class":96},[82,6697,141],{"class":88},[82,6699,155],{"class":96},[82,6701,209],{"class":100},[82,6703,192],{"class":96},[82,6705,170],{"class":88},[82,6707,173],{"class":96},[82,6709,6710],{"class":84,"line":218},[82,6711,222],{"emptyLinePlaceholder":221},[82,6713,6714,6716,6718],{"class":84,"line":225},[82,6715,228],{"class":96},[82,6717,141],{"class":88},[82,6719,233],{"class":100},[82,6721,6722,6724,6726,6729,6731,6734],{"class":84,"line":236},[82,6723,250],{"class":96},[82,6725,141],{"class":88},[82,6727,6728],{"class":96}," [(",[82,6730,293],{"class":100},[82,6732,6733],{"class":96},", start_node)]  ",[82,6735,6736],{"class":258},"# (cost, node) pairs\n",[82,6738,6739],{"class":84,"line":247},[82,6740,222],{"emptyLinePlaceholder":221},[82,6742,6743,6745],{"class":84,"line":262},[82,6744,270],{"class":88},[82,6746,273],{"class":96},[82,6748,6749],{"class":84,"line":267},[82,6750,6751],{"class":258},"        # Pick the unvisited node with lowest cost\n",[82,6753,6754],{"class":84,"line":276},[82,6755,279],{"class":96},[82,6757,6758,6761,6763,6765,6767],{"class":84,"line":282},[82,6759,6760],{"class":96},"        current_cost, current_node ",[82,6762,141],{"class":88},[82,6764,290],{"class":96},[82,6766,293],{"class":100},[82,6768,296],{"class":96},[82,6770,6771],{"class":84,"line":299},[82,6772,222],{"emptyLinePlaceholder":221},[82,6774,6775,6777],{"class":84,"line":304},[82,6776,307],{"class":88},[82,6778,310],{"class":96},[82,6780,6781],{"class":84,"line":313},[82,6782,316],{"class":88},[82,6784,6785,6787,6789],{"class":84,"line":319},[82,6786,322],{"class":96},[82,6788,141],{"class":88},[82,6790,327],{"class":100},[82,6792,6793],{"class":84,"line":330},[82,6794,222],{"emptyLinePlaceholder":221},[82,6796,6797,6799,6801,6803],{"class":84,"line":335},[82,6798,307],{"class":88},[82,6800,340],{"class":96},[82,6802,343],{"class":88},[82,6804,346],{"class":96},[82,6806,6807],{"class":84,"line":349},[82,6808,352],{"class":88},[82,6810,6811],{"class":84,"line":355},[82,6812,222],{"emptyLinePlaceholder":221},[82,6814,6815,6817,6819,6821],{"class":84,"line":360},[82,6816,363],{"class":88},[82,6818,366],{"class":96},[82,6820,369],{"class":88},[82,6822,372],{"class":96},[82,6824,6825,6827],{"class":84,"line":375},[82,6826,378],{"class":88},[82,6828,381],{"class":96},[82,6830,6831],{"class":84,"line":384},[82,6832,387],{"class":88},[82,6834,6835],{"class":84,"line":390},[82,6836,222],{"emptyLinePlaceholder":221},[82,6838,6839,6841,6843,6846,6848],{"class":84,"line":395},[82,6840,398],{"class":96},[82,6842,141],{"class":88},[82,6844,6845],{"class":96}," current_cost ",[82,6847,406],{"class":88},[82,6849,409],{"class":96},[82,6851,6852],{"class":84,"line":412},[82,6853,222],{"emptyLinePlaceholder":221},[82,6855,6856,6858,6860,6862],{"class":84,"line":417},[82,6857,378],{"class":88},[82,6859,422],{"class":96},[82,6861,425],{"class":88},[82,6863,428],{"class":96},[82,6865,6866,6868,6870],{"class":84,"line":431},[82,6867,434],{"class":96},[82,6869,141],{"class":88},[82,6871,439],{"class":96},[82,6873,6874,6876,6878],{"class":84,"line":442},[82,6875,445],{"class":96},[82,6877,141],{"class":88},[82,6879,450],{"class":96},[82,6881,6882],{"class":84,"line":453},[82,6883,6884],{"class":96},"                frontier.append((new_cost, neighbor_node))\n",[82,6886,6887],{"class":84,"line":468},[82,6888,222],{"emptyLinePlaceholder":221},[82,6890,6891],{"class":84,"line":474},[82,6892,482],{"class":258},[82,6894,6895,6897,6899],{"class":84,"line":479},[82,6896,488],{"class":96},[82,6898,141],{"class":88},[82,6900,493],{"class":96},[82,6902,6903,6905,6907],{"class":84,"line":485},[82,6904,499],{"class":96},[82,6906,141],{"class":88},[82,6908,504],{"class":96},[82,6910,6911,6913,6915,6917,6919,6921],{"class":84,"line":496},[82,6912,270],{"class":88},[82,6914,512],{"class":96},[82,6916,515],{"class":88},[82,6918,518],{"class":88},[82,6920,189],{"class":100},[82,6922,523],{"class":96},[82,6924,6925],{"class":84,"line":507},[82,6926,529],{"class":96},[82,6928,6929,6931,6933],{"class":84,"line":526},[82,6930,535],{"class":96},[82,6932,141],{"class":88},[82,6934,540],{"class":96},[82,6936,6937],{"class":84,"line":532},[82,6938,546],{"class":96},[82,6940,6941],{"class":84,"line":543},[82,6942,222],{"emptyLinePlaceholder":221},[82,6944,6945,6947,6949],{"class":84,"line":549},[82,6946,557],{"class":96},[82,6948,141],{"class":88},[82,6950,562],{"class":96},[82,6952,6953,6955],{"class":84,"line":554},[82,6954,568],{"class":88},[82,6956,571],{"class":96},[24,6958,6960],{"id":6959},"why-dijkstra-is-optimal","Why Dijkstra is Optimal",[15,6962,6963],{},"When Dijkstra visits a node, it has found the cheapest possible path to that node. This is because it always processes the lowest-cost node next — any unprocessed node has equal or higher cost, so it cannot provide a shortcut.",[15,6965,6966,6969],{},[19,6967,6968],{},"Requirement",": All edge weights must be non-negative. Negative weights can create cheaper paths through already-visited nodes, breaking the guarantee.",[24,6971,6973],{"id":6972},"dijkstra-vs-bfs","Dijkstra vs BFS",[731,6975,6976,6986],{},[734,6977,6978],{},[737,6979,6980,6982,6984],{},[740,6981,742],{},[740,6983,3049],{},[740,6985,745],{},[750,6987,6988,6999,7010,7019],{},[737,6989,6990,6993,6996],{},[755,6991,6992],{},"Graph type",[755,6994,6995],{},"Unweighted",[755,6997,6998],{},"Weighted (non-negative)",[737,7000,7001,7004,7007],{},[755,7002,7003],{},"Optimizes",[755,7005,7006],{},"Fewest hops",[755,7008,7009],{},"Lowest total cost",[737,7011,7012,7014,7016],{},[755,7013,3059],{},[755,7015,3062],{},[755,7017,7018],{},"Priority queue",[737,7020,7021,7024,7027],{},[755,7022,7023],{},"On unweighted graph",[755,7025,7026],{},"Optimal",[755,7028,7029],{},"Same result, more overhead",[15,7031,7032],{},"On an unweighted graph (all weights = 1), Dijkstra degenerates to BFS. Use BFS when weights are uniform.",[24,7034,4369],{"id":4368},[43,7036,7037,7040,7043],{},[46,7038,7039],{},"With a simple list as priority queue: O(V^2)",[46,7041,7042],{},"With a binary heap: O((V + E) log V)",[46,7044,7045],{},"With a Fibonacci heap: O(V log V + E) — theoretical best",[15,7047,7048],{},"For most practical cases, a binary heap is the right choice.",[24,7050,7052],{"id":7051},"when-to-use-dijkstra","When to Use Dijkstra",[43,7054,7055,7058,7061,7064],{},[46,7056,7057],{},"Finding cheapest path on weighted graphs with non-negative edges",[46,7059,7060],{},"GPS\u002Fnavigation (road network with distances or travel times)",[46,7062,7063],{},"Network routing (minimizing latency or cost)",[46,7065,7066],{},"Any \"minimum cost path\" problem where you don't know the goal's position relative to the start",[850,7068,852],{},{"title":41,"searchDepth":122,"depth":122,"links":7070},[7071,7072,7073,7074,7075,7076],{"id":892,"depth":122,"text":893},{"id":69,"depth":122,"text":70},{"id":6959,"depth":122,"text":6960},{"id":6972,"depth":122,"text":6973},{"id":4368,"depth":122,"text":4369},{"id":7051,"depth":122,"text":7052},"Learn how Dijkstra finds the cheapest path on weighted graphs by expanding nodes in order of total cost.",{"timeComplexity":867,"spaceComplexity":868},"\u002Flearn\u002Fdijkstra","dijkstra",{"title":6570,"description":7077},"learn\u002Fdijkstra","XHIz0QWGw_u0SxLnHR9fiD0W7KXwzmk59mF22p8dTRs",{"id":7085,"title":7086,"body":7087,"category":3113,"complexity":862,"date":862,"description":8170,"difficulty":864,"extension":865,"meta":8171,"navigation":221,"order":135,"path":8172,"publishedAt":870,"relatedAlgorithmId":7080,"seo":8173,"stem":8174,"__hash__":8175},"learn\u002Flearn\u002Fdijkstra-and-astar.md","Dijkstra and A* Search",{"type":8,"value":7088,"toc":8157},[7089,7092,7095,7097,7104,7107,7109,7123,7127,7133,7139,7156,7159,7173,7175,7178,7314,7318,7646,7650,8087,8091,8149,8151,8154],[11,7090,7086],{"id":7091},"dijkstra-and-a-search",[15,7093,7094],{},"When graph edges have different weights (costs), BFS no longer finds the cheapest path — it finds the path with fewest hops. Dijkstra's algorithm and A* both solve the weighted shortest-path problem, but with different strategies.",[24,7096,6570],{"id":6575},[15,7098,7099,7100,7103],{},"Dijkstra explores nodes in order of their ",[19,7101,7102],{},"total cost from the start",". It always expands the cheapest unvisited node next, guaranteeing that when it reaches any node, it has found the cheapest path to it.",[15,7105,7106],{},"Think of it like water flowing through pipes of different widths — it fills the cheapest paths first.",[1024,7108,1998],{"id":1997},[43,7110,7111,7114,7117,7120],{},[46,7112,7113],{},"Finds the cheapest path (minimum total edge weight)",[46,7115,7116],{},"Explores uniformly in all directions by cost",[46,7118,7119],{},"Does not use any information about where the goal is",[46,7121,7122],{},"Requires non-negative edge weights",[24,7124,7126],{"id":7125},"a-search","A* Search",[15,7128,7129,7130,7132],{},"A* improves on Dijkstra by adding a ",[19,7131,21],{}," — an estimate of remaining cost to the goal. It prioritizes nodes where actual cost so far + estimated cost to goal is lowest.",[15,7134,7135,7136],{},"The formula: ",[39,7137,7138],{},"f(node) = g(node) + h(node)",[43,7140,7141,7146,7151],{},[46,7142,7143,7145],{},[39,7144,50],{}," = actual cost from start to this node",[46,7147,7148,7150],{},[39,7149,56],{}," = estimated cost from this node to the goal",[46,7152,7153,7155],{},[39,7154,62],{}," = total estimated cost of the path through this node",[1024,7157,1998],{"id":7158},"key-properties-1",[43,7160,7161,7164,7167,7170],{},[46,7162,7163],{},"Finds the cheapest path (same guarantee as Dijkstra) when the heuristic is admissible",[46,7165,7166],{},"Explores fewer nodes than Dijkstra because it's guided toward the goal",[46,7168,7169],{},"An admissible heuristic never overestimates the true cost",[46,7171,7172],{},"Manhattan distance is admissible for grid-based movement",[24,7174,2524],{"id":2523},[15,7176,7177],{},"Both algorithms use the same weighted graph structure:",[32,7179,7181],{"className":76,"code":7180,"language":78,"meta":41,"style":41},"class WeightedGraph:\n    def __init__(self, num_nodes: int):\n        self.num_nodes = num_nodes\n        self.edges = [[] for _ in range(num_nodes)]\n\n    def add_edge(self, from_node: int, to_node: int, weight: int):\n        self.edges[from_node].append((to_node, weight))\n        self.edges[to_node].append((from_node, weight))\n\n    def get_neighbors(self, node: int) -> list[tuple[int, int]]:\n        \"\"\"Returns list of (neighbor, weight) pairs.\"\"\"\n        return self.edges[node]\n",[39,7182,7183,7192,7204,7214,7235,7239,7260,7267,7274,7278,7300,7305],{"__ignoreMap":41},[82,7184,7185,7187,7190],{"class":84,"line":85},[82,7186,2534],{"class":88},[82,7188,7189],{"class":92}," WeightedGraph",[82,7191,523],{"class":96},[82,7193,7194,7196,7198,7200,7202],{"class":84,"line":122},[82,7195,1176],{"class":88},[82,7197,2546],{"class":100},[82,7199,2549],{"class":96},[82,7201,101],{"class":100},[82,7203,2554],{"class":96},[82,7205,7206,7208,7210,7212],{"class":84,"line":129},[82,7207,2559],{"class":100},[82,7209,2562],{"class":96},[82,7211,141],{"class":88},[82,7213,173],{"class":96},[82,7215,7216,7218,7221,7223,7225,7227,7229,7231,7233],{"class":84,"line":135},[82,7217,2559],{"class":100},[82,7219,7220],{"class":96},".edges ",[82,7222,141],{"class":88},[82,7224,2578],{"class":96},[82,7226,2581],{"class":88},[82,7228,2584],{"class":96},[82,7230,369],{"class":88},[82,7232,1228],{"class":100},[82,7234,2591],{"class":96},[82,7236,7237],{"class":84,"line":147},[82,7238,222],{"emptyLinePlaceholder":221},[82,7240,7241,7243,7245,7247,7249,7251,7253,7256,7258],{"class":84,"line":176},[82,7242,1176],{"class":88},[82,7244,2602],{"class":92},[82,7246,2605],{"class":96},[82,7248,101],{"class":100},[82,7250,2610],{"class":96},[82,7252,101],{"class":100},[82,7254,7255],{"class":96},", weight: ",[82,7257,101],{"class":100},[82,7259,2554],{"class":96},[82,7261,7262,7264],{"class":84,"line":199},[82,7263,2559],{"class":100},[82,7265,7266],{"class":96},".edges[from_node].append((to_node, weight))\n",[82,7268,7269,7271],{"class":84,"line":218},[82,7270,2559],{"class":100},[82,7272,7273],{"class":96},".edges[to_node].append((from_node, weight))\n",[82,7275,7276],{"class":84,"line":225},[82,7277,222],{"emptyLinePlaceholder":221},[82,7279,7280,7282,7284,7286,7288,7291,7293,7296,7298],{"class":84,"line":236},[82,7281,1176],{"class":88},[82,7283,2639],{"class":92},[82,7285,2642],{"class":96},[82,7287,101],{"class":100},[82,7289,7290],{"class":96},") -> list[tuple[",[82,7292,101],{"class":100},[82,7294,7295],{"class":96},", ",[82,7297,101],{"class":100},[82,7299,1070],{"class":96},[82,7301,7302],{"class":84,"line":247},[82,7303,7304],{"class":125},"        \"\"\"Returns list of (neighbor, weight) pairs.\"\"\"\n",[82,7306,7307,7309,7311],{"class":84,"line":262},[82,7308,2655],{"class":88},[82,7310,2658],{"class":100},[82,7312,7313],{"class":96},".edges[node]\n",[24,7315,7317],{"id":7316},"code-snippet-dijkstra","Code Snippet — Dijkstra",[32,7319,7321],{"className":76,"code":7320,"language":78,"meta":41,"style":41},"def dijkstra(graph: WeightedGraph, start_node: int, goal_node: int) -> list[int]:\n    \"\"\"Find cheapest path from start to goal using uniform-cost expansion.\"\"\"\n    num_nodes = graph.num_nodes\n    cost_to_reach = [float('inf')] * num_nodes\n    parent_of = [-1] * num_nodes\n    visited = [False] * num_nodes\n\n    cost_to_reach[start_node] = 0\n\n    # Simple priority queue: list of (cost, node), pick minimum each step\n    frontier = [(0, start_node)]\n\n    while frontier:\n        # Find the unvisited node with lowest cost\n        frontier.sort()\n        current_cost, current_node = frontier.pop(0)\n\n        if visited[current_node]:\n            continue\n        visited[current_node] = True\n\n        if current_node == goal_node:\n            break\n\n        for neighbor, edge_weight in graph.get_neighbors(current_node):\n            if visited[neighbor]:\n                continue\n            new_cost = current_cost + edge_weight\n            if new_cost \u003C cost_to_reach[neighbor]:\n                cost_to_reach[neighbor] = new_cost\n                parent_of[neighbor] = current_node\n                frontier.append((new_cost, neighbor))\n\n    # Reconstruct path\n    path = []\n    node = goal_node\n    while node != -1:\n        path.append(node)\n        node = parent_of[node]\n    path.reverse()\n    return path\n",[39,7322,7323,7344,7349,7357,7377,7395,7411,7415,7423,7427,7432,7445,7449,7455,7460,7464,7476,7480,7486,7490,7498,7502,7512,7516,7520,7531,7537,7541,7553,7564,7573,7581,7586,7590,7594,7602,7610,7624,7628,7636,7640],{"__ignoreMap":41},[82,7324,7325,7327,7329,7332,7334,7336,7338,7340,7342],{"class":84,"line":85},[82,7326,89],{"class":88},[82,7328,6616],{"class":92},[82,7330,7331],{"class":96},"(graph: WeightedGraph, start_node: ",[82,7333,101],{"class":100},[82,7335,104],{"class":96},[82,7337,101],{"class":100},[82,7339,2141],{"class":96},[82,7341,101],{"class":100},[82,7343,119],{"class":96},[82,7345,7346],{"class":84,"line":122},[82,7347,7348],{"class":125},"    \"\"\"Find cheapest path from start to goal using uniform-cost expansion.\"\"\"\n",[82,7350,7351,7353,7355],{"class":84,"line":129},[82,7352,138],{"class":96},[82,7354,141],{"class":88},[82,7356,144],{"class":96},[82,7358,7359,7361,7363,7365,7367,7369,7371,7373,7375],{"class":84,"line":135},[82,7360,150],{"class":96},[82,7362,141],{"class":88},[82,7364,155],{"class":96},[82,7366,158],{"class":100},[82,7368,161],{"class":96},[82,7370,164],{"class":125},[82,7372,167],{"class":96},[82,7374,170],{"class":88},[82,7376,173],{"class":96},[82,7378,7379,7381,7383,7385,7387,7389,7391,7393],{"class":84,"line":147},[82,7380,179],{"class":96},[82,7382,141],{"class":88},[82,7384,155],{"class":96},[82,7386,186],{"class":88},[82,7388,189],{"class":100},[82,7390,192],{"class":96},[82,7392,170],{"class":88},[82,7394,173],{"class":96},[82,7396,7397,7399,7401,7403,7405,7407,7409],{"class":84,"line":176},[82,7398,202],{"class":96},[82,7400,141],{"class":88},[82,7402,155],{"class":96},[82,7404,209],{"class":100},[82,7406,192],{"class":96},[82,7408,170],{"class":88},[82,7410,173],{"class":96},[82,7412,7413],{"class":84,"line":199},[82,7414,222],{"emptyLinePlaceholder":221},[82,7416,7417,7419,7421],{"class":84,"line":218},[82,7418,228],{"class":96},[82,7420,141],{"class":88},[82,7422,233],{"class":100},[82,7424,7425],{"class":84,"line":225},[82,7426,222],{"emptyLinePlaceholder":221},[82,7428,7429],{"class":84,"line":236},[82,7430,7431],{"class":258},"    # Simple priority queue: list of (cost, node), pick minimum each step\n",[82,7433,7434,7436,7438,7440,7442],{"class":84,"line":247},[82,7435,250],{"class":96},[82,7437,141],{"class":88},[82,7439,6728],{"class":96},[82,7441,293],{"class":100},[82,7443,7444],{"class":96},", start_node)]\n",[82,7446,7447],{"class":84,"line":262},[82,7448,222],{"emptyLinePlaceholder":221},[82,7450,7451,7453],{"class":84,"line":267},[82,7452,270],{"class":88},[82,7454,273],{"class":96},[82,7456,7457],{"class":84,"line":276},[82,7458,7459],{"class":258},"        # Find the unvisited node with lowest cost\n",[82,7461,7462],{"class":84,"line":282},[82,7463,279],{"class":96},[82,7465,7466,7468,7470,7472,7474],{"class":84,"line":299},[82,7467,6760],{"class":96},[82,7469,141],{"class":88},[82,7471,290],{"class":96},[82,7473,293],{"class":100},[82,7475,296],{"class":96},[82,7477,7478],{"class":84,"line":304},[82,7479,222],{"emptyLinePlaceholder":221},[82,7481,7482,7484],{"class":84,"line":313},[82,7483,307],{"class":88},[82,7485,310],{"class":96},[82,7487,7488],{"class":84,"line":319},[82,7489,316],{"class":88},[82,7491,7492,7494,7496],{"class":84,"line":330},[82,7493,322],{"class":96},[82,7495,141],{"class":88},[82,7497,327],{"class":100},[82,7499,7500],{"class":84,"line":335},[82,7501,222],{"emptyLinePlaceholder":221},[82,7503,7504,7506,7508,7510],{"class":84,"line":349},[82,7505,307],{"class":88},[82,7507,340],{"class":96},[82,7509,343],{"class":88},[82,7511,346],{"class":96},[82,7513,7514],{"class":84,"line":355},[82,7515,352],{"class":88},[82,7517,7518],{"class":84,"line":360},[82,7519,222],{"emptyLinePlaceholder":221},[82,7521,7522,7524,7527,7529],{"class":84,"line":375},[82,7523,363],{"class":88},[82,7525,7526],{"class":96}," neighbor, edge_weight ",[82,7528,369],{"class":88},[82,7530,372],{"class":96},[82,7532,7533,7535],{"class":84,"line":384},[82,7534,378],{"class":88},[82,7536,2303],{"class":96},[82,7538,7539],{"class":84,"line":390},[82,7540,387],{"class":88},[82,7542,7543,7545,7547,7549,7551],{"class":84,"line":395},[82,7544,398],{"class":96},[82,7546,141],{"class":88},[82,7548,6845],{"class":96},[82,7550,406],{"class":88},[82,7552,409],{"class":96},[82,7554,7555,7557,7559,7561],{"class":84,"line":412},[82,7556,378],{"class":88},[82,7558,422],{"class":96},[82,7560,425],{"class":88},[82,7562,7563],{"class":96}," cost_to_reach[neighbor]:\n",[82,7565,7566,7569,7571],{"class":84,"line":417},[82,7567,7568],{"class":96},"                cost_to_reach[neighbor] ",[82,7570,141],{"class":88},[82,7572,439],{"class":96},[82,7574,7575,7577,7579],{"class":84,"line":431},[82,7576,2317],{"class":96},[82,7578,141],{"class":88},[82,7580,450],{"class":96},[82,7582,7583],{"class":84,"line":442},[82,7584,7585],{"class":96},"                frontier.append((new_cost, neighbor))\n",[82,7587,7588],{"class":84,"line":453},[82,7589,222],{"emptyLinePlaceholder":221},[82,7591,7592],{"class":84,"line":468},[82,7593,482],{"class":258},[82,7595,7596,7598,7600],{"class":84,"line":474},[82,7597,488],{"class":96},[82,7599,141],{"class":88},[82,7601,493],{"class":96},[82,7603,7604,7606,7608],{"class":84,"line":479},[82,7605,499],{"class":96},[82,7607,141],{"class":88},[82,7609,504],{"class":96},[82,7611,7612,7614,7616,7618,7620,7622],{"class":84,"line":485},[82,7613,270],{"class":88},[82,7615,512],{"class":96},[82,7617,515],{"class":88},[82,7619,518],{"class":88},[82,7621,189],{"class":100},[82,7623,523],{"class":96},[82,7625,7626],{"class":84,"line":496},[82,7627,529],{"class":96},[82,7629,7630,7632,7634],{"class":84,"line":507},[82,7631,535],{"class":96},[82,7633,141],{"class":88},[82,7635,540],{"class":96},[82,7637,7638],{"class":84,"line":526},[82,7639,546],{"class":96},[82,7641,7642,7644],{"class":84,"line":532},[82,7643,568],{"class":88},[82,7645,2388],{"class":96},[24,7647,7649],{"id":7648},"code-snippet-a","Code Snippet — A*",[32,7651,7653],{"className":76,"code":7652,"language":78,"meta":41,"style":41},"def astar(graph: WeightedGraph, start_node: int, goal_node: int,\n          heuristic) -> list[int]:\n    \"\"\"Find cheapest path using cost + heuristic estimate.\"\"\"\n    num_nodes = graph.num_nodes\n    cost_to_reach = [float('inf')] * num_nodes\n    parent_of = [-1] * num_nodes\n    visited = [False] * num_nodes\n\n    cost_to_reach[start_node] = 0\n    estimated_total = heuristic(start_node, goal_node)\n\n    # Priority queue: (f_score, node)\n    frontier = [(estimated_total, start_node)]\n\n    while frontier:\n        frontier.sort()\n        current_f_score, current_node = frontier.pop(0)\n\n        if visited[current_node]:\n            continue\n        visited[current_node] = True\n\n        if current_node == goal_node:\n            break\n\n        for neighbor, edge_weight in graph.get_neighbors(current_node):\n            if visited[neighbor]:\n                continue\n            new_cost = cost_to_reach[current_node] + edge_weight\n            if new_cost \u003C cost_to_reach[neighbor]:\n                cost_to_reach[neighbor] = new_cost\n                parent_of[neighbor] = current_node\n                f_score = new_cost + heuristic(neighbor, goal_node)\n                frontier.append((f_score, neighbor))\n\n    # Reconstruct path\n    path = []\n    node = goal_node\n    while node != -1:\n        path.append(node)\n        node = parent_of[node]\n    path.reverse()\n    return path\n\n\ndef manhattan_distance(node_a: int, node_b: int, grid_cols: int) -> int:\n    \"\"\"Admissible heuristic for grid-based pathfinding.\"\"\"\n    row_a, col_a = node_a \u002F\u002F grid_cols, node_a % grid_cols\n    row_b, col_b = node_b \u002F\u002F grid_cols, node_b % grid_cols\n    return abs(row_a - row_b) + abs(col_a - col_b)\n",[39,7654,7655,7672,7681,7686,7694,7714,7732,7748,7752,7760,7768,7772,7777,7786,7790,7796,7800,7812,7816,7822,7826,7834,7838,7848,7852,7856,7866,7872,7876,7888,7898,7906,7914,7927,7932,7936,7940,7948,7956,7970,7974,7982,7986,7992,7996,8000,8025,8030,8048,8065],{"__ignoreMap":41},[82,7656,7657,7659,7662,7664,7666,7668,7670],{"class":84,"line":85},[82,7658,89],{"class":88},[82,7660,7661],{"class":92}," astar",[82,7663,7331],{"class":96},[82,7665,101],{"class":100},[82,7667,104],{"class":96},[82,7669,101],{"class":100},[82,7671,6385],{"class":96},[82,7673,7674,7677,7679],{"class":84,"line":122},[82,7675,7676],{"class":96},"          heuristic) -> list[",[82,7678,101],{"class":100},[82,7680,119],{"class":96},[82,7682,7683],{"class":84,"line":129},[82,7684,7685],{"class":125},"    \"\"\"Find cheapest path using cost + heuristic estimate.\"\"\"\n",[82,7687,7688,7690,7692],{"class":84,"line":135},[82,7689,138],{"class":96},[82,7691,141],{"class":88},[82,7693,144],{"class":96},[82,7695,7696,7698,7700,7702,7704,7706,7708,7710,7712],{"class":84,"line":147},[82,7697,150],{"class":96},[82,7699,141],{"class":88},[82,7701,155],{"class":96},[82,7703,158],{"class":100},[82,7705,161],{"class":96},[82,7707,164],{"class":125},[82,7709,167],{"class":96},[82,7711,170],{"class":88},[82,7713,173],{"class":96},[82,7715,7716,7718,7720,7722,7724,7726,7728,7730],{"class":84,"line":176},[82,7717,179],{"class":96},[82,7719,141],{"class":88},[82,7721,155],{"class":96},[82,7723,186],{"class":88},[82,7725,189],{"class":100},[82,7727,192],{"class":96},[82,7729,170],{"class":88},[82,7731,173],{"class":96},[82,7733,7734,7736,7738,7740,7742,7744,7746],{"class":84,"line":199},[82,7735,202],{"class":96},[82,7737,141],{"class":88},[82,7739,155],{"class":96},[82,7741,209],{"class":100},[82,7743,192],{"class":96},[82,7745,170],{"class":88},[82,7747,173],{"class":96},[82,7749,7750],{"class":84,"line":218},[82,7751,222],{"emptyLinePlaceholder":221},[82,7753,7754,7756,7758],{"class":84,"line":225},[82,7755,228],{"class":96},[82,7757,141],{"class":88},[82,7759,233],{"class":100},[82,7761,7762,7764,7766],{"class":84,"line":236},[82,7763,239],{"class":96},[82,7765,141],{"class":88},[82,7767,244],{"class":96},[82,7769,7770],{"class":84,"line":247},[82,7771,222],{"emptyLinePlaceholder":221},[82,7773,7774],{"class":84,"line":262},[82,7775,7776],{"class":258},"    # Priority queue: (f_score, node)\n",[82,7778,7779,7781,7783],{"class":84,"line":267},[82,7780,250],{"class":96},[82,7782,141],{"class":88},[82,7784,7785],{"class":96}," [(estimated_total, start_node)]\n",[82,7787,7788],{"class":84,"line":276},[82,7789,222],{"emptyLinePlaceholder":221},[82,7791,7792,7794],{"class":84,"line":282},[82,7793,270],{"class":88},[82,7795,273],{"class":96},[82,7797,7798],{"class":84,"line":299},[82,7799,279],{"class":96},[82,7801,7802,7804,7806,7808,7810],{"class":84,"line":304},[82,7803,285],{"class":96},[82,7805,141],{"class":88},[82,7807,290],{"class":96},[82,7809,293],{"class":100},[82,7811,296],{"class":96},[82,7813,7814],{"class":84,"line":313},[82,7815,222],{"emptyLinePlaceholder":221},[82,7817,7818,7820],{"class":84,"line":319},[82,7819,307],{"class":88},[82,7821,310],{"class":96},[82,7823,7824],{"class":84,"line":330},[82,7825,316],{"class":88},[82,7827,7828,7830,7832],{"class":84,"line":335},[82,7829,322],{"class":96},[82,7831,141],{"class":88},[82,7833,327],{"class":100},[82,7835,7836],{"class":84,"line":349},[82,7837,222],{"emptyLinePlaceholder":221},[82,7839,7840,7842,7844,7846],{"class":84,"line":355},[82,7841,307],{"class":88},[82,7843,340],{"class":96},[82,7845,343],{"class":88},[82,7847,346],{"class":96},[82,7849,7850],{"class":84,"line":360},[82,7851,352],{"class":88},[82,7853,7854],{"class":84,"line":375},[82,7855,222],{"emptyLinePlaceholder":221},[82,7857,7858,7860,7862,7864],{"class":84,"line":384},[82,7859,363],{"class":88},[82,7861,7526],{"class":96},[82,7863,369],{"class":88},[82,7865,372],{"class":96},[82,7867,7868,7870],{"class":84,"line":390},[82,7869,378],{"class":88},[82,7871,2303],{"class":96},[82,7873,7874],{"class":84,"line":395},[82,7875,387],{"class":88},[82,7877,7878,7880,7882,7884,7886],{"class":84,"line":412},[82,7879,398],{"class":96},[82,7881,141],{"class":88},[82,7883,403],{"class":96},[82,7885,406],{"class":88},[82,7887,409],{"class":96},[82,7889,7890,7892,7894,7896],{"class":84,"line":417},[82,7891,378],{"class":88},[82,7893,422],{"class":96},[82,7895,425],{"class":88},[82,7897,7563],{"class":96},[82,7899,7900,7902,7904],{"class":84,"line":431},[82,7901,7568],{"class":96},[82,7903,141],{"class":88},[82,7905,439],{"class":96},[82,7907,7908,7910,7912],{"class":84,"line":442},[82,7909,2317],{"class":96},[82,7911,141],{"class":88},[82,7913,450],{"class":96},[82,7915,7916,7918,7920,7922,7924],{"class":84,"line":453},[82,7917,456],{"class":96},[82,7919,141],{"class":88},[82,7921,422],{"class":96},[82,7923,406],{"class":88},[82,7925,7926],{"class":96}," heuristic(neighbor, goal_node)\n",[82,7928,7929],{"class":84,"line":468},[82,7930,7931],{"class":96},"                frontier.append((f_score, neighbor))\n",[82,7933,7934],{"class":84,"line":474},[82,7935,222],{"emptyLinePlaceholder":221},[82,7937,7938],{"class":84,"line":479},[82,7939,482],{"class":258},[82,7941,7942,7944,7946],{"class":84,"line":485},[82,7943,488],{"class":96},[82,7945,141],{"class":88},[82,7947,493],{"class":96},[82,7949,7950,7952,7954],{"class":84,"line":496},[82,7951,499],{"class":96},[82,7953,141],{"class":88},[82,7955,504],{"class":96},[82,7957,7958,7960,7962,7964,7966,7968],{"class":84,"line":507},[82,7959,270],{"class":88},[82,7961,512],{"class":96},[82,7963,515],{"class":88},[82,7965,518],{"class":88},[82,7967,189],{"class":100},[82,7969,523],{"class":96},[82,7971,7972],{"class":84,"line":526},[82,7973,529],{"class":96},[82,7975,7976,7978,7980],{"class":84,"line":532},[82,7977,535],{"class":96},[82,7979,141],{"class":88},[82,7981,540],{"class":96},[82,7983,7984],{"class":84,"line":543},[82,7985,546],{"class":96},[82,7987,7988,7990],{"class":84,"line":549},[82,7989,568],{"class":88},[82,7991,2388],{"class":96},[82,7993,7994],{"class":84,"line":554},[82,7995,222],{"emptyLinePlaceholder":221},[82,7997,7998],{"class":84,"line":565},[82,7999,222],{"emptyLinePlaceholder":221},[82,8001,8002,8004,8006,8008,8010,8012,8014,8017,8019,8021,8023],{"class":84,"line":574},[82,8003,89],{"class":88},[82,8005,589],{"class":92},[82,8007,592],{"class":96},[82,8009,101],{"class":100},[82,8011,597],{"class":96},[82,8013,101],{"class":100},[82,8015,8016],{"class":96},", grid_cols: ",[82,8018,101],{"class":100},[82,8020,607],{"class":96},[82,8022,101],{"class":100},[82,8024,523],{"class":96},[82,8026,8027],{"class":84,"line":579},[82,8028,8029],{"class":125},"    \"\"\"Admissible heuristic for grid-based pathfinding.\"\"\"\n",[82,8031,8032,8034,8036,8038,8040,8043,8045],{"class":84,"line":584},[82,8033,623],{"class":96},[82,8035,141],{"class":88},[82,8037,628],{"class":96},[82,8039,631],{"class":88},[82,8041,8042],{"class":96}," grid_cols, node_a ",[82,8044,637],{"class":88},[82,8046,8047],{"class":96}," grid_cols\n",[82,8049,8050,8052,8054,8056,8058,8061,8063],{"class":84,"line":614},[82,8051,646],{"class":96},[82,8053,141],{"class":88},[82,8055,651],{"class":96},[82,8057,631],{"class":88},[82,8059,8060],{"class":96}," grid_cols, node_b ",[82,8062,637],{"class":88},[82,8064,8047],{"class":96},[82,8066,8067,8069,8071,8073,8075,8077,8079,8081,8083,8085],{"class":84,"line":620},[82,8068,568],{"class":88},[82,8070,668],{"class":100},[82,8072,671],{"class":96},[82,8074,186],{"class":88},[82,8076,676],{"class":96},[82,8078,406],{"class":88},[82,8080,668],{"class":100},[82,8082,683],{"class":96},[82,8084,186],{"class":88},[82,8086,688],{"class":96},[24,8088,8090],{"id":8089},"when-to-use-which","When to Use Which",[731,8092,8093,8106],{},[734,8094,8095],{},[737,8096,8097,8100,8103],{},[740,8098,8099],{},"Scenario",[740,8101,8102],{},"Algorithm",[740,8104,8105],{},"Why",[750,8107,8108,8118,8128,8138],{},[737,8109,8110,8113,8115],{},[755,8111,8112],{},"Unweighted graph",[755,8114,3049],{},[755,8116,8117],{},"Simpler, same result as Dijkstra with weight=1",[737,8119,8120,8123,8125],{},[755,8121,8122],{},"Weighted graph, no goal info",[755,8124,745],{},[755,8126,8127],{},"Explores uniformly by cost",[737,8129,8130,8133,8135],{},[755,8131,8132],{},"Weighted graph, known goal position",[755,8134,748],{},[755,8136,8137],{},"Fewer nodes explored with good heuristic",[737,8139,8140,8143,8146],{},[755,8141,8142],{},"Negative edge weights",[755,8144,8145],{},"Neither",[755,8147,8148],{},"Use Bellman-Ford instead",[24,8150,811],{"id":810},[15,8152,8153],{},"On a weighted maze, Dijkstra explores in expanding cost-circles (avoiding expensive edges), while A* focuses exploration toward the exit. Both find the same cheapest path, but A* gets there by exploring fewer cells.",[850,8155,8156],{},"html pre.shiki code .snl16, html code.shiki .snl16{--shiki-default:#F97583}html pre.shiki code .svObZ, html code.shiki .svObZ{--shiki-default:#B392F0}html pre.shiki code .s95oV, html code.shiki .s95oV{--shiki-default:#E1E4E8}html pre.shiki code .sDLfK, html code.shiki .sDLfK{--shiki-default:#79B8FF}html pre.shiki code .sU2Wk, html code.shiki .sU2Wk{--shiki-default:#9ECBFF}html .default .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html pre.shiki code .sAwPA, html code.shiki .sAwPA{--shiki-default:#6A737D}",{"title":41,"searchDepth":122,"depth":122,"links":8158},[8159,8162,8165,8166,8167,8168,8169],{"id":6575,"depth":122,"text":6570,"children":8160},[8161],{"id":1997,"depth":129,"text":1998},{"id":7125,"depth":122,"text":7126,"children":8163},[8164],{"id":7158,"depth":129,"text":1998},{"id":2523,"depth":122,"text":2524},{"id":7316,"depth":122,"text":7317},{"id":7648,"depth":122,"text":7649},{"id":8089,"depth":122,"text":8090},{"id":810,"depth":122,"text":811},"Understand weighted shortest-path algorithms: how Dijkstra explores uniformly by cost, and how A* uses heuristics to search smarter.",{"timeComplexity":867,"spaceComplexity":868},"\u002Flearn\u002Fdijkstra-and-astar",{"title":7086,"description":8170},"learn\u002Fdijkstra-and-astar","zlqfXE6FVJ0xJs7QzINVQMzT6DkuR5ILwush6Brvq40",{"id":8177,"title":8178,"body":8179,"category":2073,"complexity":862,"date":862,"description":9178,"difficulty":864,"extension":865,"meta":9179,"navigation":221,"order":122,"path":9180,"publishedAt":9181,"relatedAlgorithmId":9182,"seo":9183,"stem":9184,"__hash__":9185},"learn\u002Flearn\u002Fdynamic-programming.md","Dynamic Programming",{"type":8,"value":8180,"toc":9161},[8181,8184,8195,8199,8202,8216,8220,8224,8227,8329,8333,8336,8469,8476,8480,8483,8486,8492,8495,8501,8508,8510,8515,8526,8579,8583,8586,8654,8658,8726,8729,8731,8735,8742,8877,8881,8888,9056,9060,9086,9088,9108,9110,9158],[11,8182,8178],{"id":8183},"dynamic-programming",[15,8185,8186,8187,8190,8191,8194],{},"Dynamic programming (DP) is a technique for solving problems by breaking them into smaller ",[19,8188,8189],{},"overlapping subproblems",", solving each subproblem once, and ",[19,8192,8193],{},"reusing"," the stored result whenever the same subproblem appears again. It turns exponential-time recursive solutions into polynomial-time ones by trading a small amount of memory for a large amount of repeated work.",[24,8196,8198],{"id":8197},"when-does-dp-apply","When Does DP Apply?",[15,8200,8201],{},"A problem is a good candidate for dynamic programming when it has both of these properties:",[895,8203,8204,8210],{},[46,8205,8206,8209],{},[19,8207,8208],{},"Overlapping subproblems",": the same smaller problems are solved repeatedly. (If subproblems never repeat, plain divide-and-conquer is enough.)",[46,8211,8212,8215],{},[19,8213,8214],{},"Optimal substructure",": an optimal solution to the whole problem can be built from optimal solutions to its subproblems.",[24,8217,8219],{"id":8218},"two-ways-to-apply-dp","Two Ways to Apply DP",[1024,8221,8223],{"id":8222},"top-down-memoization","Top-Down (Memoization)",[15,8225,8226],{},"Write the natural recursion, then cache each result the first time it is computed. Subsequent calls return the cached value instead of recomputing.",[32,8228,8230],{"className":76,"code":8229,"language":78,"meta":41,"style":41},"from functools import lru_cache\n\n@lru_cache(maxsize=None)\ndef fib(n: int) -> int:\n    if n \u003C 2:\n        return n\n    return fib(n - 1) + fib(n - 2)\n",[39,8231,8232,8246,8250,8267,8284,8298,8305],{"__ignoreMap":41},[82,8233,8234,8237,8240,8243],{"class":84,"line":85},[82,8235,8236],{"class":88},"from",[82,8238,8239],{"class":96}," functools ",[82,8241,8242],{"class":88},"import",[82,8244,8245],{"class":96}," lru_cache\n",[82,8247,8248],{"class":84,"line":122},[82,8249,222],{"emptyLinePlaceholder":221},[82,8251,8252,8255,8257,8261,8263,8265],{"class":84,"line":129},[82,8253,8254],{"class":92},"@lru_cache",[82,8256,161],{"class":96},[82,8258,8260],{"class":8259},"s9osk","maxsize",[82,8262,141],{"class":88},[82,8264,1188],{"class":100},[82,8266,296],{"class":96},[82,8268,8269,8271,8274,8276,8278,8280,8282],{"class":84,"line":135},[82,8270,89],{"class":88},[82,8272,8273],{"class":92}," fib",[82,8275,1060],{"class":96},[82,8277,101],{"class":100},[82,8279,607],{"class":96},[82,8281,101],{"class":100},[82,8283,523],{"class":96},[82,8285,8286,8288,8291,8293,8296],{"class":84,"line":147},[82,8287,960],{"class":88},[82,8289,8290],{"class":96}," n ",[82,8292,425],{"class":88},[82,8294,8295],{"class":100}," 2",[82,8297,523],{"class":96},[82,8299,8300,8302],{"class":84,"line":176},[82,8301,2655],{"class":88},[82,8303,8304],{"class":96}," n\n",[82,8306,8307,8309,8312,8314,8316,8319,8321,8323,8325,8327],{"class":84,"line":199},[82,8308,568],{"class":88},[82,8310,8311],{"class":96}," fib(n ",[82,8313,186],{"class":88},[82,8315,1348],{"class":100},[82,8317,8318],{"class":96},") ",[82,8320,406],{"class":88},[82,8322,8311],{"class":96},[82,8324,186],{"class":88},[82,8326,8295],{"class":100},[82,8328,296],{"class":96},[1024,8330,8332],{"id":8331},"bottom-up-tabulation","Bottom-Up (Tabulation)",[15,8334,8335],{},"Fill a table starting from the base cases and building up to the answer. There is no recursion — just a loop that computes each entry from earlier entries.",[32,8337,8339],{"className":76,"code":8338,"language":78,"meta":41,"style":41},"def fib(n: int) -> int:\n    if n \u003C 2:\n        return n\n    dp = [0] * (n + 1)\n    dp[1] = 1\n    for i in range(2, n + 1):\n        dp[i] = dp[i - 1] + dp[i - 2]\n    return dp[n]\n",[39,8340,8341,8357,8369,8375,8399,8412,8436,8462],{"__ignoreMap":41},[82,8342,8343,8345,8347,8349,8351,8353,8355],{"class":84,"line":85},[82,8344,89],{"class":88},[82,8346,8273],{"class":92},[82,8348,1060],{"class":96},[82,8350,101],{"class":100},[82,8352,607],{"class":96},[82,8354,101],{"class":100},[82,8356,523],{"class":96},[82,8358,8359,8361,8363,8365,8367],{"class":84,"line":122},[82,8360,960],{"class":88},[82,8362,8290],{"class":96},[82,8364,425],{"class":88},[82,8366,8295],{"class":100},[82,8368,523],{"class":96},[82,8370,8371,8373],{"class":84,"line":129},[82,8372,2655],{"class":88},[82,8374,8304],{"class":96},[82,8376,8377,8380,8382,8384,8386,8388,8390,8393,8395,8397],{"class":84,"line":135},[82,8378,8379],{"class":96},"    dp ",[82,8381,141],{"class":88},[82,8383,155],{"class":96},[82,8385,293],{"class":100},[82,8387,192],{"class":96},[82,8389,170],{"class":88},[82,8391,8392],{"class":96}," (n ",[82,8394,406],{"class":88},[82,8396,1348],{"class":100},[82,8398,296],{"class":96},[82,8400,8401,8404,8406,8408,8410],{"class":84,"line":147},[82,8402,8403],{"class":96},"    dp[",[82,8405,189],{"class":100},[82,8407,192],{"class":96},[82,8409,141],{"class":88},[82,8411,2260],{"class":100},[82,8413,8414,8416,8418,8420,8422,8424,8427,8430,8432,8434],{"class":84,"line":176},[82,8415,982],{"class":88},[82,8417,1536],{"class":96},[82,8419,369],{"class":88},[82,8421,1228],{"class":100},[82,8423,161],{"class":96},[82,8425,8426],{"class":100},"2",[82,8428,8429],{"class":96},", n ",[82,8431,406],{"class":88},[82,8433,1348],{"class":100},[82,8435,2554],{"class":96},[82,8437,8438,8441,8443,8446,8448,8450,8452,8454,8456,8458,8460],{"class":84,"line":199},[82,8439,8440],{"class":96},"        dp[i] ",[82,8442,141],{"class":88},[82,8444,8445],{"class":96}," dp[i ",[82,8447,186],{"class":88},[82,8449,1348],{"class":100},[82,8451,192],{"class":96},[82,8453,406],{"class":88},[82,8455,8445],{"class":96},[82,8457,186],{"class":88},[82,8459,8295],{"class":100},[82,8461,3224],{"class":96},[82,8463,8464,8466],{"class":84,"line":218},[82,8465,568],{"class":88},[82,8467,8468],{"class":96}," dp[n]\n",[15,8470,8471,8472,8475],{},"Both run in O(n) time. The bottom-up version is what the interactive visualizer animates: each cell ",[39,8473,8474],{},"dp[i]"," is filled from the two cells before it.",[24,8477,8479],{"id":8478},"worked-example-fibonacci","Worked Example: Fibonacci",[15,8481,8482],{},"The Fibonacci sequence is the classic first example because the naive recursion is spectacularly wasteful, and DP fixes it cleanly.",[15,8484,8485],{},"The naive recursion recomputes the same values over and over:",[32,8487,8490],{"className":8488,"code":8489,"language":37,"meta":41},[35],"                     fib(5)\n              \u002F                  \\\n          fib(4)                fib(3)\n         \u002F      \\              \u002F      \\\n     fib(3)    fib(2)      fib(2)    fib(1)\n     \u002F    \\    \u002F    \\      \u002F    \\\n fib(2) fib(1) ...        ...\n\nfib(3) is computed twice, fib(2) three times, and it gets worse as n grows.\n",[39,8491,8489],{"__ignoreMap":41},[15,8493,8494],{},"Dynamic programming computes each value exactly once. Building the table bottom-up:",[32,8496,8499],{"className":8497,"code":8498,"language":37,"meta":41},[35],"i:      0    1    2    3    4    5    6    7\ndp[i]:  0    1    1    2    3    5    8   13\n                  ^\n                  dp[2] = dp[1] + dp[0] = 1 + 0 = 1\n",[39,8500,8498],{"__ignoreMap":41},[15,8502,8503,8504,8507],{},"Each entry is the sum of the two preceding entries: ",[39,8505,8506],{},"dp[i] = dp[i-1] + dp[i-2]",". The final answer is the last cell.",[24,8509,1816],{"id":1815},[15,8511,8512],{},[19,8513,8514],{},"Time Complexity: O(n)",[15,8516,8517,8518,8521,8522,8525],{},"Naive recursion makes roughly ",[39,8519,8520],{},"fib(n)"," calls, which grows as O(2^n). DP computes each of the ",[39,8523,8524],{},"n + 1"," table entries once, so the runtime is linear.",[731,8527,8528,8538],{},[734,8529,8530],{},[737,8531,8532,8534,8536],{},[740,8533,1862],{},[740,8535,2048],{},[740,8537,2429],{},[750,8539,8540,8551,8561,8570],{},[737,8541,8542,8545,8548],{},[755,8543,8544],{},"Naive recursion",[755,8546,8547],{},"O(2^n)",[755,8549,8550],{},"O(n) stack",[737,8552,8553,8556,8558],{},[755,8554,8555],{},"Memoization (top-down)",[755,8557,2077],{},[755,8559,8560],{},"O(n) + O(n) stack",[737,8562,8563,8566,8568],{},[755,8564,8565],{},"Tabulation (bottom-up)",[755,8567,2077],{},[755,8569,2077],{},[737,8571,8572,8575,8577],{},[755,8573,8574],{},"Tabulation, rolling variables",[755,8576,2077],{},[755,8578,3903],{},[15,8580,8581],{},[19,8582,1846],{},[15,8584,8585],{},"The DP table stores one value per index. When only the last two values are needed — as in Fibonacci — the table can be replaced by two rolling variables to reach O(1) space:",[32,8587,8589],{"className":76,"code":8588,"language":78,"meta":41,"style":41},"def fib(n: int) -> int:\n    prev, curr = 0, 1\n    for _ in range(n):\n        prev, curr = curr, prev + curr\n    return prev\n",[39,8590,8591,8607,8620,8632,8647],{"__ignoreMap":41},[82,8592,8593,8595,8597,8599,8601,8603,8605],{"class":84,"line":85},[82,8594,89],{"class":88},[82,8596,8273],{"class":92},[82,8598,1060],{"class":96},[82,8600,101],{"class":100},[82,8602,607],{"class":96},[82,8604,101],{"class":100},[82,8606,523],{"class":96},[82,8608,8609,8612,8614,8616,8618],{"class":84,"line":122},[82,8610,8611],{"class":96},"    prev, curr ",[82,8613,141],{"class":88},[82,8615,1699],{"class":100},[82,8617,7295],{"class":96},[82,8619,3395],{"class":100},[82,8621,8622,8624,8626,8628,8630],{"class":84,"line":129},[82,8623,982],{"class":88},[82,8625,2584],{"class":96},[82,8627,369],{"class":88},[82,8629,1228],{"class":100},[82,8631,1231],{"class":96},[82,8633,8634,8637,8639,8642,8644],{"class":84,"line":135},[82,8635,8636],{"class":96},"        prev, curr ",[82,8638,141],{"class":88},[82,8640,8641],{"class":96}," curr, prev ",[82,8643,406],{"class":88},[82,8645,8646],{"class":96}," curr\n",[82,8648,8649,8651],{"class":84,"line":147},[82,8650,568],{"class":88},[82,8652,8653],{"class":96}," prev\n",[24,8655,8657],{"id":8656},"memoization-vs-tabulation","Memoization vs. Tabulation",[731,8659,8660,8671],{},[734,8661,8662],{},[737,8663,8664,8667,8669],{},[740,8665,8666],{},"Aspect",[740,8668,8555],{},[740,8670,8565],{},[750,8672,8673,8684,8694,8705,8716],{},[737,8674,8675,8678,8681],{},[755,8676,8677],{},"Style",[755,8679,8680],{},"Recursion + cache",[755,8682,8683],{},"Iterative table fill",[737,8685,8686,8688,8691],{},[755,8687,5566],{},[755,8689,8690],{},"Computes only needed subproblems",[755,8692,8693],{},"Computes all subproblems in order",[737,8695,8696,8699,8702],{},[755,8697,8698],{},"Overhead",[755,8700,8701],{},"Recursion\u002Fcall-stack cost",[755,8703,8704],{},"No recursion",[737,8706,8707,8710,8713],{},[755,8708,8709],{},"Readability",[755,8711,8712],{},"Mirrors the natural recurrence",[755,8714,8715],{},"Requires choosing a fill order",[737,8717,8718,8721,8724],{},[755,8719,8720],{},"Risk",[755,8722,8723],{},"Stack overflow for large n",[755,8725,1188],{},[15,8727,8728],{},"Choose memoization when the recurrence is easy to express and not all subproblems are needed. Choose tabulation when you want to avoid recursion or reduce space with a rolling window.",[24,8730,1411],{"id":1410},[1024,8732,8734],{"id":8733},"climbing-stairs","Climbing Stairs",[15,8736,8737,8738,8741],{},"Count the ways to climb ",[39,8739,8740],{},"n"," steps taking 1 or 2 steps at a time — the same recurrence as Fibonacci.",[32,8743,8745],{"className":76,"code":8744,"language":78,"meta":41,"style":41},"def climb_stairs(n: int) -> int:\n    if n \u003C 2:\n        return 1\n    dp = [0] * (n + 1)\n    dp[0] = dp[1] = 1\n    for i in range(2, n + 1):\n        dp[i] = dp[i - 1] + dp[i - 2]\n    return dp[n]\n",[39,8746,8747,8764,8776,8782,8804,8825,8847,8871],{"__ignoreMap":41},[82,8748,8749,8751,8754,8756,8758,8760,8762],{"class":84,"line":85},[82,8750,89],{"class":88},[82,8752,8753],{"class":92}," climb_stairs",[82,8755,1060],{"class":96},[82,8757,101],{"class":100},[82,8759,607],{"class":96},[82,8761,101],{"class":100},[82,8763,523],{"class":96},[82,8765,8766,8768,8770,8772,8774],{"class":84,"line":122},[82,8767,960],{"class":88},[82,8769,8290],{"class":96},[82,8771,425],{"class":88},[82,8773,8295],{"class":100},[82,8775,523],{"class":96},[82,8777,8778,8780],{"class":84,"line":129},[82,8779,2655],{"class":88},[82,8781,2260],{"class":100},[82,8783,8784,8786,8788,8790,8792,8794,8796,8798,8800,8802],{"class":84,"line":135},[82,8785,8379],{"class":96},[82,8787,141],{"class":88},[82,8789,155],{"class":96},[82,8791,293],{"class":100},[82,8793,192],{"class":96},[82,8795,170],{"class":88},[82,8797,8392],{"class":96},[82,8799,406],{"class":88},[82,8801,1348],{"class":100},[82,8803,296],{"class":96},[82,8805,8806,8808,8810,8812,8814,8817,8819,8821,8823],{"class":84,"line":147},[82,8807,8403],{"class":96},[82,8809,293],{"class":100},[82,8811,192],{"class":96},[82,8813,141],{"class":88},[82,8815,8816],{"class":96}," dp[",[82,8818,189],{"class":100},[82,8820,192],{"class":96},[82,8822,141],{"class":88},[82,8824,2260],{"class":100},[82,8826,8827,8829,8831,8833,8835,8837,8839,8841,8843,8845],{"class":84,"line":176},[82,8828,982],{"class":88},[82,8830,1536],{"class":96},[82,8832,369],{"class":88},[82,8834,1228],{"class":100},[82,8836,161],{"class":96},[82,8838,8426],{"class":100},[82,8840,8429],{"class":96},[82,8842,406],{"class":88},[82,8844,1348],{"class":100},[82,8846,2554],{"class":96},[82,8848,8849,8851,8853,8855,8857,8859,8861,8863,8865,8867,8869],{"class":84,"line":199},[82,8850,8440],{"class":96},[82,8852,141],{"class":88},[82,8854,8445],{"class":96},[82,8856,186],{"class":88},[82,8858,1348],{"class":100},[82,8860,192],{"class":96},[82,8862,406],{"class":88},[82,8864,8445],{"class":96},[82,8866,186],{"class":88},[82,8868,8295],{"class":100},[82,8870,3224],{"class":96},[82,8872,8873,8875],{"class":84,"line":218},[82,8874,568],{"class":88},[82,8876,8468],{"class":96},[1024,8878,8880],{"id":8879},"coin-change-minimum-coins","Coin Change (Minimum Coins)",[15,8882,8883,8884,8887],{},"Find the fewest coins that sum to ",[39,8885,8886],{},"amount",", or -1 if impossible.",[32,8889,8891],{"className":76,"code":8890,"language":78,"meta":41,"style":41},"def coin_change(coins: list[int], amount: int) -> int:\n    dp = [float(\"inf\")] * (amount + 1)\n    dp[0] = 0\n    for value in range(1, amount + 1):\n        for coin in coins:\n            if coin \u003C= value:\n                dp[value] = min(dp[value], dp[value - coin] + 1)\n    return dp[amount] if dp[amount] != float(\"inf\") else -1\n",[39,8892,8893,8916,8944,8956,8979,8991,9002,9026],{"__ignoreMap":41},[82,8894,8895,8897,8900,8903,8905,8908,8910,8912,8914],{"class":84,"line":85},[82,8896,89],{"class":88},[82,8898,8899],{"class":92}," coin_change",[82,8901,8902],{"class":96},"(coins: list[",[82,8904,101],{"class":100},[82,8906,8907],{"class":96},"], amount: ",[82,8909,101],{"class":100},[82,8911,607],{"class":96},[82,8913,101],{"class":100},[82,8915,523],{"class":96},[82,8917,8918,8920,8922,8924,8926,8928,8931,8933,8935,8938,8940,8942],{"class":84,"line":122},[82,8919,8379],{"class":96},[82,8921,141],{"class":88},[82,8923,155],{"class":96},[82,8925,158],{"class":100},[82,8927,161],{"class":96},[82,8929,8930],{"class":125},"\"inf\"",[82,8932,167],{"class":96},[82,8934,170],{"class":88},[82,8936,8937],{"class":96}," (amount ",[82,8939,406],{"class":88},[82,8941,1348],{"class":100},[82,8943,296],{"class":96},[82,8945,8946,8948,8950,8952,8954],{"class":84,"line":129},[82,8947,8403],{"class":96},[82,8949,293],{"class":100},[82,8951,192],{"class":96},[82,8953,141],{"class":88},[82,8955,233],{"class":100},[82,8957,8958,8960,8962,8964,8966,8968,8970,8973,8975,8977],{"class":84,"line":135},[82,8959,982],{"class":88},[82,8961,4855],{"class":96},[82,8963,369],{"class":88},[82,8965,1228],{"class":100},[82,8967,161],{"class":96},[82,8969,189],{"class":100},[82,8971,8972],{"class":96},", amount ",[82,8974,406],{"class":88},[82,8976,1348],{"class":100},[82,8978,2554],{"class":96},[82,8980,8981,8983,8986,8988],{"class":84,"line":147},[82,8982,363],{"class":88},[82,8984,8985],{"class":96}," coin ",[82,8987,369],{"class":88},[82,8989,8990],{"class":96}," coins:\n",[82,8992,8993,8995,8997,8999],{"class":84,"line":176},[82,8994,378],{"class":88},[82,8996,8985],{"class":96},[82,8998,3298],{"class":88},[82,9000,9001],{"class":96}," value:\n",[82,9003,9004,9007,9009,9012,9015,9017,9020,9022,9024],{"class":84,"line":199},[82,9005,9006],{"class":96},"                dp[value] ",[82,9008,141],{"class":88},[82,9010,9011],{"class":100}," min",[82,9013,9014],{"class":96},"(dp[value], dp[value ",[82,9016,186],{"class":88},[82,9018,9019],{"class":96}," coin] ",[82,9021,406],{"class":88},[82,9023,1348],{"class":100},[82,9025,296],{"class":96},[82,9027,9028,9030,9033,9036,9038,9040,9043,9045,9047,9049,9052,9054],{"class":84,"line":218},[82,9029,568],{"class":88},[82,9031,9032],{"class":96}," dp[amount] ",[82,9034,9035],{"class":88},"if",[82,9037,9032],{"class":96},[82,9039,515],{"class":88},[82,9041,9042],{"class":100}," float",[82,9044,161],{"class":96},[82,9046,8930],{"class":125},[82,9048,8318],{"class":96},[82,9050,9051],{"class":88},"else",[82,9053,518],{"class":88},[82,9055,3395],{"class":100},[24,9057,9059],{"id":9058},"when-to-use-dynamic-programming","When to Use Dynamic Programming",[43,9061,9062,9068,9074,9080],{},[46,9063,9064,9067],{},[19,9065,9066],{},"Counting problems",": number of ways to reach a state (climbing stairs, paths in a grid).",[46,9069,9070,9073],{},[19,9071,9072],{},"Optimization with substructure",": shortest path, minimum cost, longest subsequence.",[46,9075,9076,9079],{},[19,9077,9078],{},"Sequence problems",": longest common subsequence, edit distance, longest increasing subsequence.",[46,9081,9082,9085],{},[19,9083,9084],{},"Resource allocation",": knapsack, partitioning, scheduling.",[24,9087,1938],{"id":1937},[43,9089,9090,9096,9102],{},[46,9091,9092,9095],{},[19,9093,9094],{},"No overlapping subproblems",": plain divide-and-conquer (e.g. merge sort) is simpler and just as fast.",[46,9097,9098,9101],{},[19,9099,9100],{},"A greedy choice is provably optimal",": greedy is faster and uses less memory.",[46,9103,9104,9107],{},[19,9105,9106],{},"The state space is too large",": if the table would not fit in memory, consider approximation or a different formulation.",[24,9109,1998],{"id":1997},[731,9111,9112,9120],{},[734,9113,9114],{},[737,9115,9116,9118],{},[740,9117,742],{},[740,9119,2009],{},[750,9121,9122,9129,9135,9143,9151],{},[737,9123,9124,9126],{},[755,9125,2016],{},[755,9127,9128],{},"Reuse of overlapping subproblems",[737,9130,9131,9133],{},[755,9132,790],{},[755,9134,8214],{},[737,9136,9137,9140],{},[755,9138,9139],{},"Styles",[755,9141,9142],{},"Top-down (memoization), bottom-up (tabulation)",[737,9144,9145,9148],{},[755,9146,9147],{},"Typical time",[755,9149,9150],{},"Polynomial (often O(n) or O(n·m))",[737,9152,9153,9155],{},[755,9154,2429],{},[755,9156,9157],{},"Size of the state table (often reducible)",[850,9159,9160],{},"html pre.shiki code .snl16, html code.shiki .snl16{--shiki-default:#F97583}html pre.shiki code .s95oV, html code.shiki .s95oV{--shiki-default:#E1E4E8}html pre.shiki code .svObZ, html code.shiki .svObZ{--shiki-default:#B392F0}html pre.shiki code .s9osk, html code.shiki .s9osk{--shiki-default:#FFAB70}html pre.shiki code .sDLfK, html code.shiki .sDLfK{--shiki-default:#79B8FF}html .default .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html pre.shiki code .sU2Wk, html code.shiki .sU2Wk{--shiki-default:#9ECBFF}",{"title":41,"searchDepth":122,"depth":122,"links":9162},[9163,9164,9168,9169,9170,9171,9175,9176,9177],{"id":8197,"depth":122,"text":8198},{"id":8218,"depth":122,"text":8219,"children":9165},[9166,9167],{"id":8222,"depth":129,"text":8223},{"id":8331,"depth":129,"text":8332},{"id":8478,"depth":122,"text":8479},{"id":1815,"depth":122,"text":1816},{"id":8656,"depth":122,"text":8657},{"id":1410,"depth":122,"text":1411,"children":9172},[9173,9174],{"id":8733,"depth":129,"text":8734},{"id":8879,"depth":129,"text":8880},{"id":9058,"depth":122,"text":9059},{"id":1937,"depth":122,"text":1938},{"id":1997,"depth":122,"text":1998},"Learn dynamic programming — solving problems by breaking them into overlapping subproblems and reusing results, illustrated with the Fibonacci sequence.",{"timeComplexity":2077,"spaceComplexity":2077},"\u002Flearn\u002Fdynamic-programming","2026-09-01","fibonacci",{"title":8178,"description":9178},"learn\u002Fdynamic-programming","qfUeACQUK4vsGdoWepAdRtagwWVuOvzZh59zBm8jXyw",{"id":9187,"title":9188,"body":9189,"category":9638,"complexity":862,"date":862,"description":9639,"difficulty":864,"extension":865,"meta":9640,"navigation":221,"order":85,"path":9641,"publishedAt":870,"relatedAlgorithmId":9642,"seo":9643,"stem":9644,"__hash__":9645},"learn\u002Flearn\u002Ffast-slow-pointers.md","Fast and Slow Pointers",{"type":8,"value":9190,"toc":9630},[9191,9194,9197,9201,9215,9218,9222,9350,9354,9357,9561,9565,9571,9577,9581,9613,9617,9625,9628],[11,9192,9188],{"id":9193},"fast-and-slow-pointers",[15,9195,9196],{},"The fast and slow pointer technique (also called Floyd's tortoise and hare) uses two pointers moving at different speeds through a sequence. The speed difference creates useful properties: the slow pointer lands at the middle when fast reaches the end, and if there's a cycle, the two pointers will eventually meet.",[24,9198,9200],{"id":9199},"core-idea","Core Idea",[43,9202,9203,9209],{},[46,9204,9205,9208],{},[19,9206,9207],{},"Slow pointer"," moves 1 step per iteration",[46,9210,9211,9214],{},[19,9212,9213],{},"Fast pointer"," moves 2 steps per iteration",[15,9216,9217],{},"When fast reaches the end of the array (or list), slow is exactly at the midpoint. This happens because fast covers twice the distance in the same number of iterations.",[24,9219,9221],{"id":9220},"code-snippet-finding-the-middle","Code Snippet — Finding the Middle",[32,9223,9225],{"className":76,"code":9224,"language":78,"meta":41,"style":41},"def find_middle_element(numbers: list[int]) -> int:\n    \"\"\"Find the middle element using two pointers at different speeds.\"\"\"\n    slow_index = 0\n    fast_index = 0\n\n    while fast_index \u003C len(numbers) - 1:\n        slow_index += 1       # slow moves 1 step\n        fast_index += 2       # fast moves 2 steps\n\n        # Prevent fast from going out of bounds\n        if fast_index >= len(numbers):\n            break\n\n    return numbers[slow_index]\n",[39,9226,9227,9244,9249,9258,9267,9271,9290,9302,9314,9318,9323,9335,9339,9343],{"__ignoreMap":41},[82,9228,9229,9231,9234,9236,9238,9240,9242],{"class":84,"line":85},[82,9230,89],{"class":88},[82,9232,9233],{"class":92}," find_middle_element",[82,9235,1627],{"class":96},[82,9237,101],{"class":100},[82,9239,3417],{"class":96},[82,9241,101],{"class":100},[82,9243,523],{"class":96},[82,9245,9246],{"class":84,"line":122},[82,9247,9248],{"class":125},"    \"\"\"Find the middle element using two pointers at different speeds.\"\"\"\n",[82,9250,9251,9254,9256],{"class":84,"line":129},[82,9252,9253],{"class":96},"    slow_index ",[82,9255,141],{"class":88},[82,9257,233],{"class":100},[82,9259,9260,9263,9265],{"class":84,"line":135},[82,9261,9262],{"class":96},"    fast_index ",[82,9264,141],{"class":88},[82,9266,233],{"class":100},[82,9268,9269],{"class":84,"line":147},[82,9270,222],{"emptyLinePlaceholder":221},[82,9272,9273,9275,9278,9280,9282,9284,9286,9288],{"class":84,"line":176},[82,9274,270],{"class":88},[82,9276,9277],{"class":96}," fast_index ",[82,9279,425],{"class":88},[82,9281,1471],{"class":100},[82,9283,3521],{"class":96},[82,9285,186],{"class":88},[82,9287,1348],{"class":100},[82,9289,523],{"class":96},[82,9291,9292,9295,9297,9299],{"class":84,"line":199},[82,9293,9294],{"class":96},"        slow_index ",[82,9296,2257],{"class":88},[82,9298,1348],{"class":100},[82,9300,9301],{"class":258},"       # slow moves 1 step\n",[82,9303,9304,9307,9309,9311],{"class":84,"line":218},[82,9305,9306],{"class":96},"        fast_index ",[82,9308,2257],{"class":88},[82,9310,8295],{"class":100},[82,9312,9313],{"class":258},"       # fast moves 2 steps\n",[82,9315,9316],{"class":84,"line":225},[82,9317,222],{"emptyLinePlaceholder":221},[82,9319,9320],{"class":84,"line":236},[82,9321,9322],{"class":258},"        # Prevent fast from going out of bounds\n",[82,9324,9325,9327,9329,9331,9333],{"class":84,"line":247},[82,9326,307],{"class":88},[82,9328,9277],{"class":96},[82,9330,1728],{"class":88},[82,9332,1471],{"class":100},[82,9334,1733],{"class":96},[82,9336,9337],{"class":84,"line":262},[82,9338,352],{"class":88},[82,9340,9341],{"class":84,"line":267},[82,9342,222],{"emptyLinePlaceholder":221},[82,9344,9345,9347],{"class":84,"line":276},[82,9346,568],{"class":88},[82,9348,9349],{"class":96}," numbers[slow_index]\n",[24,9351,9353],{"id":9352},"code-snippet-cycle-detection-floyds-algorithm","Code Snippet — Cycle Detection (Floyd's Algorithm)",[15,9355,9356],{},"For linked-list-style problems where you follow \"next\" pointers:",[32,9358,9360],{"className":76,"code":9359,"language":78,"meta":41,"style":41},"def has_cycle(next_pointers: list[int], start: int) -> bool:\n    \"\"\"Detect if following next_pointers from start leads to a cycle.\n    next_pointers[node] gives the next node, -1 means end.\"\"\"\n    slow_position = start\n    fast_position = start\n\n    while True:\n        # Move slow one step\n        slow_position = next_pointers[slow_position]\n        if slow_position == -1:\n            return False  # reached end, no cycle\n\n        # Move fast two steps\n        fast_position = next_pointers[fast_position]\n        if fast_position == -1:\n            return False\n        fast_position = next_pointers[fast_position]\n        if fast_position == -1:\n            return False\n\n        # If they meet, there's a cycle\n        if slow_position == fast_position:\n            return True\n",[39,9361,9362,9385,9390,9395,9405,9414,9418,9427,9432,9442,9457,9467,9471,9476,9486,9501,9507,9515,9529,9535,9539,9544,9555],{"__ignoreMap":41},[82,9363,9364,9366,9369,9372,9374,9377,9379,9381,9383],{"class":84,"line":85},[82,9365,89],{"class":88},[82,9367,9368],{"class":92}," has_cycle",[82,9370,9371],{"class":96},"(next_pointers: list[",[82,9373,101],{"class":100},[82,9375,9376],{"class":96},"], start: ",[82,9378,101],{"class":100},[82,9380,607],{"class":96},[82,9382,4921],{"class":100},[82,9384,523],{"class":96},[82,9386,9387],{"class":84,"line":122},[82,9388,9389],{"class":125},"    \"\"\"Detect if following next_pointers from start leads to a cycle.\n",[82,9391,9392],{"class":84,"line":129},[82,9393,9394],{"class":125},"    next_pointers[node] gives the next node, -1 means end.\"\"\"\n",[82,9396,9397,9400,9402],{"class":84,"line":135},[82,9398,9399],{"class":96},"    slow_position ",[82,9401,141],{"class":88},[82,9403,9404],{"class":96}," start\n",[82,9406,9407,9410,9412],{"class":84,"line":147},[82,9408,9409],{"class":96},"    fast_position ",[82,9411,141],{"class":88},[82,9413,9404],{"class":96},[82,9415,9416],{"class":84,"line":176},[82,9417,222],{"emptyLinePlaceholder":221},[82,9419,9420,9422,9425],{"class":84,"line":199},[82,9421,270],{"class":88},[82,9423,9424],{"class":100}," True",[82,9426,523],{"class":96},[82,9428,9429],{"class":84,"line":218},[82,9430,9431],{"class":258},"        # Move slow one step\n",[82,9433,9434,9437,9439],{"class":84,"line":225},[82,9435,9436],{"class":96},"        slow_position ",[82,9438,141],{"class":88},[82,9440,9441],{"class":96}," next_pointers[slow_position]\n",[82,9443,9444,9446,9449,9451,9453,9455],{"class":84,"line":236},[82,9445,307],{"class":88},[82,9447,9448],{"class":96}," slow_position ",[82,9450,343],{"class":88},[82,9452,518],{"class":88},[82,9454,189],{"class":100},[82,9456,523],{"class":96},[82,9458,9459,9461,9464],{"class":84,"line":247},[82,9460,3338],{"class":88},[82,9462,9463],{"class":100}," False",[82,9465,9466],{"class":258},"  # reached end, no cycle\n",[82,9468,9469],{"class":84,"line":262},[82,9470,222],{"emptyLinePlaceholder":221},[82,9472,9473],{"class":84,"line":267},[82,9474,9475],{"class":258},"        # Move fast two steps\n",[82,9477,9478,9481,9483],{"class":84,"line":276},[82,9479,9480],{"class":96},"        fast_position ",[82,9482,141],{"class":88},[82,9484,9485],{"class":96}," next_pointers[fast_position]\n",[82,9487,9488,9490,9493,9495,9497,9499],{"class":84,"line":282},[82,9489,307],{"class":88},[82,9491,9492],{"class":96}," fast_position ",[82,9494,343],{"class":88},[82,9496,518],{"class":88},[82,9498,189],{"class":100},[82,9500,523],{"class":96},[82,9502,9503,9505],{"class":84,"line":299},[82,9504,3338],{"class":88},[82,9506,1592],{"class":100},[82,9508,9509,9511,9513],{"class":84,"line":304},[82,9510,9480],{"class":96},[82,9512,141],{"class":88},[82,9514,9485],{"class":96},[82,9516,9517,9519,9521,9523,9525,9527],{"class":84,"line":313},[82,9518,307],{"class":88},[82,9520,9492],{"class":96},[82,9522,343],{"class":88},[82,9524,518],{"class":88},[82,9526,189],{"class":100},[82,9528,523],{"class":96},[82,9530,9531,9533],{"class":84,"line":319},[82,9532,3338],{"class":88},[82,9534,1592],{"class":100},[82,9536,9537],{"class":84,"line":330},[82,9538,222],{"emptyLinePlaceholder":221},[82,9540,9541],{"class":84,"line":335},[82,9542,9543],{"class":258},"        # If they meet, there's a cycle\n",[82,9545,9546,9548,9550,9552],{"class":84,"line":349},[82,9547,307],{"class":88},[82,9549,9448],{"class":96},[82,9551,343],{"class":88},[82,9553,9554],{"class":96}," fast_position:\n",[82,9556,9557,9559],{"class":84,"line":355},[82,9558,3338],{"class":88},[82,9560,327],{"class":100},[24,9562,9564],{"id":9563},"why-this-works","Why This Works",[15,9566,9567,9570],{},[19,9568,9569],{},"For midpoint finding",": After k iterations, slow is at position k and fast is at position 2k. When fast hits position n (the end), slow is at n\u002F2 (the middle).",[15,9572,9573,9576],{},[19,9574,9575],{},"For cycle detection",": If there's a cycle of length C, fast gains 1 position on slow per iteration. After at most C iterations inside the cycle, fast laps slow and they collide.",[24,9578,9580],{"id":9579},"applications","Applications",[43,9582,9583,9589,9595,9601,9607],{},[46,9584,9585,9588],{},[19,9586,9587],{},"Find middle of linked list"," — one pass, O(1) space",[46,9590,9591,9594],{},[19,9592,9593],{},"Detect cycles"," — in linked lists, sequences, or function iteration",[46,9596,9597,9600],{},[19,9598,9599],{},"Find cycle start"," — after detection, reset one pointer to start and move both at speed 1",[46,9602,9603,9606],{},[19,9604,9605],{},"Check if number is happy"," — repeated digit-square-sum either cycles or reaches 1",[46,9608,9609,9612],{},[19,9610,9611],{},"Palindrome linked list"," — find middle, reverse second half, compare",[24,9614,9616],{"id":9615},"time-and-space","Time and Space",[43,9618,9619,9622],{},[46,9620,9621],{},"Time: O(n) — each pointer traverses at most n elements",[46,9623,9624],{},"Space: O(1) — only two pointer variables, no extra data structures",[15,9626,9627],{},"This is the key advantage over alternatives like using a hash set for cycle detection (which needs O(n) space).",[850,9629,852],{},{"title":41,"searchDepth":122,"depth":122,"links":9631},[9632,9633,9634,9635,9636,9637],{"id":9199,"depth":122,"text":9200},{"id":9220,"depth":122,"text":9221},{"id":9352,"depth":122,"text":9353},{"id":9563,"depth":122,"text":9564},{"id":9579,"depth":122,"text":9580},{"id":9615,"depth":122,"text":9616},"two-pointers","Learn the two-pointer technique where pointers move at different speeds to solve problems like finding midpoints and detecting cycles.",{"timeComplexity":2077,"spaceComplexity":3903},"\u002Flearn\u002Ffast-slow-pointers","fast-slow",{"title":9188,"description":9639},"learn\u002Ffast-slow-pointers","QcZlY8dqT4EjM1wbgJTlhBZuqqNpjzejEQ4bYpPSdaU",{"id":9647,"title":9648,"body":9649,"category":3113,"complexity":862,"date":862,"description":10100,"difficulty":2462,"extension":865,"meta":10101,"navigation":221,"order":122,"path":10102,"publishedAt":870,"relatedAlgorithmId":862,"seo":10103,"stem":10104,"__hash__":10105},"learn\u002Flearn\u002Fgraphs-and-weighted-graphs.md","Graphs and Weighted Graphs",{"type":8,"value":9650,"toc":10089},[9651,9654,9665,9669,9673,9676,9681,9685,9688,9693,9697,9711,9715,9718,9976,9980,9983,9986,9992,9995,9999,10013,10016,10020,10086],[11,9652,9648],{"id":9653},"graphs-and-weighted-graphs",[15,9655,9656,9657,9660,9661,9664],{},"A graph is a collection of ",[19,9658,9659],{},"nodes"," (vertices) connected by ",[19,9662,9663],{},"edges",". Graphs model relationships: cities connected by roads, web pages connected by links, or maze cells connected by corridors.",[24,9666,9668],{"id":9667},"types-of-graphs","Types of Graphs",[1024,9670,9672],{"id":9671},"unweighted-graph","Unweighted Graph",[15,9674,9675],{},"Every edge has the same cost (implicitly 1). All connections are equal.",[15,9677,9678,9680],{},[19,9679,5572],{},": \"How many steps to reach the goal?\" — BFS answers this optimally.",[1024,9682,9684],{"id":9683},"weighted-graph","Weighted Graph",[15,9686,9687],{},"Each edge has a numeric weight representing cost, distance, or time. Some paths are cheaper than others.",[15,9689,9690,9692],{},[19,9691,5572],{},": \"What's the cheapest route?\" — Dijkstra and A* answer this.",[1024,9694,9696],{"id":9695},"directed-vs-undirected","Directed vs Undirected",[43,9698,9699,9705],{},[46,9700,9701,9704],{},[19,9702,9703],{},"Undirected",": edges go both ways (a road between cities)",[46,9706,9707,9710],{},[19,9708,9709],{},"Directed",": edges have a direction (a one-way street)",[24,9712,9714],{"id":9713},"code-snippet-graph-representation","Code Snippet — Graph Representation",[15,9716,9717],{},"The adjacency list is the most common representation for sparse graphs:",[32,9719,9721],{"className":76,"code":9720,"language":78,"meta":41,"style":41},"class Graph:\n    \"\"\"Unweighted graph using adjacency list.\"\"\"\n    def __init__(self, num_nodes: int):\n        self.num_nodes = num_nodes\n        self.adjacency_list = [[] for _ in range(num_nodes)]\n\n    def add_edge(self, from_node: int, to_node: int):\n        self.adjacency_list[from_node].append(to_node)\n        self.adjacency_list[to_node].append(from_node)\n\n    def get_neighbors(self, node: int) -> list[int]:\n        return self.adjacency_list[node]\n\n\nclass WeightedGraph:\n    \"\"\"Weighted graph where each edge has a cost.\"\"\"\n    def __init__(self, num_nodes: int):\n        self.num_nodes = num_nodes\n        self.adjacency_list = [[] for _ in range(num_nodes)]\n\n    def add_edge(self, from_node: int, to_node: int, weight: int):\n        self.adjacency_list[from_node].append((to_node, weight))\n        self.adjacency_list[to_node].append((from_node, weight))\n\n    def get_neighbors(self, node: int) -> list[tuple[int, int]]:\n        \"\"\"Returns list of (neighbor_node, edge_weight) pairs.\"\"\"\n        return self.adjacency_list[node]\n",[39,9722,9723,9731,9736,9748,9758,9778,9782,9798,9804,9810,9814,9830,9838,9842,9846,9854,9859,9871,9881,9901,9905,9925,9932,9939,9943,9963,9968],{"__ignoreMap":41},[82,9724,9725,9727,9729],{"class":84,"line":85},[82,9726,2534],{"class":88},[82,9728,2537],{"class":92},[82,9730,523],{"class":96},[82,9732,9733],{"class":84,"line":122},[82,9734,9735],{"class":125},"    \"\"\"Unweighted graph using adjacency list.\"\"\"\n",[82,9737,9738,9740,9742,9744,9746],{"class":84,"line":129},[82,9739,1176],{"class":88},[82,9741,2546],{"class":100},[82,9743,2549],{"class":96},[82,9745,101],{"class":100},[82,9747,2554],{"class":96},[82,9749,9750,9752,9754,9756],{"class":84,"line":135},[82,9751,2559],{"class":100},[82,9753,2562],{"class":96},[82,9755,141],{"class":88},[82,9757,173],{"class":96},[82,9759,9760,9762,9764,9766,9768,9770,9772,9774,9776],{"class":84,"line":147},[82,9761,2559],{"class":100},[82,9763,2573],{"class":96},[82,9765,141],{"class":88},[82,9767,2578],{"class":96},[82,9769,2581],{"class":88},[82,9771,2584],{"class":96},[82,9773,369],{"class":88},[82,9775,1228],{"class":100},[82,9777,2591],{"class":96},[82,9779,9780],{"class":84,"line":176},[82,9781,222],{"emptyLinePlaceholder":221},[82,9783,9784,9786,9788,9790,9792,9794,9796],{"class":84,"line":199},[82,9785,1176],{"class":88},[82,9787,2602],{"class":92},[82,9789,2605],{"class":96},[82,9791,101],{"class":100},[82,9793,2610],{"class":96},[82,9795,101],{"class":100},[82,9797,2554],{"class":96},[82,9799,9800,9802],{"class":84,"line":218},[82,9801,2559],{"class":100},[82,9803,2621],{"class":96},[82,9805,9806,9808],{"class":84,"line":225},[82,9807,2559],{"class":100},[82,9809,2628],{"class":96},[82,9811,9812],{"class":84,"line":236},[82,9813,222],{"emptyLinePlaceholder":221},[82,9815,9816,9818,9820,9822,9824,9826,9828],{"class":84,"line":247},[82,9817,1176],{"class":88},[82,9819,2639],{"class":92},[82,9821,2642],{"class":96},[82,9823,101],{"class":100},[82,9825,2141],{"class":96},[82,9827,101],{"class":100},[82,9829,119],{"class":96},[82,9831,9832,9834,9836],{"class":84,"line":262},[82,9833,2655],{"class":88},[82,9835,2658],{"class":100},[82,9837,2661],{"class":96},[82,9839,9840],{"class":84,"line":267},[82,9841,222],{"emptyLinePlaceholder":221},[82,9843,9844],{"class":84,"line":276},[82,9845,222],{"emptyLinePlaceholder":221},[82,9847,9848,9850,9852],{"class":84,"line":282},[82,9849,2534],{"class":88},[82,9851,7189],{"class":92},[82,9853,523],{"class":96},[82,9855,9856],{"class":84,"line":299},[82,9857,9858],{"class":125},"    \"\"\"Weighted graph where each edge has a cost.\"\"\"\n",[82,9860,9861,9863,9865,9867,9869],{"class":84,"line":304},[82,9862,1176],{"class":88},[82,9864,2546],{"class":100},[82,9866,2549],{"class":96},[82,9868,101],{"class":100},[82,9870,2554],{"class":96},[82,9872,9873,9875,9877,9879],{"class":84,"line":313},[82,9874,2559],{"class":100},[82,9876,2562],{"class":96},[82,9878,141],{"class":88},[82,9880,173],{"class":96},[82,9882,9883,9885,9887,9889,9891,9893,9895,9897,9899],{"class":84,"line":319},[82,9884,2559],{"class":100},[82,9886,2573],{"class":96},[82,9888,141],{"class":88},[82,9890,2578],{"class":96},[82,9892,2581],{"class":88},[82,9894,2584],{"class":96},[82,9896,369],{"class":88},[82,9898,1228],{"class":100},[82,9900,2591],{"class":96},[82,9902,9903],{"class":84,"line":330},[82,9904,222],{"emptyLinePlaceholder":221},[82,9906,9907,9909,9911,9913,9915,9917,9919,9921,9923],{"class":84,"line":335},[82,9908,1176],{"class":88},[82,9910,2602],{"class":92},[82,9912,2605],{"class":96},[82,9914,101],{"class":100},[82,9916,2610],{"class":96},[82,9918,101],{"class":100},[82,9920,7255],{"class":96},[82,9922,101],{"class":100},[82,9924,2554],{"class":96},[82,9926,9927,9929],{"class":84,"line":349},[82,9928,2559],{"class":100},[82,9930,9931],{"class":96},".adjacency_list[from_node].append((to_node, weight))\n",[82,9933,9934,9936],{"class":84,"line":355},[82,9935,2559],{"class":100},[82,9937,9938],{"class":96},".adjacency_list[to_node].append((from_node, weight))\n",[82,9940,9941],{"class":84,"line":360},[82,9942,222],{"emptyLinePlaceholder":221},[82,9944,9945,9947,9949,9951,9953,9955,9957,9959,9961],{"class":84,"line":375},[82,9946,1176],{"class":88},[82,9948,2639],{"class":92},[82,9950,2642],{"class":96},[82,9952,101],{"class":100},[82,9954,7290],{"class":96},[82,9956,101],{"class":100},[82,9958,7295],{"class":96},[82,9960,101],{"class":100},[82,9962,1070],{"class":96},[82,9964,9965],{"class":84,"line":384},[82,9966,9967],{"class":125},"        \"\"\"Returns list of (neighbor_node, edge_weight) pairs.\"\"\"\n",[82,9969,9970,9972,9974],{"class":84,"line":390},[82,9971,2655],{"class":88},[82,9973,2658],{"class":100},[82,9975,2661],{"class":96},[24,9977,9979],{"id":9978},"why-weights-matter","Why Weights Matter",[15,9981,9982],{},"On an unweighted graph, the shortest path (fewest edges) is always optimal. BFS finds this.",[15,9984,9985],{},"On a weighted graph, the path with fewest edges might be expensive:",[32,9987,9990],{"className":9988,"code":9989,"language":37},[35],"A --1-- B --1-- C    (cost: 2, hops: 2)\nA --5-- C            (cost: 5, hops: 1)\n",[39,9991,9989],{"__ignoreMap":41},[15,9993,9994],{},"BFS would pick A→C (1 hop) but Dijkstra picks A→B→C (cost 2).",[24,9996,9998],{"id":9997},"space-complexity","Space Complexity",[43,10000,10001,10007],{},[46,10002,10003,10006],{},[19,10004,10005],{},"Adjacency list",": O(V + E) — stores each edge twice for undirected graphs",[46,10008,10009,10012],{},[19,10010,10011],{},"Adjacency matrix",": O(V^2) — wastes space on sparse graphs but allows O(1) edge lookup",[15,10014,10015],{},"For most pathfinding problems, adjacency lists are preferred because real-world graphs are sparse.",[24,10017,10019],{"id":10018},"which-algorithm-for-which-graph","Which Algorithm for Which Graph",[731,10021,10022,10035],{},[734,10023,10024],{},[737,10025,10026,10029,10032],{},[740,10027,10028],{},"Graph Type",[740,10030,10031],{},"Best Algorithm",[740,10033,10034],{},"Guarantee",[750,10036,10037,10046,10055,10065,10076],{},[737,10038,10039,10041,10043],{},[755,10040,6995],{},[755,10042,3049],{},[755,10044,10045],{},"Shortest path (fewest hops)",[737,10047,10048,10050,10052],{},[755,10049,6998],{},[755,10051,745],{},[755,10053,10054],{},"Cheapest path (minimum total weight)",[737,10056,10057,10060,10062],{},[755,10058,10059],{},"Weighted + goal known",[755,10061,748],{},[755,10063,10064],{},"Cheapest path with fewer explorations",[737,10066,10067,10070,10073],{},[755,10068,10069],{},"Weighted (negative edges)",[755,10071,10072],{},"Bellman-Ford",[755,10074,10075],{},"Handles negative weights",[737,10077,10078,10081,10083],{},[755,10079,10080],{},"Unweighted, any path",[755,10082,3052],{},[755,10084,10085],{},"Uses less memory than BFS",[850,10087,10088],{},"html pre.shiki code .snl16, html code.shiki .snl16{--shiki-default:#F97583}html pre.shiki code .svObZ, html code.shiki .svObZ{--shiki-default:#B392F0}html pre.shiki code .s95oV, html code.shiki .s95oV{--shiki-default:#E1E4E8}html pre.shiki code .sU2Wk, html code.shiki .sU2Wk{--shiki-default:#9ECBFF}html pre.shiki code .sDLfK, html code.shiki .sDLfK{--shiki-default:#79B8FF}html .default .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}",{"title":41,"searchDepth":122,"depth":122,"links":10090},[10091,10096,10097,10098,10099],{"id":9667,"depth":122,"text":9668,"children":10092},[10093,10094,10095],{"id":9671,"depth":129,"text":9672},{"id":9683,"depth":129,"text":9684},{"id":9695,"depth":129,"text":9696},{"id":9713,"depth":122,"text":9714},{"id":9978,"depth":122,"text":9979},{"id":9997,"depth":122,"text":9998},{"id":10018,"depth":122,"text":10019},"Understand graph data structures: adjacency lists, edge weights, directed vs undirected, and how pathfinding algorithms operate on them.",{"timeComplexity":2464,"spaceComplexity":2464},"\u002Flearn\u002Fgraphs-and-weighted-graphs",{"title":9648,"description":10100},"learn\u002Fgraphs-and-weighted-graphs","EuuI5dUOoTX1DnLDRgv4ahnbPXLz8q6t-3DvXXXyTEg",{"id":10107,"title":10108,"body":10109,"category":5751,"complexity":862,"date":862,"description":11060,"difficulty":2462,"extension":865,"meta":11061,"navigation":221,"order":129,"path":11063,"publishedAt":2079,"relatedAlgorithmId":11064,"seo":11065,"stem":11066,"__hash__":11067},"learn\u002Flearn\u002Fhash-maps.md","Hash Maps",{"type":8,"value":10110,"toc":11045},[10111,10114,10137,10139,10168,10172,10175,10195,10198,10202,10205,10209,10212,10216,10219,10221,10224,10230,10232,10876,10878,10883,10897,10901,10904,10908,10915,10923,10926,10930,10968,10972,10992,10994,11043],[11,10112,10108],{"id":10113},"hash-maps",[15,10115,10116,10117,10120,10121,10124,10125,10128,10129,10132,10133,10136],{},"A hash map (also called a hash table or dictionary) is a data structure that maps keys to values using a ",[19,10118,10119],{},"hash function",". It provides O(1) average-case time for insertions, deletions, and lookups — making it one of the most widely used data structures in programming. Python's ",[39,10122,10123],{},"dict",", JavaScript's ",[39,10126,10127],{},"Object","\u002F",[39,10130,10131],{},"Map",", and Java's ",[39,10134,10135],{},"HashMap"," are all hash maps under the hood.",[24,10138,893],{"id":892},[895,10140,10141,10147,10156,10162],{},[46,10142,10143,10146],{},[19,10144,10145],{},"Hash the key",": Apply a hash function to convert the key into an integer",[46,10148,10149,10152,10153],{},[19,10150,10151],{},"Compute the index",": Use modulo to map the hash to a valid array index: ",[39,10154,10155],{},"index = hash(key) % table_size",[46,10157,10158,10161],{},[19,10159,10160],{},"Store the value",": Place the key-value pair at the computed index",[46,10163,10164,10167],{},[19,10165,10166],{},"Handle collisions",": When two keys map to the same index, use a collision resolution strategy",[24,10169,10171],{"id":10170},"the-hash-function","The Hash Function",[15,10173,10174],{},"A good hash function has these properties:",[43,10176,10177,10183,10189],{},[46,10178,10179,10182],{},[19,10180,10181],{},"Deterministic",": Same key always produces the same hash",[46,10184,10185,10188],{},[19,10186,10187],{},"Uniform distribution",": Spreads keys evenly across the table",[46,10190,10191,10194],{},[19,10192,10193],{},"Fast to compute",": O(1) time for any key",[15,10196,10197],{},"Example: For string keys, a common approach multiplies each character's ASCII value by powers of a prime number.",[24,10199,10201],{"id":10200},"collision-resolution","Collision Resolution",[15,10203,10204],{},"When two different keys hash to the same index, we have a collision. Two main strategies:",[1024,10206,10208],{"id":10207},"chaining-separate-chaining","Chaining (Separate Chaining)",[15,10210,10211],{},"Each table slot holds a linked list (or array) of all key-value pairs that hash to that index.",[1024,10213,10215],{"id":10214},"open-addressing-linear-probing","Open Addressing (Linear Probing)",[15,10217,10218],{},"When a collision occurs, probe the next available slot in the table.",[24,10220,4623],{"id":4622},[15,10222,10223],{},"Insert keys with table size 7:",[32,10225,10228],{"className":10226,"code":10227,"language":37},[35],"insert(\"cat\", 1): hash(\"cat\") % 7 = 3 → table[3] = (\"cat\", 1)\ninsert(\"dog\", 2): hash(\"dog\") % 7 = 5 → table[5] = (\"dog\", 2)\ninsert(\"rat\", 3): hash(\"rat\") % 7 = 3 → collision! Chain at table[3]\nlookup(\"cat\"):    hash(\"cat\") % 7 = 3 → search chain → found (\"cat\", 1)\ndelete(\"cat\"):    hash(\"cat\") % 7 = 3 → search chain → remove (\"cat\", 1)\n",[39,10229,10227],{"__ignoreMap":41},[24,10231,70],{"id":69},[32,10233,10235],{"className":76,"code":10234,"language":78,"meta":41,"style":41},"class HashMap:\n    \"\"\"Hash map with separate chaining for collision resolution.\"\"\"\n\n    def __init__(self, capacity: int = 16):\n        self._capacity = capacity\n        self._size = 0\n        self._buckets = [[] for _ in range(capacity)]\n        self._load_factor_threshold = 0.75\n\n    def _hash(self, key: str) -> int:\n        \"\"\"Compute hash index for a string key.\"\"\"\n        hash_value = 0\n        for char in key:\n            hash_value = hash_value * 31 + ord(char)\n        return hash_value % self._capacity\n\n    def put(self, key: str, value) -> None:\n        \"\"\"Insert or update a key-value pair.\"\"\"\n        index = self._hash(key)\n        bucket = self._buckets[index]\n\n        # Update existing key\n        for i, (existing_key, _) in enumerate(bucket):\n            if existing_key == key:\n                bucket[i] = (key, value)\n                return\n\n        # Insert new key\n        bucket.append((key, value))\n        self._size += 1\n\n        # Resize if load factor exceeded\n        if self._size \u002F self._capacity > self._load_factor_threshold:\n            self._resize()\n\n    def get(self, key: str):\n        \"\"\"Retrieve value by key. Returns None if not found.\"\"\"\n        index = self._hash(key)\n        bucket = self._buckets[index]\n\n        for existing_key, value in bucket:\n            if existing_key == key:\n                return value\n        return None\n\n    def remove(self, key: str) -> bool:\n        \"\"\"Remove a key-value pair. Returns True if found.\"\"\"\n        index = self._hash(key)\n        bucket = self._buckets[index]\n\n        for i, (existing_key, _) in enumerate(bucket):\n            if existing_key == key:\n                bucket.pop(i)\n                self._size -= 1\n                return True\n        return False\n\n    def _resize(self) -> None:\n        \"\"\"Double capacity and rehash all entries.\"\"\"\n        old_buckets = self._buckets\n        self._capacity *= 2\n        self._buckets = [[] for _ in range(self._capacity)]\n        self._size = 0\n\n        for bucket in old_buckets:\n            for key, value in bucket:\n                self.put(key, value)\n",[39,10236,10237,10246,10251,10255,10274,10286,10297,10319,10331,10335,10354,10359,10368,10380,10404,10417,10421,10439,10444,10456,10468,10472,10477,10492,10503,10513,10518,10522,10527,10532,10542,10546,10551,10572,10579,10583,10596,10601,10611,10621,10625,10637,10647,10653,10659,10663,10680,10685,10695,10705,10709,10721,10731,10736,10748,10754,10760,10764,10778,10783,10795,10806,10831,10841,10845,10857,10869],{"__ignoreMap":41},[82,10238,10239,10241,10244],{"class":84,"line":85},[82,10240,2534],{"class":88},[82,10242,10243],{"class":92}," HashMap",[82,10245,523],{"class":96},[82,10247,10248],{"class":84,"line":122},[82,10249,10250],{"class":125},"    \"\"\"Hash map with separate chaining for collision resolution.\"\"\"\n",[82,10252,10253],{"class":84,"line":129},[82,10254,222],{"emptyLinePlaceholder":221},[82,10256,10257,10259,10261,10264,10266,10269,10272],{"class":84,"line":135},[82,10258,1176],{"class":88},[82,10260,2546],{"class":100},[82,10262,10263],{"class":96},"(self, capacity: ",[82,10265,101],{"class":100},[82,10267,10268],{"class":88}," =",[82,10270,10271],{"class":100}," 16",[82,10273,2554],{"class":96},[82,10275,10276,10278,10281,10283],{"class":84,"line":147},[82,10277,2559],{"class":100},[82,10279,10280],{"class":96},"._capacity ",[82,10282,141],{"class":88},[82,10284,10285],{"class":96}," capacity\n",[82,10287,10288,10290,10293,10295],{"class":84,"line":176},[82,10289,2559],{"class":100},[82,10291,10292],{"class":96},"._size ",[82,10294,141],{"class":88},[82,10296,233],{"class":100},[82,10298,10299,10301,10304,10306,10308,10310,10312,10314,10316],{"class":84,"line":199},[82,10300,2559],{"class":100},[82,10302,10303],{"class":96},"._buckets ",[82,10305,141],{"class":88},[82,10307,2578],{"class":96},[82,10309,2581],{"class":88},[82,10311,2584],{"class":96},[82,10313,369],{"class":88},[82,10315,1228],{"class":100},[82,10317,10318],{"class":96},"(capacity)]\n",[82,10320,10321,10323,10326,10328],{"class":84,"line":218},[82,10322,2559],{"class":100},[82,10324,10325],{"class":96},"._load_factor_threshold ",[82,10327,141],{"class":88},[82,10329,10330],{"class":100}," 0.75\n",[82,10332,10333],{"class":84,"line":225},[82,10334,222],{"emptyLinePlaceholder":221},[82,10336,10337,10339,10342,10345,10348,10350,10352],{"class":84,"line":236},[82,10338,1176],{"class":88},[82,10340,10341],{"class":92}," _hash",[82,10343,10344],{"class":96},"(self, key: ",[82,10346,10347],{"class":100},"str",[82,10349,607],{"class":96},[82,10351,101],{"class":100},[82,10353,523],{"class":96},[82,10355,10356],{"class":84,"line":247},[82,10357,10358],{"class":125},"        \"\"\"Compute hash index for a string key.\"\"\"\n",[82,10360,10361,10364,10366],{"class":84,"line":262},[82,10362,10363],{"class":96},"        hash_value ",[82,10365,141],{"class":88},[82,10367,233],{"class":100},[82,10369,10370,10372,10375,10377],{"class":84,"line":267},[82,10371,363],{"class":88},[82,10373,10374],{"class":96}," char ",[82,10376,369],{"class":88},[82,10378,10379],{"class":96}," key:\n",[82,10381,10382,10385,10387,10390,10392,10395,10398,10401],{"class":84,"line":276},[82,10383,10384],{"class":96},"            hash_value ",[82,10386,141],{"class":88},[82,10388,10389],{"class":96}," hash_value ",[82,10391,170],{"class":88},[82,10393,10394],{"class":100}," 31",[82,10396,10397],{"class":88}," +",[82,10399,10400],{"class":100}," ord",[82,10402,10403],{"class":96},"(char)\n",[82,10405,10406,10408,10410,10412,10414],{"class":84,"line":282},[82,10407,2655],{"class":88},[82,10409,10389],{"class":96},[82,10411,637],{"class":88},[82,10413,2658],{"class":100},[82,10415,10416],{"class":96},"._capacity\n",[82,10418,10419],{"class":84,"line":299},[82,10420,222],{"emptyLinePlaceholder":221},[82,10422,10423,10425,10428,10430,10432,10435,10437],{"class":84,"line":304},[82,10424,1176],{"class":88},[82,10426,10427],{"class":92}," put",[82,10429,10344],{"class":96},[82,10431,10347],{"class":100},[82,10433,10434],{"class":96},", value) -> ",[82,10436,1188],{"class":100},[82,10438,523],{"class":96},[82,10440,10441],{"class":84,"line":313},[82,10442,10443],{"class":125},"        \"\"\"Insert or update a key-value pair.\"\"\"\n",[82,10445,10446,10449,10451,10453],{"class":84,"line":319},[82,10447,10448],{"class":96},"        index ",[82,10450,141],{"class":88},[82,10452,2658],{"class":100},[82,10454,10455],{"class":96},"._hash(key)\n",[82,10457,10458,10461,10463,10465],{"class":84,"line":330},[82,10459,10460],{"class":96},"        bucket ",[82,10462,141],{"class":88},[82,10464,2658],{"class":100},[82,10466,10467],{"class":96},"._buckets[index]\n",[82,10469,10470],{"class":84,"line":335},[82,10471,222],{"emptyLinePlaceholder":221},[82,10473,10474],{"class":84,"line":349},[82,10475,10476],{"class":258},"        # Update existing key\n",[82,10478,10479,10481,10484,10486,10489],{"class":84,"line":355},[82,10480,363],{"class":88},[82,10482,10483],{"class":96}," i, (existing_key, _) ",[82,10485,369],{"class":88},[82,10487,10488],{"class":100}," enumerate",[82,10490,10491],{"class":96},"(bucket):\n",[82,10493,10494,10496,10499,10501],{"class":84,"line":360},[82,10495,378],{"class":88},[82,10497,10498],{"class":96}," existing_key ",[82,10500,343],{"class":88},[82,10502,10379],{"class":96},[82,10504,10505,10508,10510],{"class":84,"line":375},[82,10506,10507],{"class":96},"                bucket[i] ",[82,10509,141],{"class":88},[82,10511,10512],{"class":96}," (key, value)\n",[82,10514,10515],{"class":84,"line":384},[82,10516,10517],{"class":88},"                return\n",[82,10519,10520],{"class":84,"line":390},[82,10521,222],{"emptyLinePlaceholder":221},[82,10523,10524],{"class":84,"line":395},[82,10525,10526],{"class":258},"        # Insert new key\n",[82,10528,10529],{"class":84,"line":412},[82,10530,10531],{"class":96},"        bucket.append((key, value))\n",[82,10533,10534,10536,10538,10540],{"class":84,"line":417},[82,10535,2559],{"class":100},[82,10537,10292],{"class":96},[82,10539,2257],{"class":88},[82,10541,2260],{"class":100},[82,10543,10544],{"class":84,"line":431},[82,10545,222],{"emptyLinePlaceholder":221},[82,10547,10548],{"class":84,"line":442},[82,10549,10550],{"class":258},"        # Resize if load factor exceeded\n",[82,10552,10553,10555,10557,10559,10561,10563,10565,10567,10569],{"class":84,"line":453},[82,10554,307],{"class":88},[82,10556,2658],{"class":100},[82,10558,10292],{"class":96},[82,10560,10128],{"class":88},[82,10562,2658],{"class":100},[82,10564,10280],{"class":96},[82,10566,3461],{"class":88},[82,10568,2658],{"class":100},[82,10570,10571],{"class":96},"._load_factor_threshold:\n",[82,10573,10574,10576],{"class":84,"line":468},[82,10575,5423],{"class":100},[82,10577,10578],{"class":96},"._resize()\n",[82,10580,10581],{"class":84,"line":474},[82,10582,222],{"emptyLinePlaceholder":221},[82,10584,10585,10587,10590,10592,10594],{"class":84,"line":479},[82,10586,1176],{"class":88},[82,10588,10589],{"class":92}," get",[82,10591,10344],{"class":96},[82,10593,10347],{"class":100},[82,10595,2554],{"class":96},[82,10597,10598],{"class":84,"line":485},[82,10599,10600],{"class":125},"        \"\"\"Retrieve value by key. Returns None if not found.\"\"\"\n",[82,10602,10603,10605,10607,10609],{"class":84,"line":496},[82,10604,10448],{"class":96},[82,10606,141],{"class":88},[82,10608,2658],{"class":100},[82,10610,10455],{"class":96},[82,10612,10613,10615,10617,10619],{"class":84,"line":507},[82,10614,10460],{"class":96},[82,10616,141],{"class":88},[82,10618,2658],{"class":100},[82,10620,10467],{"class":96},[82,10622,10623],{"class":84,"line":526},[82,10624,222],{"emptyLinePlaceholder":221},[82,10626,10627,10629,10632,10634],{"class":84,"line":532},[82,10628,363],{"class":88},[82,10630,10631],{"class":96}," existing_key, value ",[82,10633,369],{"class":88},[82,10635,10636],{"class":96}," bucket:\n",[82,10638,10639,10641,10643,10645],{"class":84,"line":543},[82,10640,378],{"class":88},[82,10642,10498],{"class":96},[82,10644,343],{"class":88},[82,10646,10379],{"class":96},[82,10648,10649,10651],{"class":84,"line":549},[82,10650,4972],{"class":88},[82,10652,4695],{"class":96},[82,10654,10655,10657],{"class":84,"line":554},[82,10656,2655],{"class":88},[82,10658,4707],{"class":100},[82,10660,10661],{"class":84,"line":565},[82,10662,222],{"emptyLinePlaceholder":221},[82,10664,10665,10667,10670,10672,10674,10676,10678],{"class":84,"line":574},[82,10666,1176],{"class":88},[82,10668,10669],{"class":92}," remove",[82,10671,10344],{"class":96},[82,10673,10347],{"class":100},[82,10675,607],{"class":96},[82,10677,4921],{"class":100},[82,10679,523],{"class":96},[82,10681,10682],{"class":84,"line":579},[82,10683,10684],{"class":125},"        \"\"\"Remove a key-value pair. Returns True if found.\"\"\"\n",[82,10686,10687,10689,10691,10693],{"class":84,"line":584},[82,10688,10448],{"class":96},[82,10690,141],{"class":88},[82,10692,2658],{"class":100},[82,10694,10455],{"class":96},[82,10696,10697,10699,10701,10703],{"class":84,"line":614},[82,10698,10460],{"class":96},[82,10700,141],{"class":88},[82,10702,2658],{"class":100},[82,10704,10467],{"class":96},[82,10706,10707],{"class":84,"line":620},[82,10708,222],{"emptyLinePlaceholder":221},[82,10710,10711,10713,10715,10717,10719],{"class":84,"line":643},[82,10712,363],{"class":88},[82,10714,10483],{"class":96},[82,10716,369],{"class":88},[82,10718,10488],{"class":100},[82,10720,10491],{"class":96},[82,10722,10723,10725,10727,10729],{"class":84,"line":663},[82,10724,378],{"class":88},[82,10726,10498],{"class":96},[82,10728,343],{"class":88},[82,10730,10379],{"class":96},[82,10732,10733],{"class":84,"line":5144},[82,10734,10735],{"class":96},"                bucket.pop(i)\n",[82,10737,10738,10741,10743,10746],{"class":84,"line":5151},[82,10739,10740],{"class":100},"                self",[82,10742,10292],{"class":96},[82,10744,10745],{"class":88},"-=",[82,10747,2260],{"class":100},[82,10749,10750,10752],{"class":84,"line":5157},[82,10751,4972],{"class":88},[82,10753,327],{"class":100},[82,10755,10756,10758],{"class":84,"line":5171},[82,10757,2655],{"class":88},[82,10759,1592],{"class":100},[82,10761,10762],{"class":84,"line":5179},[82,10763,222],{"emptyLinePlaceholder":221},[82,10765,10766,10768,10771,10774,10776],{"class":84,"line":5193},[82,10767,1176],{"class":88},[82,10769,10770],{"class":92}," _resize",[82,10772,10773],{"class":96},"(self) -> ",[82,10775,1188],{"class":100},[82,10777,523],{"class":96},[82,10779,10780],{"class":84,"line":5201},[82,10781,10782],{"class":125},"        \"\"\"Double capacity and rehash all entries.\"\"\"\n",[82,10784,10785,10788,10790,10792],{"class":84,"line":5206},[82,10786,10787],{"class":96},"        old_buckets ",[82,10789,141],{"class":88},[82,10791,2658],{"class":100},[82,10793,10794],{"class":96},"._buckets\n",[82,10796,10797,10799,10801,10804],{"class":84,"line":5212},[82,10798,2559],{"class":100},[82,10800,10280],{"class":96},[82,10802,10803],{"class":88},"*=",[82,10805,3321],{"class":100},[82,10807,10808,10810,10812,10814,10816,10818,10820,10822,10824,10826,10828],{"class":84,"line":5225},[82,10809,2559],{"class":100},[82,10811,10303],{"class":96},[82,10813,141],{"class":88},[82,10815,2578],{"class":96},[82,10817,2581],{"class":88},[82,10819,2584],{"class":96},[82,10821,369],{"class":88},[82,10823,1228],{"class":100},[82,10825,161],{"class":96},[82,10827,4806],{"class":100},[82,10829,10830],{"class":96},"._capacity)]\n",[82,10832,10833,10835,10837,10839],{"class":84,"line":5236},[82,10834,2559],{"class":100},[82,10836,10292],{"class":96},[82,10838,141],{"class":88},[82,10840,233],{"class":100},[82,10842,10843],{"class":84,"line":5248},[82,10844,222],{"emptyLinePlaceholder":221},[82,10846,10847,10849,10852,10854],{"class":84,"line":5253},[82,10848,363],{"class":88},[82,10850,10851],{"class":96}," bucket ",[82,10853,369],{"class":88},[82,10855,10856],{"class":96}," old_buckets:\n",[82,10858,10859,10862,10865,10867],{"class":84,"line":5260},[82,10860,10861],{"class":88},"            for",[82,10863,10864],{"class":96}," key, value ",[82,10866,369],{"class":88},[82,10868,10636],{"class":96},[82,10870,10871,10873],{"class":84,"line":5265},[82,10872,10740],{"class":100},[82,10874,10875],{"class":96},".put(key, value)\n",[24,10877,1816],{"id":1815},[15,10879,10880],{},[19,10881,10882],{},"Time Complexity: O(1) average, O(n) worst case",[43,10884,10885,10891],{},[46,10886,10887,10890],{},[19,10888,10889],{},"Average case",": With a good hash function and load factor below 0.75, most operations access one bucket with one or two entries — effectively O(1).",[46,10892,10893,10896],{},[19,10894,10895],{},"Worst case",": If all keys hash to the same bucket, every operation must traverse the entire chain — O(n). This is extremely rare with a proper hash function.",[15,10898,10899],{},[19,10900,1846],{},[15,10902,10903],{},"The hash map stores n key-value pairs plus the table array. With resizing, the table capacity is always within a constant factor of n.",[24,10905,10907],{"id":10906},"load-factor-and-resizing","Load Factor and Resizing",[15,10909,10910,10911,10914],{},"The ",[19,10912,10913],{},"load factor"," = n \u002F capacity. When it exceeds a threshold (typically 0.75):",[43,10916,10917,10920],{},[46,10918,10919],{},"Double the table capacity",[46,10921,10922],{},"Rehash all existing entries into the new table",[15,10924,10925],{},"This keeps chains short and maintains O(1) average performance. Resizing itself is O(n), but it happens infrequently enough that the amortized cost per operation remains O(1).",[24,10927,10929],{"id":10928},"when-to-use-hash-maps","When to Use Hash Maps",[43,10931,10932,10938,10944,10950,10956,10962],{},[46,10933,10934,10937],{},[19,10935,10936],{},"Frequency counting",": Count occurrences of elements in O(n) time.",[46,10939,10940,10943],{},[19,10941,10942],{},"Caching\u002FMemoization",": Store computed results for fast retrieval.",[46,10945,10946,10949],{},[19,10947,10948],{},"Deduplication",": Track seen elements to detect duplicates.",[46,10951,10952,10955],{},[19,10953,10954],{},"Indexing",": Build lookup tables mapping IDs to records.",[46,10957,10958,10961],{},[19,10959,10960],{},"Two-sum style problems",": Check for complement values in O(1).",[46,10963,10964,10967],{},[19,10965,10966],{},"Symbol tables",": Compilers use hash maps for variable\u002Ffunction name resolution.",[24,10969,10971],{"id":10970},"when-to-avoid-hash-maps","When to Avoid Hash Maps",[43,10973,10974,10980,10986],{},[46,10975,10976,10979],{},[19,10977,10978],{},"Ordered traversal needed",": Hash maps don't maintain insertion or sorted order. Use a balanced BST or sorted array instead.",[46,10981,10982,10985],{},[19,10983,10984],{},"Memory constrained",": The table array and linked list pointers add overhead beyond the raw data.",[46,10987,10988,10991],{},[19,10989,10990],{},"Small fixed datasets",": For very few keys, a simple array or linear scan may be simpler and faster.",[24,10993,1998],{"id":1997},[731,10995,10996,11004],{},[734,10997,10998],{},[737,10999,11000,11002],{},[740,11001,742],{},[740,11003,2009],{},[750,11005,11006,11013,11020,11027,11035],{},[737,11007,11008,11011],{},[755,11009,11010],{},"Average lookup",[755,11012,3903],{},[737,11014,11015,11018],{},[755,11016,11017],{},"Worst-case lookup",[755,11019,2077],{},[737,11021,11022,11024],{},[755,11023,5711],{},[755,11025,11026],{},"No (unordered)",[737,11028,11029,11032],{},[755,11030,11031],{},"Duplicate keys",[755,11033,11034],{},"No (values overwritten)",[737,11036,11037,11040],{},[755,11038,11039],{},"Null keys",[755,11041,11042],{},"Implementation-dependent",[850,11044,5733],{},{"title":41,"searchDepth":122,"depth":122,"links":11046},[11047,11048,11049,11053,11054,11055,11056,11057,11058,11059],{"id":892,"depth":122,"text":893},{"id":10170,"depth":122,"text":10171},{"id":10200,"depth":122,"text":10201,"children":11050},[11051,11052],{"id":10207,"depth":129,"text":10208},{"id":10214,"depth":129,"text":10215},{"id":4622,"depth":122,"text":4623},{"id":69,"depth":122,"text":70},{"id":1815,"depth":122,"text":1816},{"id":10906,"depth":122,"text":10907},{"id":10928,"depth":122,"text":10929},{"id":10970,"depth":122,"text":10971},{"id":1997,"depth":122,"text":1998},"Learn how hash maps provide O(1) average-case lookups using hash functions and collision resolution strategies.",{"timeComplexity":11062,"spaceComplexity":2077},"O(1) avg","\u002Flearn\u002Fhash-maps","hash-map",{"title":10108,"description":11060},"learn\u002Fhash-maps","EgpafdGvo212dJJLsDcUKZ934HhjwVrwQ3Oy2iRge9M",{"id":11069,"title":11070,"body":11071,"category":5751,"complexity":862,"date":862,"description":12646,"difficulty":864,"extension":865,"meta":12647,"navigation":221,"order":147,"path":12648,"publishedAt":2079,"relatedAlgorithmId":12649,"seo":12650,"stem":12651,"__hash__":12652},"learn\u002Flearn\u002Fheap-data-structure.md","Heap Data Structure",{"type":8,"value":11072,"toc":12628},[11073,11076,11083,11087,11108,11115,11119,11125,11151,11154,11157,11163,11165,11232,11234,11238,11252,11256,11273,11277,11292,11294,11300,11306,11325,11333,11347,11361,11363,12340,12342,12347,12372,12376,12379,12383,12386,12391,12395,12433,12437,12495,12498,12502,12564,12567,12569,12626],[11,11074,11070],{"id":11075},"heap-data-structure",[15,11077,11078,11079,11082],{},"A binary heap is a complete binary tree stored in an array that satisfies the ",[19,11080,11081],{},"heap property",": in a min-heap, every parent is smaller than or equal to its children; in a max-heap, every parent is larger. This structure provides O(1) access to the minimum (or maximum) element and O(log n) insertion and deletion — making it the backbone of priority queues.",[24,11084,11086],{"id":11085},"heap-property","Heap Property",[43,11088,11089,11099],{},[46,11090,11091,11094,11095,11098],{},[19,11092,11093],{},"Min-heap",": ",[39,11096,11097],{},"parent.value ≤ child.value"," for all nodes. The root is the smallest element.",[46,11100,11101,11094,11104,11107],{},[19,11102,11103],{},"Max-heap",[39,11105,11106],{},"parent.value ≥ child.value"," for all nodes. The root is the largest element.",[15,11109,11110,11111,11114],{},"The heap is ",[19,11112,11113],{},"not fully sorted"," — it only guarantees the parent-child relationship, not the ordering between siblings or across subtrees.",[24,11116,11118],{"id":11117},"array-representation","Array Representation",[15,11120,11121,11122,4469],{},"A binary heap is stored as a flat array. For a node at index ",[39,11123,11124],{},"i",[43,11126,11127,11135,11143],{},[46,11128,11129,11094,11132],{},[19,11130,11131],{},"Parent",[39,11133,11134],{},"(i - 1) \u002F\u002F 2",[46,11136,11137,11094,11140],{},[19,11138,11139],{},"Left child",[39,11141,11142],{},"2 * i + 1",[46,11144,11145,11094,11148],{},[19,11146,11147],{},"Right child",[39,11149,11150],{},"2 * i + 2",[15,11152,11153],{},"This avoids the overhead of explicit pointers and gives excellent cache locality.",[15,11155,11156],{},"Example min-heap as tree and array:",[32,11158,11161],{"className":11159,"code":11160,"language":37},[35],"Tree:       1\n           \u002F \\\n          3   5\n         \u002F \\\n        7   4\n\nArray: [1, 3, 5, 7, 4]\nIndex:  0  1  2  3  4\n",[39,11162,11160],{"__ignoreMap":41},[24,11164,4496],{"id":4495},[731,11166,11167,11178],{},[734,11168,11169],{},[737,11170,11171,11173,11175],{},[740,11172,4505],{},[740,11174,4369],{},[740,11176,11177],{},"Description",[750,11179,11180,11196,11208,11220],{},[737,11181,11182,11191,11193],{},[755,11183,11184,11187,11188],{},[39,11185,11186],{},"peek()"," \u002F ",[39,11189,11190],{},"get_min()",[755,11192,3903],{},[755,11194,11195],{},"Return the root element",[737,11197,11198,11203,11205],{},[755,11199,11200],{},[39,11201,11202],{},"insert(value)",[755,11204,3911],{},[755,11206,11207],{},"Add element, bubble up",[737,11209,11210,11215,11217],{},[755,11211,11212],{},[39,11213,11214],{},"extract_min()",[755,11216,3911],{},[755,11218,11219],{},"Remove root, bubble down",[737,11221,11222,11227,11229],{},[755,11223,11224],{},[39,11225,11226],{},"heapify(array)",[755,11228,2077],{},[755,11230,11231],{},"Build heap from array",[24,11233,893],{"id":892},[1024,11235,11237],{"id":11236},"insert-bubble-up","Insert (Bubble Up)",[895,11239,11240,11243,11246,11249],{},[46,11241,11242],{},"Add the new element at the end of the array (next available position)",[46,11244,11245],{},"Compare it with its parent",[46,11247,11248],{},"If it's smaller than the parent (min-heap), swap them",[46,11250,11251],{},"Repeat until the heap property is restored or you reach the root",[1024,11253,11255],{"id":11254},"extract-min-bubble-down","Extract Min (Bubble Down)",[895,11257,11258,11261,11264,11267,11270],{},[46,11259,11260],{},"Save the root (minimum element) to return",[46,11262,11263],{},"Move the last element to the root position",[46,11265,11266],{},"Compare the new root with its children",[46,11268,11269],{},"Swap with the smaller child if the parent is larger",[46,11271,11272],{},"Repeat until the heap property is restored or you reach a leaf",[1024,11274,11276],{"id":11275},"build-heap-heapify","Build Heap (Heapify)",[895,11278,11279,11286,11289],{},[46,11280,11281,11282,11285],{},"Start from the last non-leaf node (index ",[39,11283,11284],{},"n\u002F\u002F2 - 1",")",[46,11287,11288],{},"Apply bubble-down on each node moving toward the root",[46,11290,11291],{},"This is O(n) — faster than inserting n elements one by one (which would be O(n log n))",[24,11293,4623],{"id":4622},[15,11295,11296,11297,4469],{},"Build a min-heap from ",[39,11298,11299],{},"[4, 10, 3, 5, 1]",[15,11301,11302,11305],{},[19,11303,11304],{},"Start",": Last non-leaf at index 1 (value 10)",[43,11307,11308,11314],{},[46,11309,11310,11311],{},"Index 1: children are 5, 1. Swap with 1 → ",[39,11312,11313],{},"[4, 1, 3, 5, 10]",[46,11315,11316,11317,11320],{},"Index 0: children are 1, 3. Swap with 1 → ",[39,11318,11319],{},"[1, 4, 3, 5, 10]",[43,11321,11322],{},[46,11323,11324],{},"Recurse: index 1 children are 5, 10. No swap needed.",[15,11326,11327,11094,11330,11332],{},[19,11328,11329],{},"Result",[39,11331,11319],{}," — valid min-heap.",[15,11334,11335,11338,11339,11342,11343,11346],{},[19,11336,11337],{},"Insert 2",": Append → ",[39,11340,11341],{},"[1, 4, 3, 5, 10, 2]",". Bubble up: 2 \u003C 3 → swap → ",[39,11344,11345],{},"[1, 4, 2, 5, 10, 3]",". 2 > 1 → stop.",[15,11348,11349,11352,11353,11356,11357,11360],{},[19,11350,11351],{},"Extract min",": Remove 1, move 3 to root → ",[39,11354,11355],{},"[3, 4, 2, 5, 10]",". Bubble down: 2 \u003C 3 → swap → ",[39,11358,11359],{},"[2, 4, 3, 5, 10]",". Done.",[24,11362,70],{"id":69},[32,11364,11366],{"className":76,"code":11365,"language":78,"meta":41,"style":41},"class MinHeap:\n    \"\"\"Min-heap implementation using an array.\"\"\"\n\n    def __init__(self):\n        self._data = []\n\n    def size(self) -> int:\n        return len(self._data)\n\n    def is_empty(self) -> bool:\n        return len(self._data) == 0\n\n    def peek(self) -> int:\n        \"\"\"Return the minimum element without removing it.\"\"\"\n        if self.is_empty():\n            raise IndexError(\"Peek at empty heap\")\n        return self._data[0]\n\n    def insert(self, value: int) -> None:\n        \"\"\"Add a value to the heap.\"\"\"\n        self._data.append(value)\n        self._bubble_up(len(self._data) - 1)\n\n    def extract_min(self) -> int:\n        \"\"\"Remove and return the minimum element.\"\"\"\n        if self.is_empty():\n            raise IndexError(\"Extract from empty heap\")\n\n        min_value = self._data[0]\n        last_value = self._data.pop()\n\n        if not self.is_empty():\n            self._data[0] = last_value\n            self._bubble_down(0)\n\n        return min_value\n\n    def _bubble_up(self, index: int) -> None:\n        \"\"\"Move element up until heap property is restored.\"\"\"\n        while index > 0:\n            parent = (index - 1) \u002F\u002F 2\n            if self._data[index] \u003C self._data[parent]:\n                self._data[index], self._data[parent] = (\n                    self._data[parent],\n                    self._data[index],\n                )\n                index = parent\n            else:\n                break\n\n    def _bubble_down(self, index: int) -> None:\n        \"\"\"Move element down until heap property is restored.\"\"\"\n        size = len(self._data)\n\n        while True:\n            smallest = index\n            left = 2 * index + 1\n            right = 2 * index + 2\n\n            if left \u003C size and self._data[left] \u003C self._data[smallest]:\n                smallest = left\n            if right \u003C size and self._data[right] \u003C self._data[smallest]:\n                smallest = right\n\n            if smallest == index:\n                break\n\n            self._data[index], self._data[smallest] = (\n                self._data[smallest],\n                self._data[index],\n            )\n            index = smallest\n\n\ndef heapify(numbers: list[int]) -> list[int]:\n    \"\"\"Convert an array into a min-heap in O(n) time.\"\"\"\n    n = len(numbers)\n\n    # Start from last non-leaf and sift down each node\n    for i in range(n \u002F\u002F 2 - 1, -1, -1):\n        index = i\n        while True:\n            smallest = index\n            left = 2 * index + 1\n            right = 2 * index + 2\n\n            if left \u003C n and numbers[left] \u003C numbers[smallest]:\n                smallest = left\n            if right \u003C n and numbers[right] \u003C numbers[smallest]:\n                smallest = right\n\n            if smallest == index:\n                break\n\n            numbers[index], numbers[smallest] = numbers[smallest], numbers[index]\n            index = smallest\n\n    return numbers\n",[39,11367,11368,11377,11382,11386,11394,11405,11409,11422,11435,11439,11452,11469,11473,11486,11491,11500,11515,11528,11532,11548,11553,11560,11581,11585,11598,11603,11611,11624,11628,11643,11655,11659,11669,11684,11695,11699,11706,11710,11728,11733,11745,11765,11781,11797,11805,11812,11816,11826,11832,11837,11841,11858,11863,11878,11882,11890,11900,11918,11935,11939,11965,11975,11999,12008,12012,12024,12028,12032,12047,12054,12060,12065,12075,12079,12083,12100,12105,12116,12120,12125,12160,12169,12177,12185,12201,12218,12223,12244,12253,12273,12282,12287,12298,12303,12308,12319,12328,12333],{"__ignoreMap":41},[82,11369,11370,11372,11375],{"class":84,"line":85},[82,11371,2534],{"class":88},[82,11373,11374],{"class":92}," MinHeap",[82,11376,523],{"class":96},[82,11378,11379],{"class":84,"line":122},[82,11380,11381],{"class":125},"    \"\"\"Min-heap implementation using an array.\"\"\"\n",[82,11383,11384],{"class":84,"line":129},[82,11385,222],{"emptyLinePlaceholder":221},[82,11387,11388,11390,11392],{"class":84,"line":135},[82,11389,1176],{"class":88},[82,11391,2546],{"class":100},[82,11393,4753],{"class":96},[82,11395,11396,11398,11401,11403],{"class":84,"line":147},[82,11397,2559],{"class":100},[82,11399,11400],{"class":96},"._data ",[82,11402,141],{"class":88},[82,11404,493],{"class":96},[82,11406,11407],{"class":84,"line":176},[82,11408,222],{"emptyLinePlaceholder":221},[82,11410,11411,11413,11416,11418,11420],{"class":84,"line":199},[82,11412,1176],{"class":88},[82,11414,11415],{"class":92}," size",[82,11417,10773],{"class":96},[82,11419,101],{"class":100},[82,11421,523],{"class":96},[82,11423,11424,11426,11428,11430,11432],{"class":84,"line":218},[82,11425,2655],{"class":88},[82,11427,1471],{"class":100},[82,11429,161],{"class":96},[82,11431,4806],{"class":100},[82,11433,11434],{"class":96},"._data)\n",[82,11436,11437],{"class":84,"line":225},[82,11438,222],{"emptyLinePlaceholder":221},[82,11440,11441,11443,11446,11448,11450],{"class":84,"line":236},[82,11442,1176],{"class":88},[82,11444,11445],{"class":92}," is_empty",[82,11447,10773],{"class":96},[82,11449,4921],{"class":100},[82,11451,523],{"class":96},[82,11453,11454,11456,11458,11460,11462,11465,11467],{"class":84,"line":247},[82,11455,2655],{"class":88},[82,11457,1471],{"class":100},[82,11459,161],{"class":96},[82,11461,4806],{"class":100},[82,11463,11464],{"class":96},"._data) ",[82,11466,343],{"class":88},[82,11468,233],{"class":100},[82,11470,11471],{"class":84,"line":262},[82,11472,222],{"emptyLinePlaceholder":221},[82,11474,11475,11477,11480,11482,11484],{"class":84,"line":267},[82,11476,1176],{"class":88},[82,11478,11479],{"class":92}," peek",[82,11481,10773],{"class":96},[82,11483,101],{"class":100},[82,11485,523],{"class":96},[82,11487,11488],{"class":84,"line":276},[82,11489,11490],{"class":125},"        \"\"\"Return the minimum element without removing it.\"\"\"\n",[82,11492,11493,11495,11497],{"class":84,"line":282},[82,11494,307],{"class":88},[82,11496,2658],{"class":100},[82,11498,11499],{"class":96},".is_empty():\n",[82,11501,11502,11505,11508,11510,11513],{"class":84,"line":299},[82,11503,11504],{"class":88},"            raise",[82,11506,11507],{"class":100}," IndexError",[82,11509,161],{"class":96},[82,11511,11512],{"class":125},"\"Peek at empty heap\"",[82,11514,296],{"class":96},[82,11516,11517,11519,11521,11524,11526],{"class":84,"line":304},[82,11518,2655],{"class":88},[82,11520,2658],{"class":100},[82,11522,11523],{"class":96},"._data[",[82,11525,293],{"class":100},[82,11527,3224],{"class":96},[82,11529,11530],{"class":84,"line":313},[82,11531,222],{"emptyLinePlaceholder":221},[82,11533,11534,11536,11538,11540,11542,11544,11546],{"class":84,"line":319},[82,11535,1176],{"class":88},[82,11537,4775],{"class":92},[82,11539,4679],{"class":96},[82,11541,101],{"class":100},[82,11543,607],{"class":96},[82,11545,1188],{"class":100},[82,11547,523],{"class":96},[82,11549,11550],{"class":84,"line":330},[82,11551,11552],{"class":125},"        \"\"\"Add a value to the heap.\"\"\"\n",[82,11554,11555,11557],{"class":84,"line":335},[82,11556,2559],{"class":100},[82,11558,11559],{"class":96},"._data.append(value)\n",[82,11561,11562,11564,11567,11569,11571,11573,11575,11577,11579],{"class":84,"line":349},[82,11563,2559],{"class":100},[82,11565,11566],{"class":96},"._bubble_up(",[82,11568,1545],{"class":100},[82,11570,161],{"class":96},[82,11572,4806],{"class":100},[82,11574,11464],{"class":96},[82,11576,186],{"class":88},[82,11578,1348],{"class":100},[82,11580,296],{"class":96},[82,11582,11583],{"class":84,"line":355},[82,11584,222],{"emptyLinePlaceholder":221},[82,11586,11587,11589,11592,11594,11596],{"class":84,"line":360},[82,11588,1176],{"class":88},[82,11590,11591],{"class":92}," extract_min",[82,11593,10773],{"class":96},[82,11595,101],{"class":100},[82,11597,523],{"class":96},[82,11599,11600],{"class":84,"line":375},[82,11601,11602],{"class":125},"        \"\"\"Remove and return the minimum element.\"\"\"\n",[82,11604,11605,11607,11609],{"class":84,"line":384},[82,11606,307],{"class":88},[82,11608,2658],{"class":100},[82,11610,11499],{"class":96},[82,11612,11613,11615,11617,11619,11622],{"class":84,"line":390},[82,11614,11504],{"class":88},[82,11616,11507],{"class":100},[82,11618,161],{"class":96},[82,11620,11621],{"class":125},"\"Extract from empty heap\"",[82,11623,296],{"class":96},[82,11625,11626],{"class":84,"line":395},[82,11627,222],{"emptyLinePlaceholder":221},[82,11629,11630,11633,11635,11637,11639,11641],{"class":84,"line":412},[82,11631,11632],{"class":96},"        min_value ",[82,11634,141],{"class":88},[82,11636,2658],{"class":100},[82,11638,11523],{"class":96},[82,11640,293],{"class":100},[82,11642,3224],{"class":96},[82,11644,11645,11648,11650,11652],{"class":84,"line":417},[82,11646,11647],{"class":96},"        last_value ",[82,11649,141],{"class":88},[82,11651,2658],{"class":100},[82,11653,11654],{"class":96},"._data.pop()\n",[82,11656,11657],{"class":84,"line":431},[82,11658,222],{"emptyLinePlaceholder":221},[82,11660,11661,11663,11665,11667],{"class":84,"line":442},[82,11662,307],{"class":88},[82,11664,2300],{"class":88},[82,11666,2658],{"class":100},[82,11668,11499],{"class":96},[82,11670,11671,11673,11675,11677,11679,11681],{"class":84,"line":453},[82,11672,5423],{"class":100},[82,11674,11523],{"class":96},[82,11676,293],{"class":100},[82,11678,192],{"class":96},[82,11680,141],{"class":88},[82,11682,11683],{"class":96}," last_value\n",[82,11685,11686,11688,11691,11693],{"class":84,"line":468},[82,11687,5423],{"class":100},[82,11689,11690],{"class":96},"._bubble_down(",[82,11692,293],{"class":100},[82,11694,296],{"class":96},[82,11696,11697],{"class":84,"line":474},[82,11698,222],{"emptyLinePlaceholder":221},[82,11700,11701,11703],{"class":84,"line":479},[82,11702,2655],{"class":88},[82,11704,11705],{"class":96}," min_value\n",[82,11707,11708],{"class":84,"line":485},[82,11709,222],{"emptyLinePlaceholder":221},[82,11711,11712,11714,11717,11720,11722,11724,11726],{"class":84,"line":496},[82,11713,1176],{"class":88},[82,11715,11716],{"class":92}," _bubble_up",[82,11718,11719],{"class":96},"(self, index: ",[82,11721,101],{"class":100},[82,11723,607],{"class":96},[82,11725,1188],{"class":100},[82,11727,523],{"class":96},[82,11729,11730],{"class":84,"line":507},[82,11731,11732],{"class":125},"        \"\"\"Move element up until heap property is restored.\"\"\"\n",[82,11734,11735,11737,11739,11741,11743],{"class":84,"line":526},[82,11736,4945],{"class":88},[82,11738,1725],{"class":96},[82,11740,3461],{"class":88},[82,11742,1699],{"class":100},[82,11744,523],{"class":96},[82,11746,11747,11750,11752,11755,11757,11759,11761,11763],{"class":84,"line":532},[82,11748,11749],{"class":96},"            parent ",[82,11751,141],{"class":88},[82,11753,11754],{"class":96}," (index ",[82,11756,186],{"class":88},[82,11758,1348],{"class":100},[82,11760,8318],{"class":96},[82,11762,631],{"class":88},[82,11764,3321],{"class":100},[82,11766,11767,11769,11771,11774,11776,11778],{"class":84,"line":543},[82,11768,378],{"class":88},[82,11770,2658],{"class":100},[82,11772,11773],{"class":96},"._data[index] ",[82,11775,425],{"class":88},[82,11777,2658],{"class":100},[82,11779,11780],{"class":96},"._data[parent]:\n",[82,11782,11783,11785,11788,11790,11793,11795],{"class":84,"line":549},[82,11784,10740],{"class":100},[82,11786,11787],{"class":96},"._data[index], ",[82,11789,4806],{"class":100},[82,11791,11792],{"class":96},"._data[parent] ",[82,11794,141],{"class":88},[82,11796,3854],{"class":96},[82,11798,11799,11802],{"class":84,"line":554},[82,11800,11801],{"class":100},"                    self",[82,11803,11804],{"class":96},"._data[parent],\n",[82,11806,11807,11809],{"class":84,"line":565},[82,11808,11801],{"class":100},[82,11810,11811],{"class":96},"._data[index],\n",[82,11813,11814],{"class":84,"line":574},[82,11815,3871],{"class":96},[82,11817,11818,11821,11823],{"class":84,"line":579},[82,11819,11820],{"class":96},"                index ",[82,11822,141],{"class":88},[82,11824,11825],{"class":96}," parent\n",[82,11827,11828,11830],{"class":84,"line":584},[82,11829,5000],{"class":88},[82,11831,523],{"class":96},[82,11833,11834],{"class":84,"line":614},[82,11835,11836],{"class":88},"                break\n",[82,11838,11839],{"class":84,"line":620},[82,11840,222],{"emptyLinePlaceholder":221},[82,11842,11843,11845,11848,11850,11852,11854,11856],{"class":84,"line":643},[82,11844,1176],{"class":88},[82,11846,11847],{"class":92}," _bubble_down",[82,11849,11719],{"class":96},[82,11851,101],{"class":100},[82,11853,607],{"class":96},[82,11855,1188],{"class":100},[82,11857,523],{"class":96},[82,11859,11860],{"class":84,"line":663},[82,11861,11862],{"class":125},"        \"\"\"Move element down until heap property is restored.\"\"\"\n",[82,11864,11865,11868,11870,11872,11874,11876],{"class":84,"line":5144},[82,11866,11867],{"class":96},"        size ",[82,11869,141],{"class":88},[82,11871,1471],{"class":100},[82,11873,161],{"class":96},[82,11875,4806],{"class":100},[82,11877,11434],{"class":96},[82,11879,11880],{"class":84,"line":5151},[82,11881,222],{"emptyLinePlaceholder":221},[82,11883,11884,11886,11888],{"class":84,"line":5157},[82,11885,4945],{"class":88},[82,11887,9424],{"class":100},[82,11889,523],{"class":96},[82,11891,11892,11895,11897],{"class":84,"line":5171},[82,11893,11894],{"class":96},"            smallest ",[82,11896,141],{"class":88},[82,11898,11899],{"class":96}," index\n",[82,11901,11902,11905,11907,11909,11912,11914,11916],{"class":84,"line":5179},[82,11903,11904],{"class":96},"            left ",[82,11906,141],{"class":88},[82,11908,8295],{"class":100},[82,11910,11911],{"class":88}," *",[82,11913,1725],{"class":96},[82,11915,406],{"class":88},[82,11917,2260],{"class":100},[82,11919,11920,11923,11925,11927,11929,11931,11933],{"class":84,"line":5193},[82,11921,11922],{"class":96},"            right ",[82,11924,141],{"class":88},[82,11926,8295],{"class":100},[82,11928,11911],{"class":88},[82,11930,1725],{"class":96},[82,11932,406],{"class":88},[82,11934,3321],{"class":100},[82,11936,11937],{"class":84,"line":5201},[82,11938,222],{"emptyLinePlaceholder":221},[82,11940,11941,11943,11946,11948,11951,11953,11955,11958,11960,11962],{"class":84,"line":5206},[82,11942,378],{"class":88},[82,11944,11945],{"class":96}," left ",[82,11947,425],{"class":88},[82,11949,11950],{"class":96}," size ",[82,11952,3664],{"class":88},[82,11954,2658],{"class":100},[82,11956,11957],{"class":96},"._data[left] ",[82,11959,425],{"class":88},[82,11961,2658],{"class":100},[82,11963,11964],{"class":96},"._data[smallest]:\n",[82,11966,11967,11970,11972],{"class":84,"line":5212},[82,11968,11969],{"class":96},"                smallest ",[82,11971,141],{"class":88},[82,11973,11974],{"class":96}," left\n",[82,11976,11977,11979,11982,11984,11986,11988,11990,11993,11995,11997],{"class":84,"line":5225},[82,11978,378],{"class":88},[82,11980,11981],{"class":96}," right ",[82,11983,425],{"class":88},[82,11985,11950],{"class":96},[82,11987,3664],{"class":88},[82,11989,2658],{"class":100},[82,11991,11992],{"class":96},"._data[right] ",[82,11994,425],{"class":88},[82,11996,2658],{"class":100},[82,11998,11964],{"class":96},[82,12000,12001,12003,12005],{"class":84,"line":5236},[82,12002,11969],{"class":96},[82,12004,141],{"class":88},[82,12006,12007],{"class":96}," right\n",[82,12009,12010],{"class":84,"line":5248},[82,12011,222],{"emptyLinePlaceholder":221},[82,12013,12014,12016,12019,12021],{"class":84,"line":5253},[82,12015,378],{"class":88},[82,12017,12018],{"class":96}," smallest ",[82,12020,343],{"class":88},[82,12022,12023],{"class":96}," index:\n",[82,12025,12026],{"class":84,"line":5260},[82,12027,11836],{"class":88},[82,12029,12030],{"class":84,"line":5265},[82,12031,222],{"emptyLinePlaceholder":221},[82,12033,12034,12036,12038,12040,12043,12045],{"class":84,"line":5276},[82,12035,5423],{"class":100},[82,12037,11787],{"class":96},[82,12039,4806],{"class":100},[82,12041,12042],{"class":96},"._data[smallest] ",[82,12044,141],{"class":88},[82,12046,3854],{"class":96},[82,12048,12049,12051],{"class":84,"line":5282},[82,12050,10740],{"class":100},[82,12052,12053],{"class":96},"._data[smallest],\n",[82,12055,12056,12058],{"class":84,"line":5291},[82,12057,10740],{"class":100},[82,12059,11811],{"class":96},[82,12061,12062],{"class":84,"line":5307},[82,12063,12064],{"class":96},"            )\n",[82,12066,12067,12070,12072],{"class":84,"line":5317},[82,12068,12069],{"class":96},"            index ",[82,12071,141],{"class":88},[82,12073,12074],{"class":96}," smallest\n",[82,12076,12077],{"class":84,"line":5325},[82,12078,222],{"emptyLinePlaceholder":221},[82,12080,12081],{"class":84,"line":5330},[82,12082,222],{"emptyLinePlaceholder":221},[82,12084,12085,12087,12090,12092,12094,12096,12098],{"class":84,"line":5345},[82,12086,89],{"class":88},[82,12088,12089],{"class":92}," heapify",[82,12091,1627],{"class":96},[82,12093,101],{"class":100},[82,12095,3503],{"class":96},[82,12097,101],{"class":100},[82,12099,119],{"class":96},[82,12101,12102],{"class":84,"line":5351},[82,12103,12104],{"class":125},"    \"\"\"Convert an array into a min-heap in O(n) time.\"\"\"\n",[82,12106,12107,12110,12112,12114],{"class":84,"line":5361},[82,12108,12109],{"class":96},"    n ",[82,12111,141],{"class":88},[82,12113,1471],{"class":100},[82,12115,3783],{"class":96},[82,12117,12118],{"class":84,"line":5374},[82,12119,222],{"emptyLinePlaceholder":221},[82,12121,12122],{"class":84,"line":5381},[82,12123,12124],{"class":258},"    # Start from last non-leaf and sift down each node\n",[82,12126,12127,12129,12131,12133,12135,12138,12140,12142,12144,12146,12148,12150,12152,12154,12156,12158],{"class":84,"line":5386},[82,12128,982],{"class":88},[82,12130,1536],{"class":96},[82,12132,369],{"class":88},[82,12134,1228],{"class":100},[82,12136,12137],{"class":96},"(n ",[82,12139,631],{"class":88},[82,12141,8295],{"class":100},[82,12143,518],{"class":88},[82,12145,1348],{"class":100},[82,12147,7295],{"class":96},[82,12149,186],{"class":88},[82,12151,189],{"class":100},[82,12153,7295],{"class":96},[82,12155,186],{"class":88},[82,12157,189],{"class":100},[82,12159,2554],{"class":96},[82,12161,12162,12164,12166],{"class":84,"line":5405},[82,12163,10448],{"class":96},[82,12165,141],{"class":88},[82,12167,12168],{"class":96}," i\n",[82,12170,12171,12173,12175],{"class":84,"line":5420},[82,12172,4945],{"class":88},[82,12174,9424],{"class":100},[82,12176,523],{"class":96},[82,12178,12179,12181,12183],{"class":84,"line":5429},[82,12180,11894],{"class":96},[82,12182,141],{"class":88},[82,12184,11899],{"class":96},[82,12186,12187,12189,12191,12193,12195,12197,12199],{"class":84,"line":5435},[82,12188,11904],{"class":96},[82,12190,141],{"class":88},[82,12192,8295],{"class":100},[82,12194,11911],{"class":88},[82,12196,1725],{"class":96},[82,12198,406],{"class":88},[82,12200,2260],{"class":100},[82,12202,12204,12206,12208,12210,12212,12214,12216],{"class":84,"line":12203},85,[82,12205,11922],{"class":96},[82,12207,141],{"class":88},[82,12209,8295],{"class":100},[82,12211,11911],{"class":88},[82,12213,1725],{"class":96},[82,12215,406],{"class":88},[82,12217,3321],{"class":100},[82,12219,12221],{"class":84,"line":12220},86,[82,12222,222],{"emptyLinePlaceholder":221},[82,12224,12226,12228,12230,12232,12234,12236,12239,12241],{"class":84,"line":12225},87,[82,12227,378],{"class":88},[82,12229,11945],{"class":96},[82,12231,425],{"class":88},[82,12233,8290],{"class":96},[82,12235,3664],{"class":88},[82,12237,12238],{"class":96}," numbers[left] ",[82,12240,425],{"class":88},[82,12242,12243],{"class":96}," numbers[smallest]:\n",[82,12245,12247,12249,12251],{"class":84,"line":12246},88,[82,12248,11969],{"class":96},[82,12250,141],{"class":88},[82,12252,11974],{"class":96},[82,12254,12256,12258,12260,12262,12264,12266,12269,12271],{"class":84,"line":12255},89,[82,12257,378],{"class":88},[82,12259,11981],{"class":96},[82,12261,425],{"class":88},[82,12263,8290],{"class":96},[82,12265,3664],{"class":88},[82,12267,12268],{"class":96}," numbers[right] ",[82,12270,425],{"class":88},[82,12272,12243],{"class":96},[82,12274,12276,12278,12280],{"class":84,"line":12275},90,[82,12277,11969],{"class":96},[82,12279,141],{"class":88},[82,12281,12007],{"class":96},[82,12283,12285],{"class":84,"line":12284},91,[82,12286,222],{"emptyLinePlaceholder":221},[82,12288,12290,12292,12294,12296],{"class":84,"line":12289},92,[82,12291,378],{"class":88},[82,12293,12018],{"class":96},[82,12295,343],{"class":88},[82,12297,12023],{"class":96},[82,12299,12301],{"class":84,"line":12300},93,[82,12302,11836],{"class":88},[82,12304,12306],{"class":84,"line":12305},94,[82,12307,222],{"emptyLinePlaceholder":221},[82,12309,12311,12314,12316],{"class":84,"line":12310},95,[82,12312,12313],{"class":96},"            numbers[index], numbers[smallest] ",[82,12315,141],{"class":88},[82,12317,12318],{"class":96}," numbers[smallest], numbers[index]\n",[82,12320,12322,12324,12326],{"class":84,"line":12321},96,[82,12323,12069],{"class":96},[82,12325,141],{"class":88},[82,12327,12074],{"class":96},[82,12329,12331],{"class":84,"line":12330},97,[82,12332,222],{"emptyLinePlaceholder":221},[82,12334,12336,12338],{"class":84,"line":12335},98,[82,12337,568],{"class":88},[82,12339,3534],{"class":96},[24,12341,1816],{"id":1815},[15,12343,12344],{},[19,12345,12346],{},"Time Complexity:",[43,12348,12349,12355,12360,12366],{},[46,12350,12351,12354],{},[19,12352,12353],{},"Peek",": O(1) — the min\u002Fmax is always at the root.",[46,12356,12357,12359],{},[19,12358,4527],{},": O(log n) — bubble up traverses at most the height of the tree (log n levels).",[46,12361,12362,12365],{},[19,12363,12364],{},"Extract min\u002Fmax",": O(log n) — bubble down traverses at most log n levels.",[46,12367,12368,12371],{},[19,12369,12370],{},"Build heap",": O(n) — not O(n log n) because most nodes are near the bottom and require few swaps.",[15,12373,12374],{},[19,12375,1846],{},[15,12377,12378],{},"The array stores all n elements. No extra pointers or links are needed.",[24,12380,12382],{"id":12381},"why-build-heap-is-on","Why Build Heap is O(n)",[15,12384,12385],{},"Intuitively: half the nodes are leaves (0 work), a quarter need at most 1 swap, an eighth need at most 2 swaps, and so on. The sum converges to O(n):",[15,12387,12388],{},[39,12389,12390],{},"n\u002F2 * 0 + n\u002F4 * 1 + n\u002F8 * 2 + ... = O(n)",[24,12392,12394],{"id":12393},"when-to-use-heaps","When to Use Heaps",[43,12396,12397,12403,12409,12415,12421,12427],{},[46,12398,12399,12402],{},[19,12400,12401],{},"Priority queues",": Process tasks by priority (job schedulers, event systems).",[46,12404,12405,12408],{},[19,12406,12407],{},"Dijkstra's algorithm",": Extract the next closest vertex in O(log n).",[46,12410,12411,12414],{},[19,12412,12413],{},"K-th largest\u002Fsmallest",": Maintain a heap of size k for streaming top-k problems.",[46,12416,12417,12420],{},[19,12418,12419],{},"Merge k sorted lists",": Use a min-heap to track the smallest element across all lists.",[46,12422,12423,12426],{},[19,12424,12425],{},"Median finding",": Two heaps (max-heap for lower half, min-heap for upper half) give O(1) median.",[46,12428,12429,12432],{},[19,12430,12431],{},"Heap sort",": In-place O(n log n) sorting.",[24,12434,12436],{"id":12435},"min-heap-vs-max-heap","Min-Heap vs. Max-Heap",[731,12438,12439,12451],{},[734,12440,12441],{},[737,12442,12443,12445,12448],{},[740,12444,742],{},[740,12446,12447],{},"Min-Heap",[740,12449,12450],{},"Max-Heap",[750,12452,12453,12464,12475,12485],{},[737,12454,12455,12458,12461],{},[755,12456,12457],{},"Root",[755,12459,12460],{},"Smallest element",[755,12462,12463],{},"Largest element",[737,12465,12466,12469,12472],{},[755,12467,12468],{},"Parent vs. child",[755,12470,12471],{},"Parent ≤ children",[755,12473,12474],{},"Parent ≥ children",[737,12476,12477,12479,12482],{},[755,12478,5572],{},[755,12480,12481],{},"Find minimum",[755,12483,12484],{},"Find maximum",[737,12486,12487,12489,12492],{},[755,12488,7018],{},[755,12490,12491],{},"Lowest priority first",[755,12493,12494],{},"Highest priority first",[15,12496,12497],{},"To convert min-heap code to max-heap, simply reverse all comparison operators.",[24,12499,12501],{"id":12500},"heap-vs-bst","Heap vs. BST",[731,12503,12504,12516],{},[734,12505,12506],{},[737,12507,12508,12510,12513],{},[740,12509,742],{},[740,12511,12512],{},"Heap",[740,12514,12515],{},"BST",[750,12517,12518,12527,12536,12544,12553],{},[737,12519,12520,12523,12525],{},[755,12521,12522],{},"Find min\u002Fmax",[755,12524,3903],{},[755,12526,3911],{},[737,12528,12529,12532,12534],{},[755,12530,12531],{},"Search arbitrary",[755,12533,2077],{},[755,12535,3911],{},[737,12537,12538,12540,12542],{},[755,12539,4527],{},[755,12541,3911],{},[755,12543,3911],{},[737,12545,12546,12549,12551],{},[755,12547,12548],{},"Ordered traversal",[755,12550,3926],{},[755,12552,2077],{},[737,12554,12555,12558,12561],{},[755,12556,12557],{},"Memory layout",[755,12559,12560],{},"Array (cache-friendly)",[755,12562,12563],{},"Pointers",[15,12565,12566],{},"Use a heap when you only need the min\u002Fmax. Use a BST when you need arbitrary search or sorted traversal.",[24,12568,1998],{"id":1997},[731,12570,12571,12579],{},[734,12572,12573],{},[737,12574,12575,12577],{},[740,12576,742],{},[740,12578,2009],{},[750,12580,12581,12589,12597,12604,12611,12618],{},[737,12582,12583,12586],{},[755,12584,12585],{},"Structure",[755,12587,12588],{},"Complete binary tree",[737,12590,12591,12594],{},[755,12592,12593],{},"Storage",[755,12595,12596],{},"Array-based",[737,12598,12599,12602],{},[755,12600,12601],{},"Access min\u002Fmax",[755,12603,3903],{},[737,12605,12606,12609],{},[755,12607,12608],{},"Insert\u002FDelete",[755,12610,3911],{},[737,12612,12613,12616],{},[755,12614,12615],{},"Build from array",[755,12617,2077],{},[737,12619,12620,12623],{},[755,12621,12622],{},"Sorted order",[755,12624,12625],{},"No (only root guaranteed)",[850,12627,5733],{},{"title":41,"searchDepth":122,"depth":122,"links":12629},[12630,12631,12632,12633,12638,12639,12640,12641,12642,12643,12644,12645],{"id":11085,"depth":122,"text":11086},{"id":11117,"depth":122,"text":11118},{"id":4495,"depth":122,"text":4496},{"id":892,"depth":122,"text":893,"children":12634},[12635,12636,12637],{"id":11236,"depth":129,"text":11237},{"id":11254,"depth":129,"text":11255},{"id":11275,"depth":129,"text":11276},{"id":4622,"depth":122,"text":4623},{"id":69,"depth":122,"text":70},{"id":1815,"depth":122,"text":1816},{"id":12381,"depth":122,"text":12382},{"id":12393,"depth":122,"text":12394},{"id":12435,"depth":122,"text":12436},{"id":12500,"depth":122,"text":12501},{"id":1997,"depth":122,"text":1998},"Learn how binary heaps work as priority queues with O(log n) insertion and O(1) access to the min\u002Fmax element.",{"timeComplexity":3911,"spaceComplexity":2077},"\u002Flearn\u002Fheap-data-structure","heap",{"title":11070,"description":12646},"learn\u002Fheap-data-structure","I9luZLOB2wZAWdE2bXWPJWGhQXjZlC2ff4sstr9T2J0",{"id":12654,"title":12655,"body":12656,"category":6049,"complexity":862,"date":862,"description":13303,"difficulty":864,"extension":865,"meta":13304,"navigation":221,"order":199,"path":13305,"publishedAt":2079,"relatedAlgorithmId":12649,"seo":13306,"stem":13307,"__hash__":13308},"learn\u002Flearn\u002Fheap-sort.md","Heap Sort",{"type":8,"value":12657,"toc":13293},[12658,12661,12664,12666,12695,12699,12705,12708,12732,12734,12739,12815,12817,13162,13164,13169,13188,13193,13196,13200,13226,13228,13248,13250,13291],[11,12659,12655],{"id":12660},"heap-sort",[15,12662,12663],{},"Heap sort leverages the binary heap data structure to sort an array in O(n log n) time. It first transforms the array into a max-heap, then repeatedly extracts the maximum element and places it at the end. Unlike merge sort, heap sort works in-place with O(1) extra space, and unlike quicksort, it guarantees O(n log n) worst-case performance.",[24,12665,893],{"id":892},[895,12667,12668,12674,12680,12686,12692],{},[46,12669,12670,12673],{},[19,12671,12672],{},"Build a max-heap"," from the input array. A max-heap is a complete binary tree where every parent is greater than or equal to its children.",[46,12675,12676,12679],{},[19,12677,12678],{},"Extract the maximum",": Swap the root (largest element) with the last element of the heap.",[46,12681,12682,12685],{},[19,12683,12684],{},"Reduce heap size"," by one (the extracted element is now in its final position).",[46,12687,12688,12691],{},[19,12689,12690],{},"Heapify the root",": Restore the heap property by sifting the new root down.",[46,12693,12694],{},"Repeat steps 2-4 until the heap is empty.",[24,12696,12698],{"id":12697},"understanding-heapify","Understanding Heapify",[15,12700,10910,12701,12704],{},[39,12702,12703],{},"heapify"," (or sift-down) operation is the core of heap sort. Given a node that may violate the heap property, it compares the node with its children and swaps it with the larger child, continuing downward until the heap property is restored.",[15,12706,12707],{},"For an array representation of a binary heap:",[43,12709,12710,12718,12725],{},[46,12711,12712,12713,12715,12716],{},"Parent of index ",[39,12714,11124],{}," is at ",[39,12717,11134],{},[46,12719,12720,12721,12715,12723],{},"Left child of index ",[39,12722,11124],{},[39,12724,11142],{},[46,12726,12727,12728,12715,12730],{},"Right child of index ",[39,12729,11124],{},[39,12731,11150],{},[24,12733,4623],{"id":4622},[15,12735,12736,12737,4469],{},"Given ",[39,12738,11299],{},[895,12740,12741,12750,12770,12785,12800],{},[46,12742,12743,12746,12747],{},[19,12744,12745],{},"Build max-heap",": Start from the last non-leaf node and heapify down → ",[39,12748,12749],{},"[10, 5, 3, 4, 1]",[46,12751,12752,12755,12756,12759,12760,12762,12763,12766,12767],{},[19,12753,12754],{},"Extract max",": Swap ",[39,12757,12758],{},"10"," with ",[39,12761,189],{}," → ",[39,12764,12765],{},"[1, 5, 3, 4, | 10]",". Heapify → ",[39,12768,12769],{},"[5, 4, 3, 1, | 10]",[46,12771,12772,12755,12774,12759,12777,12762,12779,12766,12782],{},[19,12773,12754],{},[39,12775,12776],{},"5",[39,12778,189],{},[39,12780,12781],{},"[1, 4, 3, | 5, 10]",[39,12783,12784],{},"[4, 1, 3, | 5, 10]",[46,12786,12787,12755,12789,12759,12792,12762,12795,12766,12798],{},[19,12788,12754],{},[39,12790,12791],{},"4",[39,12793,12794],{},"3",[39,12796,12797],{},"[3, 1, | 4, 5, 10]",[39,12799,12797],{},[46,12801,12802,12755,12804,12759,12806,12762,12808,12811,12812],{},[19,12803,12754],{},[39,12805,12794],{},[39,12807,189],{},[39,12809,12810],{},"[1, | 3, 4, 5, 10]",". Done → ",[39,12813,12814],{},"[1, 3, 4, 5, 10]",[24,12816,70],{"id":69},[32,12818,12820],{"className":76,"code":12819,"language":78,"meta":41,"style":41},"def heap_sort(numbers: list[int]) -> list[int]:\n    \"\"\"Sort using a max-heap built in-place.\"\"\"\n    array_length = len(numbers)\n\n    def heapify(heap_size: int, root_index: int) -> None:\n        \"\"\"Sift down the element at root_index to restore heap property.\"\"\"\n        largest = root_index\n        left_child = 2 * root_index + 1\n        right_child = 2 * root_index + 2\n\n        if left_child \u003C heap_size and numbers[left_child] > numbers[largest]:\n            largest = left_child\n\n        if right_child \u003C heap_size and numbers[right_child] > numbers[largest]:\n            largest = right_child\n\n        if largest != root_index:\n            numbers[root_index], numbers[largest] = numbers[largest], numbers[root_index]\n            heapify(heap_size, largest)\n\n    # Build max-heap (start from last non-leaf node)\n    last_non_leaf = array_length \u002F\u002F 2 - 1\n    for i in range(last_non_leaf, -1, -1):\n        heapify(array_length, i)\n\n    # Extract elements one by one\n    for end in range(array_length - 1, 0, -1):\n        numbers[0], numbers[end] = numbers[end], numbers[0]\n        heapify(end, 0)\n\n    return numbers\n",[39,12821,12822,12839,12844,12854,12858,12880,12885,12895,12913,12930,12934,12956,12965,12969,12989,12998,13002,13014,13024,13029,13033,13038,13056,13081,13086,13090,13095,13124,13143,13152,13156],{"__ignoreMap":41},[82,12823,12824,12826,12829,12831,12833,12835,12837],{"class":84,"line":85},[82,12825,89],{"class":88},[82,12827,12828],{"class":92}," heap_sort",[82,12830,1627],{"class":96},[82,12832,101],{"class":100},[82,12834,3503],{"class":96},[82,12836,101],{"class":100},[82,12838,119],{"class":96},[82,12840,12841],{"class":84,"line":122},[82,12842,12843],{"class":125},"    \"\"\"Sort using a max-heap built in-place.\"\"\"\n",[82,12845,12846,12848,12850,12852],{"class":84,"line":129},[82,12847,3776],{"class":96},[82,12849,141],{"class":88},[82,12851,1471],{"class":100},[82,12853,3783],{"class":96},[82,12855,12856],{"class":84,"line":135},[82,12857,222],{"emptyLinePlaceholder":221},[82,12859,12860,12862,12864,12867,12869,12872,12874,12876,12878],{"class":84,"line":147},[82,12861,1176],{"class":88},[82,12863,12089],{"class":92},[82,12865,12866],{"class":96},"(heap_size: ",[82,12868,101],{"class":100},[82,12870,12871],{"class":96},", root_index: ",[82,12873,101],{"class":100},[82,12875,607],{"class":96},[82,12877,1188],{"class":100},[82,12879,523],{"class":96},[82,12881,12882],{"class":84,"line":176},[82,12883,12884],{"class":125},"        \"\"\"Sift down the element at root_index to restore heap property.\"\"\"\n",[82,12886,12887,12890,12892],{"class":84,"line":199},[82,12888,12889],{"class":96},"        largest ",[82,12891,141],{"class":88},[82,12893,12894],{"class":96}," root_index\n",[82,12896,12897,12900,12902,12904,12906,12909,12911],{"class":84,"line":218},[82,12898,12899],{"class":96},"        left_child ",[82,12901,141],{"class":88},[82,12903,8295],{"class":100},[82,12905,11911],{"class":88},[82,12907,12908],{"class":96}," root_index ",[82,12910,406],{"class":88},[82,12912,2260],{"class":100},[82,12914,12915,12918,12920,12922,12924,12926,12928],{"class":84,"line":225},[82,12916,12917],{"class":96},"        right_child ",[82,12919,141],{"class":88},[82,12921,8295],{"class":100},[82,12923,11911],{"class":88},[82,12925,12908],{"class":96},[82,12927,406],{"class":88},[82,12929,3321],{"class":100},[82,12931,12932],{"class":84,"line":236},[82,12933,222],{"emptyLinePlaceholder":221},[82,12935,12936,12938,12941,12943,12946,12948,12951,12953],{"class":84,"line":247},[82,12937,307],{"class":88},[82,12939,12940],{"class":96}," left_child ",[82,12942,425],{"class":88},[82,12944,12945],{"class":96}," heap_size ",[82,12947,3664],{"class":88},[82,12949,12950],{"class":96}," numbers[left_child] ",[82,12952,3461],{"class":88},[82,12954,12955],{"class":96}," numbers[largest]:\n",[82,12957,12958,12960,12962],{"class":84,"line":262},[82,12959,3469],{"class":96},[82,12961,141],{"class":88},[82,12963,12964],{"class":96}," left_child\n",[82,12966,12967],{"class":84,"line":267},[82,12968,222],{"emptyLinePlaceholder":221},[82,12970,12971,12973,12976,12978,12980,12982,12985,12987],{"class":84,"line":276},[82,12972,307],{"class":88},[82,12974,12975],{"class":96}," right_child ",[82,12977,425],{"class":88},[82,12979,12945],{"class":96},[82,12981,3664],{"class":88},[82,12983,12984],{"class":96}," numbers[right_child] ",[82,12986,3461],{"class":88},[82,12988,12955],{"class":96},[82,12990,12991,12993,12995],{"class":84,"line":282},[82,12992,3469],{"class":96},[82,12994,141],{"class":88},[82,12996,12997],{"class":96}," right_child\n",[82,12999,13000],{"class":84,"line":299},[82,13001,222],{"emptyLinePlaceholder":221},[82,13003,13004,13006,13009,13011],{"class":84,"line":304},[82,13005,307],{"class":88},[82,13007,13008],{"class":96}," largest ",[82,13010,515],{"class":88},[82,13012,13013],{"class":96}," root_index:\n",[82,13015,13016,13019,13021],{"class":84,"line":313},[82,13017,13018],{"class":96},"            numbers[root_index], numbers[largest] ",[82,13020,141],{"class":88},[82,13022,13023],{"class":96}," numbers[largest], numbers[root_index]\n",[82,13025,13026],{"class":84,"line":319},[82,13027,13028],{"class":96},"            heapify(heap_size, largest)\n",[82,13030,13031],{"class":84,"line":330},[82,13032,222],{"emptyLinePlaceholder":221},[82,13034,13035],{"class":84,"line":335},[82,13036,13037],{"class":258},"    # Build max-heap (start from last non-leaf node)\n",[82,13039,13040,13043,13045,13048,13050,13052,13054],{"class":84,"line":349},[82,13041,13042],{"class":96},"    last_non_leaf ",[82,13044,141],{"class":88},[82,13046,13047],{"class":96}," array_length ",[82,13049,631],{"class":88},[82,13051,8295],{"class":100},[82,13053,518],{"class":88},[82,13055,2260],{"class":100},[82,13057,13058,13060,13062,13064,13066,13069,13071,13073,13075,13077,13079],{"class":84,"line":355},[82,13059,982],{"class":88},[82,13061,1536],{"class":96},[82,13063,369],{"class":88},[82,13065,1228],{"class":100},[82,13067,13068],{"class":96},"(last_non_leaf, ",[82,13070,186],{"class":88},[82,13072,189],{"class":100},[82,13074,7295],{"class":96},[82,13076,186],{"class":88},[82,13078,189],{"class":100},[82,13080,2554],{"class":96},[82,13082,13083],{"class":84,"line":360},[82,13084,13085],{"class":96},"        heapify(array_length, i)\n",[82,13087,13088],{"class":84,"line":375},[82,13089,222],{"emptyLinePlaceholder":221},[82,13091,13092],{"class":84,"line":384},[82,13093,13094],{"class":258},"    # Extract elements one by one\n",[82,13096,13097,13099,13102,13104,13106,13108,13110,13112,13114,13116,13118,13120,13122],{"class":84,"line":390},[82,13098,982],{"class":88},[82,13100,13101],{"class":96}," end ",[82,13103,369],{"class":88},[82,13105,1228],{"class":100},[82,13107,3811],{"class":96},[82,13109,186],{"class":88},[82,13111,1348],{"class":100},[82,13113,7295],{"class":96},[82,13115,293],{"class":100},[82,13117,7295],{"class":96},[82,13119,186],{"class":88},[82,13121,189],{"class":100},[82,13123,2554],{"class":96},[82,13125,13126,13129,13131,13134,13136,13139,13141],{"class":84,"line":395},[82,13127,13128],{"class":96},"        numbers[",[82,13130,293],{"class":100},[82,13132,13133],{"class":96},"], numbers[end] ",[82,13135,141],{"class":88},[82,13137,13138],{"class":96}," numbers[end], numbers[",[82,13140,293],{"class":100},[82,13142,3224],{"class":96},[82,13144,13145,13148,13150],{"class":84,"line":412},[82,13146,13147],{"class":96},"        heapify(end, ",[82,13149,293],{"class":100},[82,13151,296],{"class":96},[82,13153,13154],{"class":84,"line":417},[82,13155,222],{"emptyLinePlaceholder":221},[82,13157,13158,13160],{"class":84,"line":431},[82,13159,568],{"class":88},[82,13161,3534],{"class":96},[24,13163,1816],{"id":1815},[15,13165,13166],{},[19,13167,13168],{},"Time Complexity: O(n log n)",[43,13170,13171,13176,13182],{},[46,13172,13173,13175],{},[19,13174,12370],{},": O(n) — this is tighter than the naive O(n log n) bound because most nodes are near the bottom and require few sift-down steps.",[46,13177,13178,13181],{},[19,13179,13180],{},"Extract all elements",": n-1 extractions, each requiring O(log n) heapify operations.",[46,13183,13184,13187],{},[19,13185,13186],{},"Total",": O(n) + O(n log n) = O(n log n) in all cases (best, average, worst).",[15,13189,13190],{},[19,13191,13192],{},"Space Complexity: O(1)",[15,13194,13195],{},"Heap sort operates entirely in-place on the input array. The only extra space used is for index variables and the recursive call stack of heapify (which can be made iterative for strict O(1)).",[24,13197,13199],{"id":13198},"when-to-use-heap-sort","When to Use Heap Sort",[43,13201,13202,13208,13214,13220],{},[46,13203,13204,13207],{},[19,13205,13206],{},"Guaranteed O(n log n)",": When you cannot tolerate quicksort's O(n²) worst case (e.g., adversarial input in competitive settings).",[46,13209,13210,13213],{},[19,13211,13212],{},"Memory-constrained environments",": Only O(1) extra space, unlike merge sort's O(n).",[46,13215,13216,13219],{},[19,13217,13218],{},"Priority queue extraction",": If you've already built a heap for other purposes, extracting in sorted order is natural.",[46,13221,13222,13225],{},[19,13223,13224],{},"Embedded systems",": Predictable performance and minimal memory make it suitable for resource-constrained devices.",[24,13227,1938],{"id":1937},[43,13229,13230,13236,13242],{},[46,13231,13232,13235],{},[19,13233,13234],{},"Cache performance matters",": Heap sort's access pattern jumps between parent and child nodes, causing poor cache locality. Quicksort and merge sort typically outperform it on modern CPUs due to sequential access patterns.",[46,13237,13238,13241],{},[19,13239,13240],{},"Stability required",": Heap sort is not stable — equal elements may be reordered.",[46,13243,13244,13247],{},[19,13245,13246],{},"Small arrays",": The overhead of building a heap isn't worth it for small n; insertion sort is simpler and faster.",[24,13249,1998],{"id":1997},[731,13251,13252,13260],{},[734,13253,13254],{},[737,13255,13256,13258],{},[740,13257,742],{},[740,13259,2009],{},[750,13261,13262,13269,13276,13283],{},[737,13263,13264,13267],{},[755,13265,13266],{},"In-place",[755,13268,782],{},[737,13270,13271,13274],{},[755,13272,13273],{},"Stable",[755,13275,3075],{},[737,13277,13278,13281],{},[755,13279,13280],{},"Adaptive",[755,13282,3075],{},[737,13284,13285,13288],{},[755,13286,13287],{},"Worst-case guarantee",[755,13289,13290],{},"Yes — always O(n log n)",[850,13292,852],{},{"title":41,"searchDepth":122,"depth":122,"links":13294},[13295,13296,13297,13298,13299,13300,13301,13302],{"id":892,"depth":122,"text":893},{"id":12697,"depth":122,"text":12698},{"id":4622,"depth":122,"text":4623},{"id":69,"depth":122,"text":70},{"id":1815,"depth":122,"text":1816},{"id":13198,"depth":122,"text":13199},{"id":1937,"depth":122,"text":1938},{"id":1997,"depth":122,"text":1998},"Learn how heap sort uses a binary heap to efficiently sort arrays in O(n log n) time with constant extra space.",{"timeComplexity":3926,"spaceComplexity":3903},"\u002Flearn\u002Fheap-sort",{"title":12655,"description":13303},"learn\u002Fheap-sort","VLrz-kLSR2DUjCvhqivm4iOaMku3BxmjXqLuNqhw5bo",{"id":13310,"title":13311,"body":13312,"category":6049,"complexity":862,"date":862,"description":13724,"difficulty":2462,"extension":865,"meta":13725,"navigation":221,"order":122,"path":13727,"publishedAt":2079,"relatedAlgorithmId":4583,"seo":13728,"stem":13729,"__hash__":13730},"learn\u002Flearn\u002Finsertion-sort.md","Insertion Sort",{"type":8,"value":13313,"toc":13715},[13314,13317,13320,13322,13339,13341,13347,13437,13439,13600,13602,13607,13627,13631,13638,13642,13667,13669,13672,13674,13713],[11,13315,13311],{"id":13316},"insertion-sort",[15,13318,13319],{},"Insertion sort works the way you might sort a hand of playing cards. You pick up one card at a time and insert it into the correct position among the cards you've already sorted. It's intuitive, simple to implement, and surprisingly efficient for small or nearly sorted datasets.",[24,13321,893],{"id":892},[895,13323,13324,13327,13330,13333,13336],{},[46,13325,13326],{},"Start with the second element (index 1) — the first element is already \"sorted\"",[46,13328,13329],{},"Compare the current element with the elements to its left",[46,13331,13332],{},"Shift all larger elements one position to the right",[46,13334,13335],{},"Insert the current element into the gap created",[46,13337,13338],{},"Repeat for every remaining element until the entire array is sorted",[24,13340,4623],{"id":4622},[15,13342,13343,13344,4469],{},"Given the array ",[39,13345,13346],{},"[5, 2, 4, 6, 1, 3]",[43,13348,13349,13369,13390,13405,13422],{},[46,13350,13351,13354,13355,13357,13358,13360,13361,13363,13364,12762,13366],{},[19,13352,13353],{},"Pass 1",": Pick ",[39,13356,8426],{},". Compare with ",[39,13359,12776],{},", shift ",[39,13362,12776],{}," right. Insert ",[39,13365,8426],{},[39,13367,13368],{},"[2, 5, 4, 6, 1, 3]",[46,13370,13371,13354,13374,13357,13376,13360,13378,13380,13381,13384,13385,12762,13387],{},[19,13372,13373],{},"Pass 2",[39,13375,12791],{},[39,13377,12776],{},[39,13379,12776],{}," right. ",[39,13382,13383],{},"2 \u003C 4",", stop. Insert ",[39,13386,12791],{},[39,13388,13389],{},"[2, 4, 5, 6, 1, 3]",[46,13391,13392,13354,13395,13398,13399,13402,13403],{},[19,13393,13394],{},"Pass 3",[39,13396,13397],{},"6",". ",[39,13400,13401],{},"5 \u003C 6",", no shift needed → ",[39,13404,13389],{},[46,13406,13407,13354,13410,13412,13413,13416,13417,12762,13419],{},[19,13408,13409],{},"Pass 4",[39,13411,189],{},". Shift ",[39,13414,13415],{},"6, 5, 4, 2"," all right. Insert ",[39,13418,189],{},[39,13420,13421],{},"[1, 2, 4, 5, 6, 3]",[46,13423,13424,13354,13427,13412,13429,13363,13432,12762,13434],{},[19,13425,13426],{},"Pass 5",[39,13428,12794],{},[39,13430,13431],{},"6, 5, 4",[39,13433,12794],{},[39,13435,13436],{},"[1, 2, 3, 4, 5, 6]",[24,13438,70],{"id":69},[32,13440,13442],{"className":76,"code":13441,"language":78,"meta":41,"style":41},"def insertion_sort(numbers: list[int]) -> list[int]:\n    \"\"\"Sort by inserting each element into its correct position.\"\"\"\n    for i in range(1, len(numbers)):\n        current_value = numbers[i]\n        insert_position = i - 1\n\n        # Shift elements that are greater than current_value to the right\n        while insert_position >= 0 and numbers[insert_position] > current_value:\n            numbers[insert_position + 1] = numbers[insert_position]\n            insert_position -= 1\n\n        # Place the current value in the correct position\n        numbers[insert_position + 1] = current_value\n\n    return numbers\n",[39,13443,13444,13461,13466,13487,13497,13510,13514,13519,13541,13557,13566,13570,13575,13590,13594],{"__ignoreMap":41},[82,13445,13446,13448,13451,13453,13455,13457,13459],{"class":84,"line":85},[82,13447,89],{"class":88},[82,13449,13450],{"class":92}," insertion_sort",[82,13452,1627],{"class":96},[82,13454,101],{"class":100},[82,13456,3503],{"class":96},[82,13458,101],{"class":100},[82,13460,119],{"class":96},[82,13462,13463],{"class":84,"line":122},[82,13464,13465],{"class":125},"    \"\"\"Sort by inserting each element into its correct position.\"\"\"\n",[82,13467,13468,13470,13472,13474,13476,13478,13480,13482,13484],{"class":84,"line":129},[82,13469,982],{"class":88},[82,13471,1536],{"class":96},[82,13473,369],{"class":88},[82,13475,1228],{"class":100},[82,13477,161],{"class":96},[82,13479,189],{"class":100},[82,13481,7295],{"class":96},[82,13483,1545],{"class":100},[82,13485,13486],{"class":96},"(numbers)):\n",[82,13488,13489,13492,13494],{"class":84,"line":135},[82,13490,13491],{"class":96},"        current_value ",[82,13493,141],{"class":88},[82,13495,13496],{"class":96}," numbers[i]\n",[82,13498,13499,13502,13504,13506,13508],{"class":84,"line":147},[82,13500,13501],{"class":96},"        insert_position ",[82,13503,141],{"class":88},[82,13505,1536],{"class":96},[82,13507,186],{"class":88},[82,13509,2260],{"class":100},[82,13511,13512],{"class":84,"line":176},[82,13513,222],{"emptyLinePlaceholder":221},[82,13515,13516],{"class":84,"line":199},[82,13517,13518],{"class":258},"        # Shift elements that are greater than current_value to the right\n",[82,13520,13521,13523,13526,13528,13530,13533,13536,13538],{"class":84,"line":218},[82,13522,4945],{"class":88},[82,13524,13525],{"class":96}," insert_position ",[82,13527,1728],{"class":88},[82,13529,1699],{"class":100},[82,13531,13532],{"class":88}," and",[82,13534,13535],{"class":96}," numbers[insert_position] ",[82,13537,3461],{"class":88},[82,13539,13540],{"class":96}," current_value:\n",[82,13542,13543,13546,13548,13550,13552,13554],{"class":84,"line":225},[82,13544,13545],{"class":96},"            numbers[insert_position ",[82,13547,406],{"class":88},[82,13549,1348],{"class":100},[82,13551,192],{"class":96},[82,13553,141],{"class":88},[82,13555,13556],{"class":96}," numbers[insert_position]\n",[82,13558,13559,13562,13564],{"class":84,"line":236},[82,13560,13561],{"class":96},"            insert_position ",[82,13563,10745],{"class":88},[82,13565,2260],{"class":100},[82,13567,13568],{"class":84,"line":247},[82,13569,222],{"emptyLinePlaceholder":221},[82,13571,13572],{"class":84,"line":262},[82,13573,13574],{"class":258},"        # Place the current value in the correct position\n",[82,13576,13577,13580,13582,13584,13586,13588],{"class":84,"line":267},[82,13578,13579],{"class":96},"        numbers[insert_position ",[82,13581,406],{"class":88},[82,13583,1348],{"class":100},[82,13585,192],{"class":96},[82,13587,141],{"class":88},[82,13589,5951],{"class":96},[82,13591,13592],{"class":84,"line":276},[82,13593,222],{"emptyLinePlaceholder":221},[82,13595,13596,13598],{"class":84,"line":282},[82,13597,568],{"class":88},[82,13599,3534],{"class":96},[24,13601,1816],{"id":1815},[15,13603,13604],{},[19,13605,13606],{},"Time Complexity: O(n²)",[43,13608,13609,13615,13621],{},[46,13610,13611,13614],{},[19,13612,13613],{},"Best case — O(n)",": When the array is already sorted, the inner loop never executes. Each element is compared once with its predecessor, giving exactly n-1 comparisons.",[46,13616,13617,13620],{},[19,13618,13619],{},"Worst case — O(n²)",": When the array is reverse-sorted, every element must be compared against all previously sorted elements, resulting in 1 + 2 + 3 + ... + (n-1) = n(n-1)\u002F2 comparisons.",[46,13622,13623,13626],{},[19,13624,13625],{},"Average case — O(n²)",": On average, each element is compared against half of the sorted portion.",[15,13628,13629],{},[19,13630,13192],{},[15,13632,13633,13634,13637],{},"Insertion sort is an in-place algorithm. It only uses a constant amount of extra memory for the ",[39,13635,13636],{},"current_value"," variable and the index pointer, regardless of input size.",[24,13639,13641],{"id":13640},"when-to-use-insertion-sort","When to Use Insertion Sort",[43,13643,13644,13650,13655,13661],{},[46,13645,13646,13649],{},[19,13647,13648],{},"Small arrays (n \u003C 50)",": The low overhead makes it faster than divide-and-conquer algorithms for tiny inputs. Many optimized implementations of quicksort and merge sort switch to insertion sort below a threshold.",[46,13651,13652,13654],{},[19,13653,6027],{},": If most elements are already close to their final position, insertion sort runs in nearly O(n) time.",[46,13656,13657,13660],{},[19,13658,13659],{},"Online sorting",": When data arrives one element at a time (streaming), insertion sort naturally handles each new element as it comes.",[46,13662,13663,13666],{},[19,13664,13665],{},"Stable sort required",": Insertion sort preserves the relative order of equal elements, making it stable.",[24,13668,1938],{"id":1937},[15,13670,13671],{},"For large datasets (n > 1000), insertion sort's O(n²) performance is unacceptable. Use merge sort, quicksort, or heapsort instead. At n = 10,000, insertion sort performs roughly 50 million comparisons while merge sort does about 130,000.",[24,13673,1998],{"id":1997},[731,13675,13676,13684],{},[734,13677,13678],{},[737,13679,13680,13682],{},[740,13681,742],{},[740,13683,2009],{},[750,13685,13686,13692,13698,13705],{},[737,13687,13688,13690],{},[755,13689,13266],{},[755,13691,782],{},[737,13693,13694,13696],{},[755,13695,13273],{},[755,13697,782],{},[737,13699,13700,13702],{},[755,13701,13280],{},[755,13703,13704],{},"Yes (faster on nearly sorted input)",[737,13706,13707,13710],{},[755,13708,13709],{},"Online",[755,13711,13712],{},"Yes (can sort as data arrives)",[850,13714,852],{},{"title":41,"searchDepth":122,"depth":122,"links":13716},[13717,13718,13719,13720,13721,13722,13723],{"id":892,"depth":122,"text":893},{"id":4622,"depth":122,"text":4623},{"id":69,"depth":122,"text":70},{"id":1815,"depth":122,"text":1816},{"id":13640,"depth":122,"text":13641},{"id":1937,"depth":122,"text":1938},{"id":1997,"depth":122,"text":1998},"Learn how insertion sort builds a sorted array one element at a time by shifting elements into their correct position.",{"timeComplexity":13726,"spaceComplexity":3903},"O(n²)","\u002Flearn\u002Finsertion-sort",{"title":13311,"description":13724},"learn\u002Finsertion-sort","LpIceyavw5tFg90OmJ2tnuhgSS69fTNUXOfASFDGUbk",{"id":13732,"title":13733,"body":13734,"category":4440,"complexity":862,"date":862,"description":13998,"difficulty":2462,"extension":865,"meta":13999,"navigation":221,"order":122,"path":14000,"publishedAt":870,"relatedAlgorithmId":14001,"seo":14002,"stem":14003,"__hash__":14004},"learn\u002Flearn\u002Flinear-search.md","Linear Search",{"type":8,"value":13735,"toc":13988},[13736,13739,13742,13744,13761,13763,13767,13848,13852,13930,13932,13950,13954,13979,13983,13986],[11,13737,13733],{"id":13738},"linear-search",[15,13740,13741],{},"Linear search (or sequential search) is the most straightforward way to find an element in a collection. It checks every element from start to end, one at a time. No sorting required, no data structure assumptions — it works on any list.",[24,13743,893],{"id":892},[895,13745,13746,13749,13752,13755,13758],{},[46,13747,13748],{},"Start at the first element",[46,13750,13751],{},"Compare the current element to the target",[46,13753,13754],{},"If it matches, return the position",[46,13756,13757],{},"If not, move to the next element",[46,13759,13760],{},"If you reach the end without finding it, the target isn't in the array",[24,13762,2520],{"id":2519},[1024,13764,13766],{"id":13765},"find-first-occurrence","Find First Occurrence",[32,13768,13770],{"className":76,"code":13769,"language":78,"meta":41,"style":41},"def linear_search(elements: list[int], target: int) -> int:\n    \"\"\"Search for target by checking each element sequentially.\n    Returns the index if found, -1 otherwise.\"\"\"\n    for position in range(len(elements)):\n        if elements[position] == target:\n            return position\n    return -1\n",[39,13771,13772,13794,13799,13804,13822,13833,13840],{"__ignoreMap":41},[82,13773,13774,13776,13779,13782,13784,13786,13788,13790,13792],{"class":84,"line":85},[82,13775,89],{"class":88},[82,13777,13778],{"class":92}," linear_search",[82,13780,13781],{"class":96},"(elements: list[",[82,13783,101],{"class":100},[82,13785,1632],{"class":96},[82,13787,101],{"class":100},[82,13789,607],{"class":96},[82,13791,101],{"class":100},[82,13793,523],{"class":96},[82,13795,13796],{"class":84,"line":122},[82,13797,13798],{"class":125},"    \"\"\"Search for target by checking each element sequentially.\n",[82,13800,13801],{"class":84,"line":129},[82,13802,13803],{"class":125},"    Returns the index if found, -1 otherwise.\"\"\"\n",[82,13805,13806,13808,13811,13813,13815,13817,13819],{"class":84,"line":135},[82,13807,982],{"class":88},[82,13809,13810],{"class":96}," position ",[82,13812,369],{"class":88},[82,13814,1228],{"class":100},[82,13816,161],{"class":96},[82,13818,1545],{"class":100},[82,13820,13821],{"class":96},"(elements)):\n",[82,13823,13824,13826,13829,13831],{"class":84,"line":147},[82,13825,307],{"class":88},[82,13827,13828],{"class":96}," elements[position] ",[82,13830,343],{"class":88},[82,13832,3333],{"class":96},[82,13834,13835,13837],{"class":84,"line":176},[82,13836,3338],{"class":88},[82,13838,13839],{"class":96}," position\n",[82,13841,13842,13844,13846],{"class":84,"line":199},[82,13843,568],{"class":88},[82,13845,518],{"class":88},[82,13847,3395],{"class":100},[1024,13849,13851],{"id":13850},"find-all-occurrences","Find All Occurrences",[32,13853,13855],{"className":76,"code":13854,"language":78,"meta":41,"style":41},"def linear_search_all(elements: list[int], target: int) -> list[int]:\n    \"\"\"Find ALL positions where target appears.\"\"\"\n    found_positions = []\n    for position in range(len(elements)):\n        if elements[position] == target:\n            found_positions.append(position)\n    return found_positions\n",[39,13856,13857,13878,13883,13892,13908,13918,13923],{"__ignoreMap":41},[82,13858,13859,13861,13864,13866,13868,13870,13872,13874,13876],{"class":84,"line":85},[82,13860,89],{"class":88},[82,13862,13863],{"class":92}," linear_search_all",[82,13865,13781],{"class":96},[82,13867,101],{"class":100},[82,13869,1632],{"class":96},[82,13871,101],{"class":100},[82,13873,2141],{"class":96},[82,13875,101],{"class":100},[82,13877,119],{"class":96},[82,13879,13880],{"class":84,"line":122},[82,13881,13882],{"class":125},"    \"\"\"Find ALL positions where target appears.\"\"\"\n",[82,13884,13885,13888,13890],{"class":84,"line":129},[82,13886,13887],{"class":96},"    found_positions ",[82,13889,141],{"class":88},[82,13891,493],{"class":96},[82,13893,13894,13896,13898,13900,13902,13904,13906],{"class":84,"line":135},[82,13895,982],{"class":88},[82,13897,13810],{"class":96},[82,13899,369],{"class":88},[82,13901,1228],{"class":100},[82,13903,161],{"class":96},[82,13905,1545],{"class":100},[82,13907,13821],{"class":96},[82,13909,13910,13912,13914,13916],{"class":84,"line":147},[82,13911,307],{"class":88},[82,13913,13828],{"class":96},[82,13915,343],{"class":88},[82,13917,3333],{"class":96},[82,13919,13920],{"class":84,"line":176},[82,13921,13922],{"class":96},"            found_positions.append(position)\n",[82,13924,13925,13927],{"class":84,"line":199},[82,13926,568],{"class":88},[82,13928,13929],{"class":96}," found_positions\n",[24,13931,4369],{"id":4368},[43,13933,13934,13940,13945],{},[46,13935,13936,13939],{},[19,13937,13938],{},"Best case",": O(1) — target is the first element",[46,13941,13942,13944],{},[19,13943,10895],{},": O(n) — target is the last element or not present",[46,13946,13947,13949],{},[19,13948,10889],{},": O(n\u002F2) which simplifies to O(n)",[24,13951,13953],{"id":13952},"when-to-use-linear-search","When to Use Linear Search",[43,13955,13956,13963,13969,13976],{},[46,13957,13958,13959,13962],{},"The array is ",[19,13960,13961],{},"unsorted"," (binary search requires sorting)",[46,13964,13958,13965,13968],{},[19,13966,13967],{},"small"," (n \u003C 20, where the overhead of sorting isn't worth it)",[46,13970,13971,13972,13975],{},"You only search ",[19,13973,13974],{},"once"," (sorting + binary search is O(n log n + log n), worse than O(n) for a single query)",[46,13977,13978],{},"The data structure doesn't support random access (linked lists)",[24,13980,13982],{"id":13981},"when-to-upgrade","When to Upgrade",[15,13984,13985],{},"If you search the same collection many times, sort it once and use binary search. The upfront O(n log n) sort cost is amortized over many O(log n) searches, beating repeated O(n) linear scans.",[850,13987,3971],{},{"title":41,"searchDepth":122,"depth":122,"links":13989},[13990,13991,13995,13996,13997],{"id":892,"depth":122,"text":893},{"id":2519,"depth":122,"text":2520,"children":13992},[13993,13994],{"id":13765,"depth":129,"text":13766},{"id":13850,"depth":129,"text":13851},{"id":4368,"depth":122,"text":4369},{"id":13952,"depth":122,"text":13953},{"id":13981,"depth":122,"text":13982},"The simplest search algorithm: check every element one by one until you find the target or exhaust the array.",{"timeComplexity":2077,"spaceComplexity":3903},"\u002Flearn\u002Flinear-search","linear",{"title":13733,"description":13998},"learn\u002Flinear-search","y0tWwepPns2bV93GziPKDhwPYYGltqvajwkStQBTQwI",{"id":14006,"title":14007,"body":14008,"category":6049,"complexity":862,"date":862,"description":14385,"difficulty":864,"extension":865,"meta":14386,"navigation":221,"order":122,"path":14387,"publishedAt":870,"relatedAlgorithmId":14388,"seo":14389,"stem":14390,"__hash__":14391},"learn\u002Flearn\u002Fmerge-sort.md","Merge Sort",{"type":8,"value":14009,"toc":14375},[14010,14013,14016,14018,14038,14041,14043,14047,14134,14138,14292,14296,14313,14316,14320,14325,14339,14344,14355,14359,14373],[11,14011,14007],{"id":14012},"merge-sort",[15,14014,14015],{},"Merge sort is a divide-and-conquer algorithm that splits the array in half, recursively sorts each half, then merges them back together. Unlike quicksort, it guarantees O(n log n) in all cases — no worst-case degradation.",[24,14017,893],{"id":892},[895,14019,14020,14026,14032],{},[46,14021,14022,14025],{},[19,14023,14024],{},"Divide",": Split the array into two halves",[46,14027,14028,14031],{},[19,14029,14030],{},"Conquer",": Recursively sort each half",[46,14033,14034,14037],{},[19,14035,14036],{},"Merge",": Combine the two sorted halves into one sorted array",[15,14039,14040],{},"The merge step is where the real work happens — it takes two already-sorted arrays and interleaves them into one sorted result.",[24,14042,2520],{"id":2519},[1024,14044,14046],{"id":14045},"main-sort-function","Main Sort Function",[32,14048,14050],{"className":76,"code":14049,"language":78,"meta":41,"style":41},"def merge_sort(numbers: list[int]) -> list[int]:\n    \"\"\"Sort by recursively splitting and merging.\"\"\"\n    if len(numbers) \u003C= 1:\n        return numbers\n\n    midpoint = len(numbers) \u002F\u002F 2\n    left_half = merge_sort(numbers[:midpoint])\n    right_half = merge_sort(numbers[midpoint:])\n    return merge(left_half, right_half)\n",[39,14051,14052,14068,14073,14087,14093,14097,14111,14119,14127],{"__ignoreMap":41},[82,14053,14054,14056,14058,14060,14062,14064,14066],{"class":84,"line":85},[82,14055,89],{"class":88},[82,14057,3496],{"class":92},[82,14059,1627],{"class":96},[82,14061,101],{"class":100},[82,14063,3503],{"class":96},[82,14065,101],{"class":100},[82,14067,119],{"class":96},[82,14069,14070],{"class":84,"line":122},[82,14071,14072],{"class":125},"    \"\"\"Sort by recursively splitting and merging.\"\"\"\n",[82,14074,14075,14077,14079,14081,14083,14085],{"class":84,"line":129},[82,14076,960],{"class":88},[82,14078,1471],{"class":100},[82,14080,3521],{"class":96},[82,14082,3298],{"class":88},[82,14084,1348],{"class":100},[82,14086,523],{"class":96},[82,14088,14089,14091],{"class":84,"line":135},[82,14090,2655],{"class":88},[82,14092,3534],{"class":96},[82,14094,14095],{"class":84,"line":147},[82,14096,222],{"emptyLinePlaceholder":221},[82,14098,14099,14101,14103,14105,14107,14109],{"class":84,"line":176},[82,14100,3543],{"class":96},[82,14102,141],{"class":88},[82,14104,1471],{"class":100},[82,14106,3521],{"class":96},[82,14108,631],{"class":88},[82,14110,3321],{"class":100},[82,14112,14113,14115,14117],{"class":84,"line":199},[82,14114,3558],{"class":96},[82,14116,141],{"class":88},[82,14118,3563],{"class":96},[82,14120,14121,14123,14125],{"class":84,"line":218},[82,14122,3568],{"class":96},[82,14124,141],{"class":88},[82,14126,3573],{"class":96},[82,14128,14129,14131],{"class":84,"line":225},[82,14130,568],{"class":88},[82,14132,14133],{"class":96}," merge(left_half, right_half)\n",[1024,14135,14137],{"id":14136},"merge-function","Merge Function",[32,14139,14141],{"className":76,"code":14140,"language":78,"meta":41,"style":41},"def merge(left_array: list[int], right_array: list[int]) -> list[int]:\n    \"\"\"Merge two sorted arrays into one sorted result.\"\"\"\n    merged_result = []\n    left_index = 0\n    right_index = 0\n\n    while left_index \u003C len(left_array) and right_index \u003C len(right_array):\n        if left_array[left_index] \u003C= right_array[right_index]:\n            merged_result.append(left_array[left_index])\n            left_index += 1\n        else:\n            merged_result.append(right_array[right_index])\n            right_index += 1\n\n    # Append remaining elements (one of these will be empty)\n    merged_result.extend(left_array[left_index:])\n    merged_result.extend(right_array[right_index:])\n    return merged_result\n",[39,14142,14143,14166,14171,14179,14187,14195,14199,14223,14235,14240,14248,14254,14259,14267,14271,14276,14281,14286],{"__ignoreMap":41},[82,14144,14145,14147,14150,14153,14155,14158,14160,14162,14164],{"class":84,"line":85},[82,14146,89],{"class":88},[82,14148,14149],{"class":92}," merge",[82,14151,14152],{"class":96},"(left_array: list[",[82,14154,101],{"class":100},[82,14156,14157],{"class":96},"], right_array: list[",[82,14159,101],{"class":100},[82,14161,3503],{"class":96},[82,14163,101],{"class":100},[82,14165,119],{"class":96},[82,14167,14168],{"class":84,"line":122},[82,14169,14170],{"class":125},"    \"\"\"Merge two sorted arrays into one sorted result.\"\"\"\n",[82,14172,14173,14175,14177],{"class":84,"line":129},[82,14174,3621],{"class":96},[82,14176,141],{"class":88},[82,14178,493],{"class":96},[82,14180,14181,14183,14185],{"class":84,"line":135},[82,14182,3630],{"class":96},[82,14184,141],{"class":88},[82,14186,233],{"class":100},[82,14188,14189,14191,14193],{"class":84,"line":147},[82,14190,3639],{"class":96},[82,14192,141],{"class":88},[82,14194,233],{"class":100},[82,14196,14197],{"class":84,"line":176},[82,14198,222],{"emptyLinePlaceholder":221},[82,14200,14201,14203,14205,14207,14209,14212,14214,14216,14218,14220],{"class":84,"line":199},[82,14202,270],{"class":88},[82,14204,3654],{"class":96},[82,14206,425],{"class":88},[82,14208,1471],{"class":100},[82,14210,14211],{"class":96},"(left_array) ",[82,14213,3664],{"class":88},[82,14215,3667],{"class":96},[82,14217,425],{"class":88},[82,14219,1471],{"class":100},[82,14221,14222],{"class":96},"(right_array):\n",[82,14224,14225,14227,14230,14232],{"class":84,"line":218},[82,14226,307],{"class":88},[82,14228,14229],{"class":96}," left_array[left_index] ",[82,14231,3298],{"class":88},[82,14233,14234],{"class":96}," right_array[right_index]:\n",[82,14236,14237],{"class":84,"line":225},[82,14238,14239],{"class":96},"            merged_result.append(left_array[left_index])\n",[82,14241,14242,14244,14246],{"class":84,"line":236},[82,14243,3696],{"class":96},[82,14245,2257],{"class":88},[82,14247,2260],{"class":100},[82,14249,14250,14252],{"class":84,"line":247},[82,14251,3371],{"class":88},[82,14253,523],{"class":96},[82,14255,14256],{"class":84,"line":262},[82,14257,14258],{"class":96},"            merged_result.append(right_array[right_index])\n",[82,14260,14261,14263,14265],{"class":84,"line":267},[82,14262,3716],{"class":96},[82,14264,2257],{"class":88},[82,14266,2260],{"class":100},[82,14268,14269],{"class":84,"line":276},[82,14270,222],{"emptyLinePlaceholder":221},[82,14272,14273],{"class":84,"line":282},[82,14274,14275],{"class":258},"    # Append remaining elements (one of these will be empty)\n",[82,14277,14278],{"class":84,"line":299},[82,14279,14280],{"class":96},"    merged_result.extend(left_array[left_index:])\n",[82,14282,14283],{"class":84,"line":304},[82,14284,14285],{"class":96},"    merged_result.extend(right_array[right_index:])\n",[82,14287,14288,14290],{"class":84,"line":313},[82,14289,568],{"class":88},[82,14291,3741],{"class":96},[24,14293,14295],{"id":14294},"why-on-log-n-is-guaranteed","Why O(n log n) is Guaranteed",[43,14297,14298,14304,14310],{},[46,14299,14300,14303],{},[19,14301,14302],{},"log n levels"," of recursion (array halves each time)",[46,14305,14306,14309],{},[19,14307,14308],{},"O(n) work per level"," (merging touches each element once)",[46,14311,14312],{},"Total: O(n log n) regardless of input order",[15,14314,14315],{},"This is the key advantage over quicksort — merge sort never degrades to O(n^2).",[24,14317,14319],{"id":14318},"trade-offs","Trade-Offs",[15,14321,14322],{},[19,14323,14324],{},"Advantages:",[43,14326,14327,14330,14333,14336],{},[46,14328,14329],{},"Guaranteed O(n log n) worst case",[46,14331,14332],{},"Stable sort (preserves relative order of equal elements)",[46,14334,14335],{},"Works well with linked lists (no random access needed)",[46,14337,14338],{},"Excellent for external sorting (data on disk)",[15,14340,14341],{},[19,14342,14343],{},"Disadvantages:",[43,14345,14346,14349,14352],{},[46,14347,14348],{},"Requires O(n) extra space for merging",[46,14350,14351],{},"Slightly slower than quicksort in practice due to cache misses",[46,14353,14354],{},"More memory allocations",[24,14356,14358],{"id":14357},"when-to-use-merge-sort","When to Use Merge Sort",[43,14360,14361,14364,14367,14370],{},[46,14362,14363],{},"When stability matters (database sorting, UI lists)",[46,14365,14366],{},"When guaranteed worst-case performance is required",[46,14368,14369],{},"When sorting linked lists",[46,14371,14372],{},"When sorting data that doesn't fit in memory (external merge sort)",[850,14374,8156],{},{"title":41,"searchDepth":122,"depth":122,"links":14376},[14377,14378,14382,14383,14384],{"id":892,"depth":122,"text":893},{"id":2519,"depth":122,"text":2520,"children":14379},[14380,14381],{"id":14045,"depth":129,"text":14046},{"id":14136,"depth":129,"text":14137},{"id":14294,"depth":122,"text":14295},{"id":14318,"depth":122,"text":14319},{"id":14357,"depth":122,"text":14358},"Learn how merge sort guarantees O(n log n) performance by dividing, sorting, and merging subarrays.",{"timeComplexity":3926,"spaceComplexity":2077},"\u002Flearn\u002Fmerge-sort","merge",{"title":14007,"description":14385},"learn\u002Fmerge-sort","-TUztr2_5N1mjCUclpn08KDtTcH_kY9sG00-jq3geZ4",{"id":14393,"title":14394,"body":14395,"category":5751,"complexity":862,"date":862,"description":15469,"difficulty":2462,"extension":865,"meta":15470,"navigation":221,"order":122,"path":15471,"publishedAt":2079,"relatedAlgorithmId":2490,"seo":15472,"stem":15473,"__hash__":15474},"learn\u002Flearn\u002Fqueues.md","Queues",{"type":8,"value":14396,"toc":15457},[14397,14400,14407,14409,14485,14487,14506,14509,14511,14514,14520,14522,14873,14877,14880,15232,15234,15239,15242,15246,15249,15253,15306,15310,15347,15351,15410,15412,15455],[11,14398,14394],{"id":14399},"queues",[15,14401,14402,14403,14406],{},"A queue is a linear data structure that follows the ",[19,14404,14405],{},"First-In, First-Out (FIFO)"," principle. Think of people waiting in line — the first person who arrives is the first person served. Elements are added at the back (enqueue) and removed from the front (dequeue). This ordering makes queues fundamental to scheduling, buffering, and breadth-first traversal.",[24,14408,4496],{"id":4495},[731,14410,14411,14421],{},[734,14412,14413],{},[737,14414,14415,14417,14419],{},[740,14416,4505],{},[740,14418,11177],{},[740,14420,4369],{},[750,14422,14423,14435,14447,14461,14473],{},[737,14424,14425,14430,14433],{},[755,14426,14427],{},[39,14428,14429],{},"enqueue(item)",[755,14431,14432],{},"Add an element to the back",[755,14434,3903],{},[737,14436,14437,14442,14445],{},[755,14438,14439],{},[39,14440,14441],{},"dequeue()",[755,14443,14444],{},"Remove and return the front element",[755,14446,3903],{},[737,14448,14449,14456,14459],{},[755,14450,14451,11187,14453],{},[39,14452,11186],{},[39,14454,14455],{},"front()",[755,14457,14458],{},"View the front element without removing it",[755,14460,3903],{},[737,14462,14463,14468,14471],{},[755,14464,14465],{},[39,14466,14467],{},"is_empty()",[755,14469,14470],{},"Check if the queue is empty",[755,14472,3903],{},[737,14474,14475,14480,14483],{},[755,14476,14477],{},[39,14478,14479],{},"size()",[755,14481,14482],{},"Return the number of elements",[755,14484,3903],{},[24,14486,893],{"id":892},[895,14488,14489,14495,14501],{},[46,14490,14491,14494],{},[19,14492,14493],{},"Enqueue",": Add a new element to the rear of the queue. Advance the rear pointer.",[46,14496,14497,14500],{},[19,14498,14499],{},"Dequeue",": Remove the element at the front. Advance the front pointer. Return the removed element.",[46,14502,14503,14505],{},[19,14504,12353],{},": Read the front element without modifying the queue.",[15,14507,14508],{},"A queue maintains two pointers — one for the front (where elements leave) and one for the rear (where elements enter).",[24,14510,4623],{"id":4622},[15,14512,14513],{},"Starting with an empty queue:",[32,14515,14518],{"className":14516,"code":14517,"language":37},[35],"enqueue(10) → Queue: [10]          (front=10, rear=10)\nenqueue(20) → Queue: [10, 20]     (front=10, rear=20)\nenqueue(30) → Queue: [10, 20, 30] (front=10, rear=30)\ndequeue()   → Returns 10, Queue: [20, 30] (front=20, rear=30)\npeek()      → Returns 20, Queue: [20, 30] (unchanged)\ndequeue()   → Returns 20, Queue: [30] (front=30, rear=30)\n",[39,14519,14517],{"__ignoreMap":41},[24,14521,70],{"id":69},[32,14523,14525],{"className":76,"code":14524,"language":78,"meta":41,"style":41},"class Queue:\n    \"\"\"Queue implementation using a list with front pointer for O(1) operations.\"\"\"\n\n    def __init__(self):\n        self._items = []\n        self._front = 0\n\n    def enqueue(self, item) -> None:\n        \"\"\"Add an element to the back of the queue.\"\"\"\n        self._items.append(item)\n\n    def dequeue(self):\n        \"\"\"Remove and return the front element. Raises error if empty.\"\"\"\n        if self.is_empty():\n            raise IndexError(\"Dequeue from empty queue\")\n        item = self._items[self._front]\n        self._front += 1\n\n        # Reclaim memory when half the list is unused\n        if self._front > len(self._items) \u002F\u002F 2:\n            self._items = self._items[self._front:]\n            self._front = 0\n\n        return item\n\n    def peek(self):\n        \"\"\"Return the front element without removing it.\"\"\"\n        if self.is_empty():\n            raise IndexError(\"Peek at empty queue\")\n        return self._items[self._front]\n\n    def is_empty(self) -> bool:\n        \"\"\"Check if the queue has no elements.\"\"\"\n        return self._front >= len(self._items)\n\n    def size(self) -> int:\n        \"\"\"Return the number of elements in the queue.\"\"\"\n        return len(self._items) - self._front\n",[39,14526,14527,14536,14541,14545,14553,14564,14575,14579,14593,14598,14605,14609,14618,14623,14631,14644,14661,14671,14675,14680,14705,14722,14732,14736,14743,14747,14755,14760,14768,14781,14793,14797,14809,14814,14833,14837,14849,14854],{"__ignoreMap":41},[82,14528,14529,14531,14534],{"class":84,"line":85},[82,14530,2534],{"class":88},[82,14532,14533],{"class":92}," Queue",[82,14535,523],{"class":96},[82,14537,14538],{"class":84,"line":122},[82,14539,14540],{"class":125},"    \"\"\"Queue implementation using a list with front pointer for O(1) operations.\"\"\"\n",[82,14542,14543],{"class":84,"line":129},[82,14544,222],{"emptyLinePlaceholder":221},[82,14546,14547,14549,14551],{"class":84,"line":135},[82,14548,1176],{"class":88},[82,14550,2546],{"class":100},[82,14552,4753],{"class":96},[82,14554,14555,14557,14560,14562],{"class":84,"line":147},[82,14556,2559],{"class":100},[82,14558,14559],{"class":96},"._items ",[82,14561,141],{"class":88},[82,14563,493],{"class":96},[82,14565,14566,14568,14571,14573],{"class":84,"line":176},[82,14567,2559],{"class":100},[82,14569,14570],{"class":96},"._front ",[82,14572,141],{"class":88},[82,14574,233],{"class":100},[82,14576,14577],{"class":84,"line":199},[82,14578,222],{"emptyLinePlaceholder":221},[82,14580,14581,14583,14586,14589,14591],{"class":84,"line":218},[82,14582,1176],{"class":88},[82,14584,14585],{"class":92}," enqueue",[82,14587,14588],{"class":96},"(self, item) -> ",[82,14590,1188],{"class":100},[82,14592,523],{"class":96},[82,14594,14595],{"class":84,"line":225},[82,14596,14597],{"class":125},"        \"\"\"Add an element to the back of the queue.\"\"\"\n",[82,14599,14600,14602],{"class":84,"line":236},[82,14601,2559],{"class":100},[82,14603,14604],{"class":96},"._items.append(item)\n",[82,14606,14607],{"class":84,"line":247},[82,14608,222],{"emptyLinePlaceholder":221},[82,14610,14611,14613,14616],{"class":84,"line":262},[82,14612,1176],{"class":88},[82,14614,14615],{"class":92}," dequeue",[82,14617,4753],{"class":96},[82,14619,14620],{"class":84,"line":267},[82,14621,14622],{"class":125},"        \"\"\"Remove and return the front element. Raises error if empty.\"\"\"\n",[82,14624,14625,14627,14629],{"class":84,"line":276},[82,14626,307],{"class":88},[82,14628,2658],{"class":100},[82,14630,11499],{"class":96},[82,14632,14633,14635,14637,14639,14642],{"class":84,"line":282},[82,14634,11504],{"class":88},[82,14636,11507],{"class":100},[82,14638,161],{"class":96},[82,14640,14641],{"class":125},"\"Dequeue from empty queue\"",[82,14643,296],{"class":96},[82,14645,14646,14649,14651,14653,14656,14658],{"class":84,"line":299},[82,14647,14648],{"class":96},"        item ",[82,14650,141],{"class":88},[82,14652,2658],{"class":100},[82,14654,14655],{"class":96},"._items[",[82,14657,4806],{"class":100},[82,14659,14660],{"class":96},"._front]\n",[82,14662,14663,14665,14667,14669],{"class":84,"line":304},[82,14664,2559],{"class":100},[82,14666,14570],{"class":96},[82,14668,2257],{"class":88},[82,14670,2260],{"class":100},[82,14672,14673],{"class":84,"line":313},[82,14674,222],{"emptyLinePlaceholder":221},[82,14676,14677],{"class":84,"line":319},[82,14678,14679],{"class":258},"        # Reclaim memory when half the list is unused\n",[82,14681,14682,14684,14686,14688,14690,14692,14694,14696,14699,14701,14703],{"class":84,"line":330},[82,14683,307],{"class":88},[82,14685,2658],{"class":100},[82,14687,14570],{"class":96},[82,14689,3461],{"class":88},[82,14691,1471],{"class":100},[82,14693,161],{"class":96},[82,14695,4806],{"class":100},[82,14697,14698],{"class":96},"._items) ",[82,14700,631],{"class":88},[82,14702,8295],{"class":100},[82,14704,523],{"class":96},[82,14706,14707,14709,14711,14713,14715,14717,14719],{"class":84,"line":335},[82,14708,5423],{"class":100},[82,14710,14559],{"class":96},[82,14712,141],{"class":88},[82,14714,2658],{"class":100},[82,14716,14655],{"class":96},[82,14718,4806],{"class":100},[82,14720,14721],{"class":96},"._front:]\n",[82,14723,14724,14726,14728,14730],{"class":84,"line":349},[82,14725,5423],{"class":100},[82,14727,14570],{"class":96},[82,14729,141],{"class":88},[82,14731,233],{"class":100},[82,14733,14734],{"class":84,"line":355},[82,14735,222],{"emptyLinePlaceholder":221},[82,14737,14738,14740],{"class":84,"line":360},[82,14739,2655],{"class":88},[82,14741,14742],{"class":96}," item\n",[82,14744,14745],{"class":84,"line":375},[82,14746,222],{"emptyLinePlaceholder":221},[82,14748,14749,14751,14753],{"class":84,"line":384},[82,14750,1176],{"class":88},[82,14752,11479],{"class":92},[82,14754,4753],{"class":96},[82,14756,14757],{"class":84,"line":390},[82,14758,14759],{"class":125},"        \"\"\"Return the front element without removing it.\"\"\"\n",[82,14761,14762,14764,14766],{"class":84,"line":395},[82,14763,307],{"class":88},[82,14765,2658],{"class":100},[82,14767,11499],{"class":96},[82,14769,14770,14772,14774,14776,14779],{"class":84,"line":412},[82,14771,11504],{"class":88},[82,14773,11507],{"class":100},[82,14775,161],{"class":96},[82,14777,14778],{"class":125},"\"Peek at empty queue\"",[82,14780,296],{"class":96},[82,14782,14783,14785,14787,14789,14791],{"class":84,"line":417},[82,14784,2655],{"class":88},[82,14786,2658],{"class":100},[82,14788,14655],{"class":96},[82,14790,4806],{"class":100},[82,14792,14660],{"class":96},[82,14794,14795],{"class":84,"line":431},[82,14796,222],{"emptyLinePlaceholder":221},[82,14798,14799,14801,14803,14805,14807],{"class":84,"line":442},[82,14800,1176],{"class":88},[82,14802,11445],{"class":92},[82,14804,10773],{"class":96},[82,14806,4921],{"class":100},[82,14808,523],{"class":96},[82,14810,14811],{"class":84,"line":453},[82,14812,14813],{"class":125},"        \"\"\"Check if the queue has no elements.\"\"\"\n",[82,14815,14816,14818,14820,14822,14824,14826,14828,14830],{"class":84,"line":468},[82,14817,2655],{"class":88},[82,14819,2658],{"class":100},[82,14821,14570],{"class":96},[82,14823,1728],{"class":88},[82,14825,1471],{"class":100},[82,14827,161],{"class":96},[82,14829,4806],{"class":100},[82,14831,14832],{"class":96},"._items)\n",[82,14834,14835],{"class":84,"line":474},[82,14836,222],{"emptyLinePlaceholder":221},[82,14838,14839,14841,14843,14845,14847],{"class":84,"line":479},[82,14840,1176],{"class":88},[82,14842,11415],{"class":92},[82,14844,10773],{"class":96},[82,14846,101],{"class":100},[82,14848,523],{"class":96},[82,14850,14851],{"class":84,"line":485},[82,14852,14853],{"class":125},"        \"\"\"Return the number of elements in the queue.\"\"\"\n",[82,14855,14856,14858,14860,14862,14864,14866,14868,14870],{"class":84,"line":496},[82,14857,2655],{"class":88},[82,14859,1471],{"class":100},[82,14861,161],{"class":96},[82,14863,4806],{"class":100},[82,14865,14698],{"class":96},[82,14867,186],{"class":88},[82,14869,2658],{"class":100},[82,14871,14872],{"class":96},"._front\n",[24,14874,14876],{"id":14875},"circular-queue-fixed-size","Circular Queue (Fixed-Size)",[15,14878,14879],{},"A circular queue uses a fixed-size array and wraps around when reaching the end. This avoids wasted space:",[32,14881,14883],{"className":76,"code":14882,"language":78,"meta":41,"style":41},"class CircularQueue:\n    \"\"\"Fixed-size queue using circular array indexing.\"\"\"\n\n    def __init__(self, capacity: int):\n        self._items = [None] * capacity\n        self._capacity = capacity\n        self._front = 0\n        self._rear = 0\n        self._size = 0\n\n    def enqueue(self, item) -> bool:\n        \"\"\"Add element. Returns False if full.\"\"\"\n        if self._size == self._capacity:\n            return False\n        self._items[self._rear] = item\n        self._rear = (self._rear + 1) % self._capacity\n        self._size += 1\n        return True\n\n    def dequeue(self):\n        \"\"\"Remove and return front element.\"\"\"\n        if self._size == 0:\n            raise IndexError(\"Dequeue from empty queue\")\n        item = self._items[self._front]\n        self._front = (self._front + 1) % self._capacity\n        self._size -= 1\n        return item\n\n    def is_empty(self) -> bool:\n        return self._size == 0\n\n    def is_full(self) -> bool:\n        return self._size == self._capacity\n",[39,14884,14885,14894,14899,14903,14915,14933,14943,14953,14964,14974,14978,14990,14995,15010,15016,15031,15058,15068,15074,15078,15086,15091,15105,15117,15131,15157,15167,15173,15177,15189,15201,15205,15218],{"__ignoreMap":41},[82,14886,14887,14889,14892],{"class":84,"line":85},[82,14888,2534],{"class":88},[82,14890,14891],{"class":92}," CircularQueue",[82,14893,523],{"class":96},[82,14895,14896],{"class":84,"line":122},[82,14897,14898],{"class":125},"    \"\"\"Fixed-size queue using circular array indexing.\"\"\"\n",[82,14900,14901],{"class":84,"line":129},[82,14902,222],{"emptyLinePlaceholder":221},[82,14904,14905,14907,14909,14911,14913],{"class":84,"line":135},[82,14906,1176],{"class":88},[82,14908,2546],{"class":100},[82,14910,10263],{"class":96},[82,14912,101],{"class":100},[82,14914,2554],{"class":96},[82,14916,14917,14919,14921,14923,14925,14927,14929,14931],{"class":84,"line":147},[82,14918,2559],{"class":100},[82,14920,14559],{"class":96},[82,14922,141],{"class":88},[82,14924,155],{"class":96},[82,14926,1188],{"class":100},[82,14928,192],{"class":96},[82,14930,170],{"class":88},[82,14932,10285],{"class":96},[82,14934,14935,14937,14939,14941],{"class":84,"line":176},[82,14936,2559],{"class":100},[82,14938,10280],{"class":96},[82,14940,141],{"class":88},[82,14942,10285],{"class":96},[82,14944,14945,14947,14949,14951],{"class":84,"line":199},[82,14946,2559],{"class":100},[82,14948,14570],{"class":96},[82,14950,141],{"class":88},[82,14952,233],{"class":100},[82,14954,14955,14957,14960,14962],{"class":84,"line":218},[82,14956,2559],{"class":100},[82,14958,14959],{"class":96},"._rear ",[82,14961,141],{"class":88},[82,14963,233],{"class":100},[82,14965,14966,14968,14970,14972],{"class":84,"line":225},[82,14967,2559],{"class":100},[82,14969,10292],{"class":96},[82,14971,141],{"class":88},[82,14973,233],{"class":100},[82,14975,14976],{"class":84,"line":236},[82,14977,222],{"emptyLinePlaceholder":221},[82,14979,14980,14982,14984,14986,14988],{"class":84,"line":247},[82,14981,1176],{"class":88},[82,14983,14585],{"class":92},[82,14985,14588],{"class":96},[82,14987,4921],{"class":100},[82,14989,523],{"class":96},[82,14991,14992],{"class":84,"line":262},[82,14993,14994],{"class":125},"        \"\"\"Add element. Returns False if full.\"\"\"\n",[82,14996,14997,14999,15001,15003,15005,15007],{"class":84,"line":267},[82,14998,307],{"class":88},[82,15000,2658],{"class":100},[82,15002,10292],{"class":96},[82,15004,343],{"class":88},[82,15006,2658],{"class":100},[82,15008,15009],{"class":96},"._capacity:\n",[82,15011,15012,15014],{"class":84,"line":276},[82,15013,3338],{"class":88},[82,15015,1592],{"class":100},[82,15017,15018,15020,15022,15024,15027,15029],{"class":84,"line":282},[82,15019,2559],{"class":100},[82,15021,14655],{"class":96},[82,15023,4806],{"class":100},[82,15025,15026],{"class":96},"._rear] ",[82,15028,141],{"class":88},[82,15030,14742],{"class":96},[82,15032,15033,15035,15037,15039,15042,15044,15046,15048,15050,15052,15054,15056],{"class":84,"line":299},[82,15034,2559],{"class":100},[82,15036,14959],{"class":96},[82,15038,141],{"class":88},[82,15040,15041],{"class":96}," (",[82,15043,4806],{"class":100},[82,15045,14959],{"class":96},[82,15047,406],{"class":88},[82,15049,1348],{"class":100},[82,15051,8318],{"class":96},[82,15053,637],{"class":88},[82,15055,2658],{"class":100},[82,15057,10416],{"class":96},[82,15059,15060,15062,15064,15066],{"class":84,"line":304},[82,15061,2559],{"class":100},[82,15063,10292],{"class":96},[82,15065,2257],{"class":88},[82,15067,2260],{"class":100},[82,15069,15070,15072],{"class":84,"line":313},[82,15071,2655],{"class":88},[82,15073,327],{"class":100},[82,15075,15076],{"class":84,"line":319},[82,15077,222],{"emptyLinePlaceholder":221},[82,15079,15080,15082,15084],{"class":84,"line":330},[82,15081,1176],{"class":88},[82,15083,14615],{"class":92},[82,15085,4753],{"class":96},[82,15087,15088],{"class":84,"line":335},[82,15089,15090],{"class":125},"        \"\"\"Remove and return front element.\"\"\"\n",[82,15092,15093,15095,15097,15099,15101,15103],{"class":84,"line":349},[82,15094,307],{"class":88},[82,15096,2658],{"class":100},[82,15098,10292],{"class":96},[82,15100,343],{"class":88},[82,15102,1699],{"class":100},[82,15104,523],{"class":96},[82,15106,15107,15109,15111,15113,15115],{"class":84,"line":355},[82,15108,11504],{"class":88},[82,15110,11507],{"class":100},[82,15112,161],{"class":96},[82,15114,14641],{"class":125},[82,15116,296],{"class":96},[82,15118,15119,15121,15123,15125,15127,15129],{"class":84,"line":360},[82,15120,14648],{"class":96},[82,15122,141],{"class":88},[82,15124,2658],{"class":100},[82,15126,14655],{"class":96},[82,15128,4806],{"class":100},[82,15130,14660],{"class":96},[82,15132,15133,15135,15137,15139,15141,15143,15145,15147,15149,15151,15153,15155],{"class":84,"line":375},[82,15134,2559],{"class":100},[82,15136,14570],{"class":96},[82,15138,141],{"class":88},[82,15140,15041],{"class":96},[82,15142,4806],{"class":100},[82,15144,14570],{"class":96},[82,15146,406],{"class":88},[82,15148,1348],{"class":100},[82,15150,8318],{"class":96},[82,15152,637],{"class":88},[82,15154,2658],{"class":100},[82,15156,10416],{"class":96},[82,15158,15159,15161,15163,15165],{"class":84,"line":384},[82,15160,2559],{"class":100},[82,15162,10292],{"class":96},[82,15164,10745],{"class":88},[82,15166,2260],{"class":100},[82,15168,15169,15171],{"class":84,"line":390},[82,15170,2655],{"class":88},[82,15172,14742],{"class":96},[82,15174,15175],{"class":84,"line":395},[82,15176,222],{"emptyLinePlaceholder":221},[82,15178,15179,15181,15183,15185,15187],{"class":84,"line":412},[82,15180,1176],{"class":88},[82,15182,11445],{"class":92},[82,15184,10773],{"class":96},[82,15186,4921],{"class":100},[82,15188,523],{"class":96},[82,15190,15191,15193,15195,15197,15199],{"class":84,"line":417},[82,15192,2655],{"class":88},[82,15194,2658],{"class":100},[82,15196,10292],{"class":96},[82,15198,343],{"class":88},[82,15200,233],{"class":100},[82,15202,15203],{"class":84,"line":431},[82,15204,222],{"emptyLinePlaceholder":221},[82,15206,15207,15209,15212,15214,15216],{"class":84,"line":442},[82,15208,1176],{"class":88},[82,15210,15211],{"class":92}," is_full",[82,15213,10773],{"class":96},[82,15215,4921],{"class":100},[82,15217,523],{"class":96},[82,15219,15220,15222,15224,15226,15228,15230],{"class":84,"line":453},[82,15221,2655],{"class":88},[82,15223,2658],{"class":100},[82,15225,10292],{"class":96},[82,15227,343],{"class":88},[82,15229,2658],{"class":100},[82,15231,10416],{"class":96},[24,15233,1816],{"id":1815},[15,15235,15236],{},[19,15237,15238],{},"Time Complexity: O(1) per operation",[15,15240,15241],{},"Every queue operation (enqueue, dequeue, peek) takes constant time. There's no traversal — you always work with the front or rear pointer directly.",[15,15243,15244],{},[19,15245,1846],{},[15,15247,15248],{},"The queue uses space proportional to the number of elements currently stored.",[24,15250,15252],{"id":15251},"queue-variants","Queue Variants",[731,15254,15255,15264],{},[734,15256,15257],{},[737,15258,15259,15262],{},[740,15260,15261],{},"Variant",[740,15263,11177],{},[750,15265,15266,15276,15286,15296],{},[737,15267,15268,15273],{},[755,15269,15270],{},[19,15271,15272],{},"Simple Queue",[755,15274,15275],{},"Basic FIFO — enqueue at rear, dequeue from front",[737,15277,15278,15283],{},[755,15279,15280],{},[19,15281,15282],{},"Circular Queue",[755,15284,15285],{},"Fixed-size with wrap-around indexing",[737,15287,15288,15293],{},[755,15289,15290],{},[19,15291,15292],{},"Double-ended Queue (Deque)",[755,15294,15295],{},"Add\u002Fremove from both ends",[737,15297,15298,15303],{},[755,15299,15300],{},[19,15301,15302],{},"Priority Queue",[755,15304,15305],{},"Dequeue returns highest-priority element (uses heap)",[24,15307,15309],{"id":15308},"when-to-use-queues","When to Use Queues",[43,15311,15312,15317,15323,15329,15335,15341],{},[46,15313,15314,15316],{},[19,15315,2086],{},": Queues power level-by-level graph\u002Ftree traversal.",[46,15318,15319,15322],{},[19,15320,15321],{},"Task scheduling",": Operating systems use queues to schedule CPU processes (round-robin).",[46,15324,15325,15328],{},[19,15326,15327],{},"Message buffering",": Message queues (RabbitMQ, SQS) buffer work between producers and consumers.",[46,15330,15331,15334],{},[19,15332,15333],{},"Print spooling",": Documents queue up and print in the order submitted.",[46,15336,15337,15340],{},[19,15338,15339],{},"Rate limiting",": Sliding window rate limiters use queues to track request timestamps.",[46,15342,15343,15346],{},[19,15344,15345],{},"Stream processing",": Data pipelines buffer events in queues between processing stages.",[24,15348,15350],{"id":15349},"stack-vs-queue","Stack vs. Queue",[731,15352,15353,15365],{},[734,15354,15355],{},[737,15356,15357,15359,15362],{},[740,15358,742],{},[740,15360,15361],{},"Stack (LIFO)",[740,15363,15364],{},"Queue (FIFO)",[750,15366,15367,15378,15388,15399],{},[737,15368,15369,15372,15375],{},[755,15370,15371],{},"Add to",[755,15373,15374],{},"Top",[755,15376,15377],{},"Back",[737,15379,15380,15383,15385],{},[755,15381,15382],{},"Remove from",[755,15384,15374],{},[755,15386,15387],{},"Front",[737,15389,15390,15393,15396],{},[755,15391,15392],{},"Traversal style",[755,15394,15395],{},"Depth-first",[755,15397,15398],{},"Breadth-first",[737,15400,15401,15404,15407],{},[755,15402,15403],{},"Real-world analogy",[755,15405,15406],{},"Stack of plates",[755,15408,15409],{},"Line at a store",[24,15411,1998],{"id":1997},[731,15413,15414,15422],{},[734,15415,15416],{},[737,15417,15418,15420],{},[740,15419,742],{},[740,15421,2009],{},[750,15423,15424,15432,15439,15447],{},[737,15425,15426,15429],{},[755,15427,15428],{},"Access pattern",[755,15430,15431],{},"FIFO (First-In, First-Out)",[737,15433,15434,15437],{},[755,15435,15436],{},"Enqueue\u002FDequeue",[755,15438,3903],{},[737,15440,15441,15444],{},[755,15442,15443],{},"Random access",[755,15445,15446],{},"Not supported",[737,15448,15449,15452],{},[755,15450,15451],{},"Variants",[755,15453,15454],{},"Circular, Deque, Priority",[850,15456,5733],{},{"title":41,"searchDepth":122,"depth":122,"links":15458},[15459,15460,15461,15462,15463,15464,15465,15466,15467,15468],{"id":4495,"depth":122,"text":4496},{"id":892,"depth":122,"text":893},{"id":4622,"depth":122,"text":4623},{"id":69,"depth":122,"text":70},{"id":14875,"depth":122,"text":14876},{"id":1815,"depth":122,"text":1816},{"id":15251,"depth":122,"text":15252},{"id":15308,"depth":122,"text":15309},{"id":15349,"depth":122,"text":15350},{"id":1997,"depth":122,"text":1998},"Learn how the queue data structure works with First-In-First-Out (FIFO) ordering, its variants, and real-world applications.",{"timeComplexity":3903,"spaceComplexity":2077},"\u002Flearn\u002Fqueues",{"title":14394,"description":15469},"learn\u002Fqueues","wXM9NeoFwUJdC7njARhGcJLjd1BjB3jeCeBktnZHdQY",{"id":15476,"title":15477,"body":15478,"category":6049,"complexity":862,"date":862,"description":15888,"difficulty":864,"extension":865,"meta":15889,"navigation":221,"order":129,"path":15890,"publishedAt":870,"relatedAlgorithmId":15891,"seo":15892,"stem":15893,"__hash__":15894},"learn\u002Flearn\u002Fquicksort-explained.md","Quick Sort",{"type":8,"value":15479,"toc":15879},[15480,15484,15491,15493,15497,15623,15627,15785,15789,15792,15806,15809,15814,15834,15838,15841,15847,15853,15859,15863,15877],[11,15481,15483],{"id":15482},"quicksort-explained","Quicksort Explained",[15,15485,15486,15487,15490],{},"Quicksort is a divide-and-conquer sorting algorithm that works by selecting a ",[19,15488,15489],{},"pivot"," element, partitioning the array so all smaller elements go left and all larger go right, then recursively sorting each partition.",[24,15492,2520],{"id":2519},[1024,15494,15496],{"id":15495},"quicksort-main-function","Quicksort (Main Function)",[32,15498,15500],{"className":76,"code":15499,"language":78,"meta":41,"style":41},"def quicksort(array: list[int], start: int = 0, end: int = None) -> None:\n    \"\"\"Sort array in-place using quicksort with Lomuto partition.\"\"\"\n    if end is None:\n        end = len(array) - 1\n    if start >= end:\n        return\n\n    pivot_final_index = partition(array, start, end)\n    quicksort(array, start, pivot_final_index - 1)\n    quicksort(array, pivot_final_index + 1, end)\n",[39,15501,15502,15537,15542,15554,15570,15582,15586,15590,15600,15611],{"__ignoreMap":41},[82,15503,15504,15506,15509,15512,15514,15516,15518,15520,15522,15525,15527,15529,15531,15533,15535],{"class":84,"line":85},[82,15505,89],{"class":88},[82,15507,15508],{"class":92}," quicksort",[82,15510,15511],{"class":96},"(array: list[",[82,15513,101],{"class":100},[82,15515,9376],{"class":96},[82,15517,101],{"class":100},[82,15519,10268],{"class":88},[82,15521,1699],{"class":100},[82,15523,15524],{"class":96},", end: ",[82,15526,101],{"class":100},[82,15528,10268],{"class":88},[82,15530,4839],{"class":100},[82,15532,607],{"class":96},[82,15534,1188],{"class":100},[82,15536,523],{"class":96},[82,15538,15539],{"class":84,"line":122},[82,15540,15541],{"class":125},"    \"\"\"Sort array in-place using quicksort with Lomuto partition.\"\"\"\n",[82,15543,15544,15546,15548,15550,15552],{"class":84,"line":129},[82,15545,960],{"class":88},[82,15547,13101],{"class":96},[82,15549,4836],{"class":88},[82,15551,4839],{"class":100},[82,15553,523],{"class":96},[82,15555,15556,15559,15561,15563,15566,15568],{"class":84,"line":135},[82,15557,15558],{"class":96},"        end ",[82,15560,141],{"class":88},[82,15562,1471],{"class":100},[82,15564,15565],{"class":96},"(array) ",[82,15567,186],{"class":88},[82,15569,2260],{"class":100},[82,15571,15572,15574,15577,15579],{"class":84,"line":147},[82,15573,960],{"class":88},[82,15575,15576],{"class":96}," start ",[82,15578,1728],{"class":88},[82,15580,15581],{"class":96}," end:\n",[82,15583,15584],{"class":84,"line":176},[82,15585,973],{"class":88},[82,15587,15588],{"class":84,"line":199},[82,15589,222],{"emptyLinePlaceholder":221},[82,15591,15592,15595,15597],{"class":84,"line":218},[82,15593,15594],{"class":96},"    pivot_final_index ",[82,15596,141],{"class":88},[82,15598,15599],{"class":96}," partition(array, start, end)\n",[82,15601,15602,15605,15607,15609],{"class":84,"line":225},[82,15603,15604],{"class":96},"    quicksort(array, start, pivot_final_index ",[82,15606,186],{"class":88},[82,15608,1348],{"class":100},[82,15610,296],{"class":96},[82,15612,15613,15616,15618,15620],{"class":84,"line":236},[82,15614,15615],{"class":96},"    quicksort(array, pivot_final_index ",[82,15617,406],{"class":88},[82,15619,1348],{"class":100},[82,15621,15622],{"class":96},", end)\n",[1024,15624,15626],{"id":15625},"lomuto-partition","Lomuto Partition",[32,15628,15630],{"className":76,"code":15629,"language":78,"meta":41,"style":41},"def partition(array: list[int], start: int, end: int) -> int:\n    \"\"\"Partition array around the last element as pivot.\n\n    After partition:\n    - All elements left of pivot_final_index are \u003C= pivot\n    - All elements right of pivot_final_index are > pivot\n    \"\"\"\n    pivot_value = array[end]\n    insert_position = start\n\n    for current_index in range(start, end):\n        if array[current_index] \u003C= pivot_value:\n            array[insert_position], array[current_index] = (\n                array[current_index], array[insert_position]\n            )\n            insert_position += 1\n\n    # Place pivot in its final sorted position\n    array[insert_position], array[end] = array[end], array[insert_position]\n    return insert_position\n",[39,15631,15632,15657,15662,15666,15671,15676,15681,15685,15695,15704,15708,15721,15733,15742,15747,15751,15759,15763,15768,15778],{"__ignoreMap":41},[82,15633,15634,15636,15639,15641,15643,15645,15647,15649,15651,15653,15655],{"class":84,"line":85},[82,15635,89],{"class":88},[82,15637,15638],{"class":92}," partition",[82,15640,15511],{"class":96},[82,15642,101],{"class":100},[82,15644,9376],{"class":96},[82,15646,101],{"class":100},[82,15648,15524],{"class":96},[82,15650,101],{"class":100},[82,15652,607],{"class":96},[82,15654,101],{"class":100},[82,15656,523],{"class":96},[82,15658,15659],{"class":84,"line":122},[82,15660,15661],{"class":125},"    \"\"\"Partition array around the last element as pivot.\n",[82,15663,15664],{"class":84,"line":129},[82,15665,222],{"emptyLinePlaceholder":221},[82,15667,15668],{"class":84,"line":135},[82,15669,15670],{"class":125},"    After partition:\n",[82,15672,15673],{"class":84,"line":147},[82,15674,15675],{"class":125},"    - All elements left of pivot_final_index are \u003C= pivot\n",[82,15677,15678],{"class":84,"line":176},[82,15679,15680],{"class":125},"    - All elements right of pivot_final_index are > pivot\n",[82,15682,15683],{"class":84,"line":199},[82,15684,1094],{"class":125},[82,15686,15687,15690,15692],{"class":84,"line":218},[82,15688,15689],{"class":96},"    pivot_value ",[82,15691,141],{"class":88},[82,15693,15694],{"class":96}," array[end]\n",[82,15696,15697,15700,15702],{"class":84,"line":225},[82,15698,15699],{"class":96},"    insert_position ",[82,15701,141],{"class":88},[82,15703,9404],{"class":96},[82,15705,15706],{"class":84,"line":236},[82,15707,222],{"emptyLinePlaceholder":221},[82,15709,15710,15712,15714,15716,15718],{"class":84,"line":247},[82,15711,982],{"class":88},[82,15713,3804],{"class":96},[82,15715,369],{"class":88},[82,15717,1228],{"class":100},[82,15719,15720],{"class":96},"(start, end):\n",[82,15722,15723,15725,15728,15730],{"class":84,"line":262},[82,15724,307],{"class":88},[82,15726,15727],{"class":96}," array[current_index] ",[82,15729,3298],{"class":88},[82,15731,15732],{"class":96}," pivot_value:\n",[82,15734,15735,15738,15740],{"class":84,"line":267},[82,15736,15737],{"class":96},"            array[insert_position], array[current_index] ",[82,15739,141],{"class":88},[82,15741,3854],{"class":96},[82,15743,15744],{"class":84,"line":276},[82,15745,15746],{"class":96},"                array[current_index], array[insert_position]\n",[82,15748,15749],{"class":84,"line":282},[82,15750,12064],{"class":96},[82,15752,15753,15755,15757],{"class":84,"line":299},[82,15754,13561],{"class":96},[82,15756,2257],{"class":88},[82,15758,2260],{"class":100},[82,15760,15761],{"class":84,"line":304},[82,15762,222],{"emptyLinePlaceholder":221},[82,15764,15765],{"class":84,"line":313},[82,15766,15767],{"class":258},"    # Place pivot in its final sorted position\n",[82,15769,15770,15773,15775],{"class":84,"line":319},[82,15771,15772],{"class":96},"    array[insert_position], array[end] ",[82,15774,141],{"class":88},[82,15776,15777],{"class":96}," array[end], array[insert_position]\n",[82,15779,15780,15782],{"class":84,"line":330},[82,15781,568],{"class":88},[82,15783,15784],{"class":96}," insert_position\n",[24,15786,15788],{"id":15787},"why-pivot-selection-matters","Why Pivot Selection Matters",[15,15790,15791],{},"Quicksort's efficiency depends entirely on how well the pivot splits the array:",[43,15793,15794,15800],{},[46,15795,15796,15799],{},[19,15797,15798],{},"Perfect split"," (pivot is the median): Each level halves the array — O(n log n)",[46,15801,15802,15805],{},[19,15803,15804],{},"Worst split"," (pivot is always min or max): One partition has n-1 elements — O(n^2)",[15,15807,15808],{},"The worst case happens when the array is already sorted and you always pick the first or last element as pivot.",[15,15810,15811],{},[19,15812,15813],{},"Mitigation strategies:",[895,15815,15816,15822,15828],{},[46,15817,15818,15821],{},[19,15819,15820],{},"Median-of-three",": Pick the median of the first, middle, and last elements",[46,15823,15824,15827],{},[19,15825,15826],{},"Random pivot",": Select a random element — makes worst-case astronomically unlikely",[46,15829,15830,15833],{},[19,15831,15832],{},"Introsort",": Switch to heapsort if recursion depth exceeds 2 log(n) — guaranteed O(n log n)",[24,15835,15837],{"id":15836},"when-quicksort-beats-mergesort","When Quicksort Beats Mergesort",[15,15839,15840],{},"Both are O(n log n) on average, but quicksort wins in practice for several reasons:",[15,15842,15843,15846],{},[19,15844,15845],{},"Cache locality",": Quicksort operates on contiguous memory, making excellent use of CPU cache lines. Mergesort's merge step accesses two separate arrays, causing more cache misses.",[15,15848,15849,15852],{},[19,15850,15851],{},"In-place sorting",": Quicksort needs only O(log n) extra space for the recursion stack. Mergesort requires O(n) auxiliary space.",[15,15854,15855,15858],{},[19,15856,15857],{},"When mergesort wins",": Mergesort guarantees O(n log n) worst case, is stable (preserves equal-element order), and works well with linked lists.",[24,15860,15862],{"id":15861},"practical-takeaways","Practical Takeaways",[43,15864,15865,15868,15871,15874],{},[46,15866,15867],{},"Use quicksort (or introsort) for general-purpose in-memory sorting",[46,15869,15870],{},"Use mergesort when you need stability or guaranteed worst-case performance",[46,15872,15873],{},"Always randomize pivot selection in production",[46,15875,15876],{},"For small subarrays (n \u003C 16), switch to insertion sort — lower constant factors",[850,15878,8156],{},{"title":41,"searchDepth":122,"depth":122,"links":15880},[15881,15885,15886,15887],{"id":2519,"depth":122,"text":2520,"children":15882},[15883,15884],{"id":15495,"depth":129,"text":15496},{"id":15625,"depth":129,"text":15626},{"id":15787,"depth":122,"text":15788},{"id":15836,"depth":122,"text":15837},{"id":15861,"depth":122,"text":15862},"Learn how quicksort's divide-and-conquer strategy works, why pivot selection matters, and when it outperforms mergesort.",{"timeComplexity":3926,"spaceComplexity":3911},"\u002Flearn\u002Fquicksort-explained","quick",{"title":15477,"description":15888},"learn\u002Fquicksort-explained","lyBuL5c99vd3LqMV0F4MpMzR_RHST_4iq2WhRO6Bl_o",{"id":15896,"title":15897,"body":15898,"category":6049,"complexity":862,"date":862,"description":16805,"difficulty":864,"extension":865,"meta":16806,"navigation":221,"order":225,"path":16807,"publishedAt":2079,"relatedAlgorithmId":16808,"seo":16809,"stem":16810,"__hash__":16811},"learn\u002Flearn\u002Fradix-sort.md","Radix Sort",{"type":8,"value":15899,"toc":16795},[15900,15903,15906,15908,15930,15937,15939,15944,15949,15987,15992,16028,16033,16058,16060,16286,16289,16599,16601,16606,16625,16628,16633,16636,16640,16666,16668,16694,16698,16749,16752,16754,16793],[11,15901,15897],{"id":15902},"radix-sort",[15,15904,15905],{},"Radix sort is a non-comparison sorting algorithm that sorts integers by processing individual digits. Instead of comparing elements against each other, it distributes elements into buckets based on each digit, from the least significant digit (LSD) to the most significant digit (MSD). This allows it to sort in O(nk) time, where k is the number of digits — potentially faster than comparison-based sorts for certain inputs.",[24,15907,893],{"id":892},[895,15909,15910,15913,15924,15927],{},[46,15911,15912],{},"Find the maximum number to determine how many digit positions to process",[46,15914,15915,15916],{},"Starting from the least significant digit (ones place):\n",[43,15917,15918,15921],{},[46,15919,15920],{},"Distribute all elements into 10 buckets (0-9) based on the current digit",[46,15922,15923],{},"Collect elements from buckets in order (0 first, then 1, ..., then 9)",[46,15925,15926],{},"Move to the next digit position (tens, hundreds, ...) and repeat",[46,15928,15929],{},"After processing all digit positions, the array is sorted",[15,15931,15932,15933,15936],{},"The algorithm relies on a ",[19,15934,15935],{},"stable"," distribution step — elements with the same digit maintain their relative order from the previous pass. This is why sorting from LSD to MSD works correctly.",[24,15938,4623],{"id":4622},[15,15940,12736,15941,4469],{},[39,15942,15943],{},"[170, 45, 75, 90, 802, 24, 2, 66]",[15,15945,15946],{},[19,15947,15948],{},"Pass 1 — ones digit:",[43,15950,15951,15957,15963,15969,15975,15981],{},[46,15952,15953,15954],{},"Bucket 0: ",[82,15955,15956],{},"170, 90",[46,15958,15959,15960],{},"Bucket 2: ",[82,15961,15962],{},"802, 2",[46,15964,15965,15966],{},"Bucket 4: ",[82,15967,15968],{},"24",[46,15970,15971,15972],{},"Bucket 5: ",[82,15973,15974],{},"45, 75",[46,15976,15977,15978],{},"Bucket 6: ",[82,15979,15980],{},"66",[46,15982,15983,15984],{},"Collect: ",[39,15985,15986],{},"[170, 90, 802, 2, 24, 45, 75, 66]",[15,15988,15989],{},[19,15990,15991],{},"Pass 2 — tens digit:",[43,15993,15994,15998,16002,16007,16011,16017,16023],{},[46,15995,15953,15996],{},[82,15997,15962],{},[46,15999,15959,16000],{},[82,16001,15968],{},[46,16003,15965,16004],{},[82,16005,16006],{},"45",[46,16008,15977,16009],{},[82,16010,15980],{},[46,16012,16013,16014],{},"Bucket 7: ",[82,16015,16016],{},"170, 75",[46,16018,16019,16020],{},"Bucket 9: ",[82,16021,16022],{},"90",[46,16024,15983,16025],{},[39,16026,16027],{},"[802, 2, 24, 45, 66, 170, 75, 90]",[15,16029,16030],{},[19,16031,16032],{},"Pass 3 — hundreds digit:",[43,16034,16035,16040,16046,16052],{},[46,16036,15953,16037],{},[82,16038,16039],{},"2, 24, 45, 66, 75, 90",[46,16041,16042,16043],{},"Bucket 1: ",[82,16044,16045],{},"170",[46,16047,16048,16049],{},"Bucket 8: ",[82,16050,16051],{},"802",[46,16053,15983,16054,16057],{},[39,16055,16056],{},"[2, 24, 45, 66, 75, 90, 170, 802]"," ✓",[24,16059,70],{"id":69},[32,16061,16063],{"className":76,"code":16062,"language":78,"meta":41,"style":41},"def radix_sort(numbers: list[int]) -> list[int]:\n    \"\"\"Sort non-negative integers by processing digits from LSD to MSD.\"\"\"\n    if not numbers:\n        return numbers\n\n    max_value = max(numbers)\n    digit_position = 1  # Start with ones place\n\n    while digit_position \u003C= max_value:\n        # Create 10 buckets (one per digit 0-9)\n        buckets = [[] for _ in range(10)]\n\n        # Distribute elements into buckets based on current digit\n        for number in numbers:\n            digit = (number \u002F\u002F digit_position) % 10\n            buckets[digit].append(number)\n\n        # Collect elements from buckets in order\n        numbers = []\n        for bucket in buckets:\n            for number in bucket:\n                numbers.append(number)\n\n        digit_position *= 10\n\n    return numbers\n",[39,16064,16065,16082,16087,16095,16101,16105,16117,16129,16133,16145,16150,16174,16178,16183,16194,16214,16219,16223,16228,16237,16248,16258,16263,16267,16276,16280],{"__ignoreMap":41},[82,16066,16067,16069,16072,16074,16076,16078,16080],{"class":84,"line":85},[82,16068,89],{"class":88},[82,16070,16071],{"class":92}," radix_sort",[82,16073,1627],{"class":96},[82,16075,101],{"class":100},[82,16077,3503],{"class":96},[82,16079,101],{"class":100},[82,16081,119],{"class":96},[82,16083,16084],{"class":84,"line":122},[82,16085,16086],{"class":125},"    \"\"\"Sort non-negative integers by processing digits from LSD to MSD.\"\"\"\n",[82,16088,16089,16091,16093],{"class":84,"line":129},[82,16090,960],{"class":88},[82,16092,2300],{"class":88},[82,16094,3452],{"class":96},[82,16096,16097,16099],{"class":84,"line":135},[82,16098,2655],{"class":88},[82,16100,3534],{"class":96},[82,16102,16103],{"class":84,"line":147},[82,16104,222],{"emptyLinePlaceholder":221},[82,16106,16107,16110,16112,16115],{"class":84,"line":176},[82,16108,16109],{"class":96},"    max_value ",[82,16111,141],{"class":88},[82,16113,16114],{"class":100}," max",[82,16116,3783],{"class":96},[82,16118,16119,16122,16124,16126],{"class":84,"line":199},[82,16120,16121],{"class":96},"    digit_position ",[82,16123,141],{"class":88},[82,16125,1348],{"class":100},[82,16127,16128],{"class":258},"  # Start with ones place\n",[82,16130,16131],{"class":84,"line":218},[82,16132,222],{"emptyLinePlaceholder":221},[82,16134,16135,16137,16140,16142],{"class":84,"line":225},[82,16136,270],{"class":88},[82,16138,16139],{"class":96}," digit_position ",[82,16141,3298],{"class":88},[82,16143,16144],{"class":96}," max_value:\n",[82,16146,16147],{"class":84,"line":236},[82,16148,16149],{"class":258},"        # Create 10 buckets (one per digit 0-9)\n",[82,16151,16152,16155,16157,16159,16161,16163,16165,16167,16169,16171],{"class":84,"line":247},[82,16153,16154],{"class":96},"        buckets ",[82,16156,141],{"class":88},[82,16158,2578],{"class":96},[82,16160,2581],{"class":88},[82,16162,2584],{"class":96},[82,16164,369],{"class":88},[82,16166,1228],{"class":100},[82,16168,161],{"class":96},[82,16170,12758],{"class":100},[82,16172,16173],{"class":96},")]\n",[82,16175,16176],{"class":84,"line":262},[82,16177,222],{"emptyLinePlaceholder":221},[82,16179,16180],{"class":84,"line":267},[82,16181,16182],{"class":258},"        # Distribute elements into buckets based on current digit\n",[82,16184,16185,16187,16190,16192],{"class":84,"line":276},[82,16186,363],{"class":88},[82,16188,16189],{"class":96}," number ",[82,16191,369],{"class":88},[82,16193,3452],{"class":96},[82,16195,16196,16199,16201,16204,16206,16209,16211],{"class":84,"line":282},[82,16197,16198],{"class":96},"            digit ",[82,16200,141],{"class":88},[82,16202,16203],{"class":96}," (number ",[82,16205,631],{"class":88},[82,16207,16208],{"class":96}," digit_position) ",[82,16210,637],{"class":88},[82,16212,16213],{"class":100}," 10\n",[82,16215,16216],{"class":84,"line":299},[82,16217,16218],{"class":96},"            buckets[digit].append(number)\n",[82,16220,16221],{"class":84,"line":304},[82,16222,222],{"emptyLinePlaceholder":221},[82,16224,16225],{"class":84,"line":313},[82,16226,16227],{"class":258},"        # Collect elements from buckets in order\n",[82,16229,16230,16233,16235],{"class":84,"line":319},[82,16231,16232],{"class":96},"        numbers ",[82,16234,141],{"class":88},[82,16236,493],{"class":96},[82,16238,16239,16241,16243,16245],{"class":84,"line":330},[82,16240,363],{"class":88},[82,16242,10851],{"class":96},[82,16244,369],{"class":88},[82,16246,16247],{"class":96}," buckets:\n",[82,16249,16250,16252,16254,16256],{"class":84,"line":335},[82,16251,10861],{"class":88},[82,16253,16189],{"class":96},[82,16255,369],{"class":88},[82,16257,10636],{"class":96},[82,16259,16260],{"class":84,"line":349},[82,16261,16262],{"class":96},"                numbers.append(number)\n",[82,16264,16265],{"class":84,"line":355},[82,16266,222],{"emptyLinePlaceholder":221},[82,16268,16269,16272,16274],{"class":84,"line":360},[82,16270,16271],{"class":96},"        digit_position ",[82,16273,10803],{"class":88},[82,16275,16213],{"class":100},[82,16277,16278],{"class":84,"line":375},[82,16279,222],{"emptyLinePlaceholder":221},[82,16281,16282,16284],{"class":84,"line":384},[82,16283,568],{"class":88},[82,16285,3534],{"class":96},[15,16287,16288],{},"Here's an alternative using counting sort as the stable subroutine (more memory-efficient):",[32,16290,16292],{"className":76,"code":16291,"language":78,"meta":41,"style":41},"def radix_sort_counting(numbers: list[int]) -> list[int]:\n    \"\"\"Radix sort using counting sort for each digit pass.\"\"\"\n    if not numbers:\n        return numbers\n\n    max_value = max(numbers)\n    digit_position = 1\n\n    while digit_position \u003C= max_value:\n        output = [0] * len(numbers)\n        count = [0] * 10\n\n        # Count occurrences of each digit\n        for number in numbers:\n            digit = (number \u002F\u002F digit_position) % 10\n            count[digit] += 1\n\n        # Compute cumulative counts (positions)\n        for i in range(1, 10):\n            count[i] += count[i - 1]\n\n        # Build output array (traverse input in reverse for stability)\n        for i in range(len(numbers) - 1, -1, -1):\n            digit = (numbers[i] \u002F\u002F digit_position) % 10\n            count[digit] -= 1\n            output[count[digit]] = numbers[i]\n\n        numbers = output\n        digit_position *= 10\n\n    return numbers\n",[39,16293,16294,16311,16316,16324,16330,16334,16344,16352,16356,16366,16385,16402,16406,16411,16421,16437,16446,16450,16455,16475,16491,16495,16500,16534,16551,16559,16568,16572,16581,16589,16593],{"__ignoreMap":41},[82,16295,16296,16298,16301,16303,16305,16307,16309],{"class":84,"line":85},[82,16297,89],{"class":88},[82,16299,16300],{"class":92}," radix_sort_counting",[82,16302,1627],{"class":96},[82,16304,101],{"class":100},[82,16306,3503],{"class":96},[82,16308,101],{"class":100},[82,16310,119],{"class":96},[82,16312,16313],{"class":84,"line":122},[82,16314,16315],{"class":125},"    \"\"\"Radix sort using counting sort for each digit pass.\"\"\"\n",[82,16317,16318,16320,16322],{"class":84,"line":129},[82,16319,960],{"class":88},[82,16321,2300],{"class":88},[82,16323,3452],{"class":96},[82,16325,16326,16328],{"class":84,"line":135},[82,16327,2655],{"class":88},[82,16329,3534],{"class":96},[82,16331,16332],{"class":84,"line":147},[82,16333,222],{"emptyLinePlaceholder":221},[82,16335,16336,16338,16340,16342],{"class":84,"line":176},[82,16337,16109],{"class":96},[82,16339,141],{"class":88},[82,16341,16114],{"class":100},[82,16343,3783],{"class":96},[82,16345,16346,16348,16350],{"class":84,"line":199},[82,16347,16121],{"class":96},[82,16349,141],{"class":88},[82,16351,2260],{"class":100},[82,16353,16354],{"class":84,"line":218},[82,16355,222],{"emptyLinePlaceholder":221},[82,16357,16358,16360,16362,16364],{"class":84,"line":225},[82,16359,270],{"class":88},[82,16361,16139],{"class":96},[82,16363,3298],{"class":88},[82,16365,16144],{"class":96},[82,16367,16368,16371,16373,16375,16377,16379,16381,16383],{"class":84,"line":236},[82,16369,16370],{"class":96},"        output ",[82,16372,141],{"class":88},[82,16374,155],{"class":96},[82,16376,293],{"class":100},[82,16378,192],{"class":96},[82,16380,170],{"class":88},[82,16382,1471],{"class":100},[82,16384,3783],{"class":96},[82,16386,16387,16390,16392,16394,16396,16398,16400],{"class":84,"line":247},[82,16388,16389],{"class":96},"        count ",[82,16391,141],{"class":88},[82,16393,155],{"class":96},[82,16395,293],{"class":100},[82,16397,192],{"class":96},[82,16399,170],{"class":88},[82,16401,16213],{"class":100},[82,16403,16404],{"class":84,"line":262},[82,16405,222],{"emptyLinePlaceholder":221},[82,16407,16408],{"class":84,"line":267},[82,16409,16410],{"class":258},"        # Count occurrences of each digit\n",[82,16412,16413,16415,16417,16419],{"class":84,"line":276},[82,16414,363],{"class":88},[82,16416,16189],{"class":96},[82,16418,369],{"class":88},[82,16420,3452],{"class":96},[82,16422,16423,16425,16427,16429,16431,16433,16435],{"class":84,"line":282},[82,16424,16198],{"class":96},[82,16426,141],{"class":88},[82,16428,16203],{"class":96},[82,16430,631],{"class":88},[82,16432,16208],{"class":96},[82,16434,637],{"class":88},[82,16436,16213],{"class":100},[82,16438,16439,16442,16444],{"class":84,"line":299},[82,16440,16441],{"class":96},"            count[digit] ",[82,16443,2257],{"class":88},[82,16445,2260],{"class":100},[82,16447,16448],{"class":84,"line":304},[82,16449,222],{"emptyLinePlaceholder":221},[82,16451,16452],{"class":84,"line":313},[82,16453,16454],{"class":258},"        # Compute cumulative counts (positions)\n",[82,16456,16457,16459,16461,16463,16465,16467,16469,16471,16473],{"class":84,"line":319},[82,16458,363],{"class":88},[82,16460,1536],{"class":96},[82,16462,369],{"class":88},[82,16464,1228],{"class":100},[82,16466,161],{"class":96},[82,16468,189],{"class":100},[82,16470,7295],{"class":96},[82,16472,12758],{"class":100},[82,16474,2554],{"class":96},[82,16476,16477,16480,16482,16485,16487,16489],{"class":84,"line":330},[82,16478,16479],{"class":96},"            count[i] ",[82,16481,2257],{"class":88},[82,16483,16484],{"class":96}," count[i ",[82,16486,186],{"class":88},[82,16488,1348],{"class":100},[82,16490,3224],{"class":96},[82,16492,16493],{"class":84,"line":335},[82,16494,222],{"emptyLinePlaceholder":221},[82,16496,16497],{"class":84,"line":349},[82,16498,16499],{"class":258},"        # Build output array (traverse input in reverse for stability)\n",[82,16501,16502,16504,16506,16508,16510,16512,16514,16516,16518,16520,16522,16524,16526,16528,16530,16532],{"class":84,"line":355},[82,16503,363],{"class":88},[82,16505,1536],{"class":96},[82,16507,369],{"class":88},[82,16509,1228],{"class":100},[82,16511,161],{"class":96},[82,16513,1545],{"class":100},[82,16515,3521],{"class":96},[82,16517,186],{"class":88},[82,16519,1348],{"class":100},[82,16521,7295],{"class":96},[82,16523,186],{"class":88},[82,16525,189],{"class":100},[82,16527,7295],{"class":96},[82,16529,186],{"class":88},[82,16531,189],{"class":100},[82,16533,2554],{"class":96},[82,16535,16536,16538,16540,16543,16545,16547,16549],{"class":84,"line":360},[82,16537,16198],{"class":96},[82,16539,141],{"class":88},[82,16541,16542],{"class":96}," (numbers[i] ",[82,16544,631],{"class":88},[82,16546,16208],{"class":96},[82,16548,637],{"class":88},[82,16550,16213],{"class":100},[82,16552,16553,16555,16557],{"class":84,"line":375},[82,16554,16441],{"class":96},[82,16556,10745],{"class":88},[82,16558,2260],{"class":100},[82,16560,16561,16564,16566],{"class":84,"line":384},[82,16562,16563],{"class":96},"            output[count[digit]] ",[82,16565,141],{"class":88},[82,16567,13496],{"class":96},[82,16569,16570],{"class":84,"line":390},[82,16571,222],{"emptyLinePlaceholder":221},[82,16573,16574,16576,16578],{"class":84,"line":395},[82,16575,16232],{"class":96},[82,16577,141],{"class":88},[82,16579,16580],{"class":96}," output\n",[82,16582,16583,16585,16587],{"class":84,"line":412},[82,16584,16271],{"class":96},[82,16586,10803],{"class":88},[82,16588,16213],{"class":100},[82,16590,16591],{"class":84,"line":417},[82,16592,222],{"emptyLinePlaceholder":221},[82,16594,16595,16597],{"class":84,"line":431},[82,16596,568],{"class":88},[82,16598,3534],{"class":96},[24,16600,1816],{"id":1815},[15,16602,16603],{},[19,16604,16605],{},"Time Complexity: O(nk)",[43,16607,16608,16613,16619,16622],{},[46,16609,16610,16612],{},[39,16611,8740],{}," is the number of elements",[46,16614,16615,16618],{},[39,16616,16617],{},"k"," is the number of digits in the maximum value (k = log₁₀(max_value) + 1)",[46,16620,16621],{},"Each pass processes all n elements in O(n) time",[46,16623,16624],{},"There are k passes total",[15,16626,16627],{},"For fixed-size integers (e.g., 32-bit), k is a constant, making radix sort effectively O(n). When values can be arbitrarily large (k = O(log n)), radix sort becomes O(n log n), matching comparison sorts.",[15,16629,16630],{},[19,16631,16632],{},"Space Complexity: O(n + k)",[15,16634,16635],{},"The bucket-based version requires O(n) space for the output array plus O(k) for the 10 buckets (where k=10 for decimal digits). Total auxiliary space is O(n + 10) = O(n).",[24,16637,16639],{"id":16638},"when-to-use-radix-sort","When to Use Radix Sort",[43,16641,16642,16648,16654,16660],{},[46,16643,16644,16647],{},[19,16645,16646],{},"Sorting integers with bounded range",": When the maximum number of digits k is small relative to n, radix sort outperforms comparison sorts.",[46,16649,16650,16653],{},[19,16651,16652],{},"Fixed-length strings",": Radix sort generalizes naturally to strings of equal length (sort by each character position).",[46,16655,16656,16659],{},[19,16657,16658],{},"Large datasets of short keys",": Sorting millions of ZIP codes, phone numbers, or social security numbers.",[46,16661,16662,16665],{},[19,16663,16664],{},"Parallel\u002Fdistributed sorting",": Each bucket pass is highly parallelizable.",[24,16667,1938],{"id":1937},[43,16669,16670,16676,16682,16688],{},[46,16671,16672,16675],{},[19,16673,16674],{},"Floating-point numbers",": Requires special encoding to handle sign bits and exponents correctly.",[46,16677,16678,16681],{},[19,16679,16680],{},"Variable-length strings",": MSD radix sort handles this but adds complexity.",[46,16683,16684,16687],{},[19,16685,16686],{},"Small datasets",": The overhead of multiple passes and bucket allocation isn't worth it for small n.",[46,16689,16690,16693],{},[19,16691,16692],{},"Large key space",": If numbers have many digits (k is large), comparison sorts may win.",[24,16695,16697],{"id":16696},"radix-sort-vs-comparison-sorts","Radix Sort vs. Comparison Sorts",[731,16699,16700,16713],{},[734,16701,16702],{},[737,16703,16704,16706,16708,16710],{},[740,16705,8102],{},[740,16707,2048],{},[740,16709,2429],{},[740,16711,16712],{},"Comparison-based?",[750,16714,16715,16727,16739],{},[737,16716,16717,16719,16722,16725],{},[755,16718,15897],{},[755,16720,16721],{},"O(nk)",[755,16723,16724],{},"O(n+k)",[755,16726,3075],{},[737,16728,16729,16732,16735,16737],{},[755,16730,16731],{},"Quicksort",[755,16733,16734],{},"O(n log n) avg",[755,16736,3911],{},[755,16738,782],{},[737,16740,16741,16743,16745,16747],{},[755,16742,14007],{},[755,16744,3926],{},[755,16746,2077],{},[755,16748,782],{},[15,16750,16751],{},"The theoretical lower bound for comparison sorts is Ω(n log n). Radix sort bypasses this by not comparing elements directly — it uses digit extraction instead.",[24,16753,1998],{"id":1997},[731,16755,16756,16764],{},[734,16757,16758],{},[737,16759,16760,16762],{},[740,16761,742],{},[740,16763,2009],{},[750,16765,16766,16773,16780,16786],{},[737,16767,16768,16770],{},[755,16769,13266],{},[755,16771,16772],{},"No (requires O(n) auxiliary space)",[737,16774,16775,16777],{},[755,16776,13273],{},[755,16778,16779],{},"Yes (when using stable distribution)",[737,16781,16782,16784],{},[755,16783,13280],{},[755,16785,3075],{},[737,16787,16788,16791],{},[755,16789,16790],{},"Non-comparative",[755,16792,782],{},[850,16794,852],{},{"title":41,"searchDepth":122,"depth":122,"links":16796},[16797,16798,16799,16800,16801,16802,16803,16804],{"id":892,"depth":122,"text":893},{"id":4622,"depth":122,"text":4623},{"id":69,"depth":122,"text":70},{"id":1815,"depth":122,"text":1816},{"id":16638,"depth":122,"text":16639},{"id":1937,"depth":122,"text":1938},{"id":16696,"depth":122,"text":16697},{"id":1997,"depth":122,"text":1998},"Learn how radix sort achieves linear-time sorting by processing digits from least significant to most significant.",{"timeComplexity":16721,"spaceComplexity":16724},"\u002Flearn\u002Fradix-sort","radix",{"title":15897,"description":16805},"learn\u002Fradix-sort","zaQW6zRmACZEn19nV4sbywaGW32NYoL3GdLWFYCdboM",{"id":16813,"title":16814,"body":16815,"category":6049,"complexity":862,"date":862,"description":17286,"difficulty":2462,"extension":865,"meta":17287,"navigation":221,"order":129,"path":17288,"publishedAt":2079,"relatedAlgorithmId":17289,"seo":17290,"stem":17291,"__hash__":17292},"learn\u002Flearn\u002Fselection-sort.md","Selection Sort",{"type":8,"value":16816,"toc":17276},[16817,16820,16823,16825,16839,16841,16846,16902,16904,17079,17081,17085,17103,17110,17114,17117,17121,17184,17191,17195,17214,17216,17234,17236,17274],[11,16818,16814],{"id":16819},"selection-sort",[15,16821,16822],{},"Selection sort divides the array into two parts: a sorted portion at the beginning and an unsorted portion at the end. It repeatedly selects the smallest element from the unsorted portion and swaps it with the first unsorted element. While simple to understand, it always performs O(n²) comparisons regardless of input order.",[24,16824,893],{"id":892},[895,16826,16827,16830,16833,16836],{},[46,16828,16829],{},"Find the minimum element in the unsorted portion of the array",[46,16831,16832],{},"Swap it with the first element of the unsorted portion",[46,16834,16835],{},"Advance the boundary between sorted and unsorted by one position",[46,16837,16838],{},"Repeat until the entire array is sorted",[24,16840,4623],{"id":4622},[15,16842,13343,16843,4469],{},[39,16844,16845],{},"[64, 25, 12, 22, 11]",[43,16847,16848,16860,16875,16889],{},[46,16849,16850,16852,16853,16856,16857],{},[19,16851,13353],{},": Find minimum (",[39,16854,16855],{},"11",") in full array. Swap with index 0 → ",[39,16858,16859],{},"[11, 25, 12, 22, 64]",[46,16861,16862,16852,16864,16867,16868,16871,16872],{},[19,16863,13373],{},[39,16865,16866],{},"12",") in ",[39,16869,16870],{},"[25, 12, 22, 64]",". Swap with index 1 → ",[39,16873,16874],{},"[11, 12, 25, 22, 64]",[46,16876,16877,16852,16879,16867,16882,16885,16886],{},[19,16878,13394],{},[39,16880,16881],{},"22",[39,16883,16884],{},"[25, 22, 64]",". Swap with index 2 → ",[39,16887,16888],{},"[11, 12, 22, 25, 64]",[46,16890,16891,16852,16893,16867,16896,16899,16900],{},[19,16892,13409],{},[39,16894,16895],{},"25",[39,16897,16898],{},"[25, 64]",". Already at index 3 → ",[39,16901,16888],{},[24,16903,70],{"id":69},[32,16905,16907],{"className":76,"code":16906,"language":78,"meta":41,"style":41},"def selection_sort(numbers: list[int]) -> list[int]:\n    \"\"\"Sort by repeatedly finding the minimum from the unsorted portion.\"\"\"\n    array_length = len(numbers)\n\n    for current_position in range(array_length - 1):\n        min_index = current_position\n\n        # Find the minimum element in the remaining unsorted array\n        for search_index in range(current_position + 1, array_length):\n            if numbers[search_index] \u003C numbers[min_index]:\n                min_index = search_index\n\n        # Swap the found minimum with the first unsorted element\n        if min_index != current_position:\n            numbers[current_position], numbers[min_index] = (\n                numbers[min_index],\n                numbers[current_position],\n            )\n\n    return numbers\n",[39,16908,16909,16926,16931,16941,16945,16963,16973,16977,16982,17003,17015,17025,17029,17034,17046,17055,17060,17065,17069,17073],{"__ignoreMap":41},[82,16910,16911,16913,16916,16918,16920,16922,16924],{"class":84,"line":85},[82,16912,89],{"class":88},[82,16914,16915],{"class":92}," selection_sort",[82,16917,1627],{"class":96},[82,16919,101],{"class":100},[82,16921,3503],{"class":96},[82,16923,101],{"class":100},[82,16925,119],{"class":96},[82,16927,16928],{"class":84,"line":122},[82,16929,16930],{"class":125},"    \"\"\"Sort by repeatedly finding the minimum from the unsorted portion.\"\"\"\n",[82,16932,16933,16935,16937,16939],{"class":84,"line":129},[82,16934,3776],{"class":96},[82,16936,141],{"class":88},[82,16938,1471],{"class":100},[82,16940,3783],{"class":96},[82,16942,16943],{"class":84,"line":135},[82,16944,222],{"emptyLinePlaceholder":221},[82,16946,16947,16949,16951,16953,16955,16957,16959,16961],{"class":84,"line":147},[82,16948,982],{"class":88},[82,16950,5869],{"class":96},[82,16952,369],{"class":88},[82,16954,1228],{"class":100},[82,16956,3811],{"class":96},[82,16958,186],{"class":88},[82,16960,1348],{"class":100},[82,16962,2554],{"class":96},[82,16964,16965,16968,16970],{"class":84,"line":176},[82,16966,16967],{"class":96},"        min_index ",[82,16969,141],{"class":88},[82,16971,16972],{"class":96}," current_position\n",[82,16974,16975],{"class":84,"line":199},[82,16976,222],{"emptyLinePlaceholder":221},[82,16978,16979],{"class":84,"line":218},[82,16980,16981],{"class":258},"        # Find the minimum element in the remaining unsorted array\n",[82,16983,16984,16986,16989,16991,16993,16996,16998,17000],{"class":84,"line":225},[82,16985,363],{"class":88},[82,16987,16988],{"class":96}," search_index ",[82,16990,369],{"class":88},[82,16992,1228],{"class":100},[82,16994,16995],{"class":96},"(current_position ",[82,16997,406],{"class":88},[82,16999,1348],{"class":100},[82,17001,17002],{"class":96},", array_length):\n",[82,17004,17005,17007,17010,17012],{"class":84,"line":236},[82,17006,378],{"class":88},[82,17008,17009],{"class":96}," numbers[search_index] ",[82,17011,425],{"class":88},[82,17013,17014],{"class":96}," numbers[min_index]:\n",[82,17016,17017,17020,17022],{"class":84,"line":247},[82,17018,17019],{"class":96},"                min_index ",[82,17021,141],{"class":88},[82,17023,17024],{"class":96}," search_index\n",[82,17026,17027],{"class":84,"line":262},[82,17028,222],{"emptyLinePlaceholder":221},[82,17030,17031],{"class":84,"line":267},[82,17032,17033],{"class":258},"        # Swap the found minimum with the first unsorted element\n",[82,17035,17036,17038,17041,17043],{"class":84,"line":276},[82,17037,307],{"class":88},[82,17039,17040],{"class":96}," min_index ",[82,17042,515],{"class":88},[82,17044,17045],{"class":96}," current_position:\n",[82,17047,17048,17051,17053],{"class":84,"line":282},[82,17049,17050],{"class":96},"            numbers[current_position], numbers[min_index] ",[82,17052,141],{"class":88},[82,17054,3854],{"class":96},[82,17056,17057],{"class":84,"line":299},[82,17058,17059],{"class":96},"                numbers[min_index],\n",[82,17061,17062],{"class":84,"line":304},[82,17063,17064],{"class":96},"                numbers[current_position],\n",[82,17066,17067],{"class":84,"line":313},[82,17068,12064],{"class":96},[82,17070,17071],{"class":84,"line":319},[82,17072,222],{"emptyLinePlaceholder":221},[82,17074,17075,17077],{"class":84,"line":330},[82,17076,568],{"class":88},[82,17078,3534],{"class":96},[24,17080,1816],{"id":1815},[15,17082,17083],{},[19,17084,13606],{},[43,17086,17087,17093,17098],{},[46,17088,17089,17092],{},[19,17090,17091],{},"Best case — O(n²)",": Even if the array is already sorted, selection sort still scans the entire unsorted portion to confirm the minimum. It always makes (n-1) + (n-2) + ... + 1 = n(n-1)\u002F2 comparisons.",[46,17094,17095,17097],{},[19,17096,13619],{},": Same number of comparisons regardless of input order.",[46,17099,17100,17102],{},[19,17101,13625],{},": No input arrangement changes the comparison count.",[15,17104,17105,17106,17109],{},"The key insight is that selection sort is ",[19,17107,17108],{},"not adaptive"," — it cannot exploit existing order in the data.",[15,17111,17112],{},[19,17113,13192],{},[15,17115,17116],{},"Selection sort is in-place, requiring only a constant amount of extra memory for the index variables and the swap operation.",[24,17118,17120],{"id":17119},"comparison-with-other-on-sorts","Comparison with Other O(n²) Sorts",[731,17122,17123,17135],{},[734,17124,17125],{},[737,17126,17127,17129,17131,17133],{},[740,17128,742],{},[740,17130,16814],{},[740,17132,13311],{},[740,17134,5762],{},[750,17136,17137,17150,17164,17174],{},[737,17138,17139,17142,17145,17148],{},[755,17140,17141],{},"Comparisons",[755,17143,17144],{},"Always n²\u002F2",[755,17146,17147],{},"Best: n, Worst: n²\u002F2",[755,17149,17147],{},[737,17151,17152,17155,17158,17161],{},[755,17153,17154],{},"Swaps",[755,17156,17157],{},"At most n-1",[755,17159,17160],{},"Up to n²\u002F2 shifts",[755,17162,17163],{},"Up to n²\u002F2",[737,17165,17166,17168,17170,17172],{},[755,17167,13273],{},[755,17169,3075],{},[755,17171,782],{},[755,17173,782],{},[737,17175,17176,17178,17180,17182],{},[755,17177,13280],{},[755,17179,3075],{},[755,17181,782],{},[755,17183,782],{},[15,17185,17186,17187,17190],{},"Selection sort's advantage is ",[19,17188,17189],{},"minimal writes"," — it performs at most n-1 swaps. This matters when writing to memory is expensive (e.g., flash memory or EEPROM).",[24,17192,17194],{"id":17193},"when-to-use-selection-sort","When to Use Selection Sort",[43,17196,17197,17203,17209],{},[46,17198,17199,17202],{},[19,17200,17201],{},"Minimizing writes",": When memory writes are costly (flash storage), selection sort's O(n) swaps beat insertion sort's O(n²) shifts.",[46,17204,17205,17208],{},[19,17206,17207],{},"Teaching purposes",": Its clear \"find minimum, place it\" logic makes it easy to visualize and understand.",[46,17210,17211,17213],{},[19,17212,13246],{},": For very small inputs (n \u003C 20), the overhead difference between algorithms is negligible.",[24,17215,1938],{"id":1937},[43,17217,17218,17224,17229],{},[46,17219,17220,17223],{},[19,17221,17222],{},"Large datasets",": O(n²) with no adaptivity makes it impractical for n > 100.",[46,17225,17226,17228],{},[19,17227,6027],{},": Unlike insertion sort, it cannot take advantage of existing order.",[46,17230,17231,17233],{},[19,17232,13240],{},": Selection sort is not stable — equal elements may change their relative order during swaps.",[24,17235,1998],{"id":1997},[731,17237,17238,17246],{},[734,17239,17240],{},[737,17241,17242,17244],{},[740,17243,742],{},[740,17245,2009],{},[750,17247,17248,17254,17260,17266],{},[737,17249,17250,17252],{},[755,17251,13266],{},[755,17253,782],{},[737,17255,17256,17258],{},[755,17257,13273],{},[755,17259,3075],{},[737,17261,17262,17264],{},[755,17263,13280],{},[755,17265,3075],{},[737,17267,17268,17271],{},[755,17269,17270],{},"Minimum swaps",[755,17272,17273],{},"Yes (at most n-1)",[850,17275,852],{},{"title":41,"searchDepth":122,"depth":122,"links":17277},[17278,17279,17280,17281,17282,17283,17284,17285],{"id":892,"depth":122,"text":893},{"id":4622,"depth":122,"text":4623},{"id":69,"depth":122,"text":70},{"id":1815,"depth":122,"text":1816},{"id":17119,"depth":122,"text":17120},{"id":17193,"depth":122,"text":17194},{"id":1937,"depth":122,"text":1938},{"id":1997,"depth":122,"text":1998},"Learn how selection sort finds the minimum element repeatedly and places it in the correct position.",{"timeComplexity":13726,"spaceComplexity":3903},"\u002Flearn\u002Fselection-sort","selection",{"title":16814,"description":17286},"learn\u002Fselection-sort","tmTctVYZ_RaISmudFpIugwOH73EJjqNidthTDl2XdLY",{"id":17294,"title":17295,"body":17296,"category":6049,"complexity":862,"date":862,"description":18026,"difficulty":864,"extension":865,"meta":18027,"navigation":221,"order":218,"path":18029,"publishedAt":2079,"relatedAlgorithmId":18030,"seo":18031,"stem":18032,"__hash__":18033},"learn\u002Flearn\u002Fshell-sort.md","Shell Sort",{"type":8,"value":17297,"toc":18016},[17298,17301,17304,17306,17324,17327,17329,17335,17341,17352,17358,17384,17390,17398,17400,17597,17601,17604,17673,17676,17888,17890,17895,17913,17916,17920,17923,17927,17952,17954,17973,17975,18014],[11,17299,17295],{"id":17300},"shell-sort",[15,17302,17303],{},"Shell sort is a generalization of insertion sort that allows elements far apart to be compared and swapped early, dramatically reducing the total number of shifts needed. It works by sorting elements at various gap intervals, progressively reducing the gap until it reaches 1 (at which point it becomes a standard insertion sort on a nearly-sorted array).",[24,17305,893],{"id":892},[895,17307,17308,17311,17318,17321],{},[46,17309,17310],{},"Choose a gap sequence (e.g., start with n\u002F2, then n\u002F4, then n\u002F8, ... down to 1)",[46,17312,17313,17314,17317],{},"For the current gap, perform a \"gapped insertion sort\" — compare elements that are ",[39,17315,17316],{},"gap"," positions apart and shift them into order",[46,17319,17320],{},"Reduce the gap and repeat",[46,17322,17323],{},"When gap = 1, perform a final insertion sort (which is fast because the array is nearly sorted)",[15,17325,17326],{},"The key insight is that by sorting with large gaps first, elements move closer to their final positions quickly. By the time the gap reaches 1, very few shifts are needed.",[24,17328,4623],{"id":4622},[15,17330,12736,17331,17334],{},[39,17332,17333],{},"[8, 3, 6, 1, 5, 2, 7, 4]"," (n=8):",[15,17336,17337,17340],{},[19,17338,17339],{},"Gap = 4",": Compare elements 4 apart",[43,17342,17343,17346],{},[46,17344,17345],{},"Compare pairs: (8,5), (3,2), (6,7), (1,4)",[46,17347,17348,17349],{},"After sorting each pair: ",[39,17350,17351],{},"[5, 2, 6, 1, 8, 3, 7, 4]",[15,17353,17354,17357],{},[19,17355,17356],{},"Gap = 2",": Compare elements 2 apart",[43,17359,17360,17369,17378],{},[46,17361,17362,17363,12762,17366],{},"Sort subsequence at indices 0,2,4,6: ",[39,17364,17365],{},"[5, 6, 8, 7]",[39,17367,17368],{},"[5, 6, 7, 8]",[46,17370,17371,17372,12762,17375],{},"Sort subsequence at indices 1,3,5,7: ",[39,17373,17374],{},"[2, 1, 3, 4]",[39,17376,17377],{},"[1, 2, 3, 4]",[46,17379,17380,17381],{},"Result: ",[39,17382,17383],{},"[5, 1, 6, 2, 7, 3, 8, 4]",[15,17385,17386,17389],{},[19,17387,17388],{},"Gap = 1",": Standard insertion sort on nearly-sorted array",[43,17391,17392],{},[46,17393,17394,17395],{},"Final result: ",[39,17396,17397],{},"[1, 2, 3, 4, 5, 6, 7, 8]",[24,17399,70],{"id":69},[32,17401,17403],{"className":76,"code":17402,"language":78,"meta":41,"style":41},"def shell_sort(numbers: list[int]) -> list[int]:\n    \"\"\"Sort using diminishing gap insertion sort.\"\"\"\n    array_length = len(numbers)\n    gap = array_length \u002F\u002F 2\n\n    while gap > 0:\n        # Perform gapped insertion sort\n        for i in range(gap, array_length):\n            current_value = numbers[i]\n            position = i\n\n            # Shift elements that are 'gap' apart\n            while position >= gap and numbers[position - gap] > current_value:\n                numbers[position] = numbers[position - gap]\n                position -= gap\n\n            numbers[position] = current_value\n\n        gap \u002F\u002F= 2\n\n    return numbers\n",[39,17404,17405,17422,17427,17437,17450,17454,17467,17472,17485,17493,17502,17506,17511,17536,17550,17560,17564,17573,17577,17587,17591],{"__ignoreMap":41},[82,17406,17407,17409,17412,17414,17416,17418,17420],{"class":84,"line":85},[82,17408,89],{"class":88},[82,17410,17411],{"class":92}," shell_sort",[82,17413,1627],{"class":96},[82,17415,101],{"class":100},[82,17417,3503],{"class":96},[82,17419,101],{"class":100},[82,17421,119],{"class":96},[82,17423,17424],{"class":84,"line":122},[82,17425,17426],{"class":125},"    \"\"\"Sort using diminishing gap insertion sort.\"\"\"\n",[82,17428,17429,17431,17433,17435],{"class":84,"line":129},[82,17430,3776],{"class":96},[82,17432,141],{"class":88},[82,17434,1471],{"class":100},[82,17436,3783],{"class":96},[82,17438,17439,17442,17444,17446,17448],{"class":84,"line":135},[82,17440,17441],{"class":96},"    gap ",[82,17443,141],{"class":88},[82,17445,13047],{"class":96},[82,17447,631],{"class":88},[82,17449,3321],{"class":100},[82,17451,17452],{"class":84,"line":147},[82,17453,222],{"emptyLinePlaceholder":221},[82,17455,17456,17458,17461,17463,17465],{"class":84,"line":176},[82,17457,270],{"class":88},[82,17459,17460],{"class":96}," gap ",[82,17462,3461],{"class":88},[82,17464,1699],{"class":100},[82,17466,523],{"class":96},[82,17468,17469],{"class":84,"line":199},[82,17470,17471],{"class":258},"        # Perform gapped insertion sort\n",[82,17473,17474,17476,17478,17480,17482],{"class":84,"line":218},[82,17475,363],{"class":88},[82,17477,1536],{"class":96},[82,17479,369],{"class":88},[82,17481,1228],{"class":100},[82,17483,17484],{"class":96},"(gap, array_length):\n",[82,17486,17487,17489,17491],{"class":84,"line":225},[82,17488,5888],{"class":96},[82,17490,141],{"class":88},[82,17492,13496],{"class":96},[82,17494,17495,17498,17500],{"class":84,"line":236},[82,17496,17497],{"class":96},"            position ",[82,17499,141],{"class":88},[82,17501,12168],{"class":96},[82,17503,17504],{"class":84,"line":247},[82,17505,222],{"emptyLinePlaceholder":221},[82,17507,17508],{"class":84,"line":262},[82,17509,17510],{"class":258},"            # Shift elements that are 'gap' apart\n",[82,17512,17513,17516,17518,17520,17522,17524,17527,17529,17532,17534],{"class":84,"line":267},[82,17514,17515],{"class":88},"            while",[82,17517,13810],{"class":96},[82,17519,1728],{"class":88},[82,17521,17460],{"class":96},[82,17523,3664],{"class":88},[82,17525,17526],{"class":96}," numbers[position ",[82,17528,186],{"class":88},[82,17530,17531],{"class":96}," gap] ",[82,17533,3461],{"class":88},[82,17535,13540],{"class":96},[82,17537,17538,17541,17543,17545,17547],{"class":84,"line":276},[82,17539,17540],{"class":96},"                numbers[position] ",[82,17542,141],{"class":88},[82,17544,17526],{"class":96},[82,17546,186],{"class":88},[82,17548,17549],{"class":96}," gap]\n",[82,17551,17552,17555,17557],{"class":84,"line":282},[82,17553,17554],{"class":96},"                position ",[82,17556,10745],{"class":88},[82,17558,17559],{"class":96}," gap\n",[82,17561,17562],{"class":84,"line":299},[82,17563,222],{"emptyLinePlaceholder":221},[82,17565,17566,17569,17571],{"class":84,"line":304},[82,17567,17568],{"class":96},"            numbers[position] ",[82,17570,141],{"class":88},[82,17572,5951],{"class":96},[82,17574,17575],{"class":84,"line":313},[82,17576,222],{"emptyLinePlaceholder":221},[82,17578,17579,17582,17585],{"class":84,"line":319},[82,17580,17581],{"class":96},"        gap ",[82,17583,17584],{"class":88},"\u002F\u002F=",[82,17586,3321],{"class":100},[82,17588,17589],{"class":84,"line":330},[82,17590,222],{"emptyLinePlaceholder":221},[82,17592,17593,17595],{"class":84,"line":335},[82,17594,568],{"class":88},[82,17596,3534],{"class":96},[24,17598,17600],{"id":17599},"gap-sequences","Gap Sequences",[15,17602,17603],{},"The choice of gap sequence significantly affects performance:",[731,17605,17606,17618],{},[734,17607,17608],{},[737,17609,17610,17612,17615],{},[740,17611,5569],{},[740,17613,17614],{},"Gaps",[740,17616,17617],{},"Worst Case",[750,17619,17620,17630,17641,17651,17662],{},[737,17621,17622,17625,17628],{},[755,17623,17624],{},"Shell (original)",[755,17626,17627],{},"n\u002F2, n\u002F4, ..., 1",[755,17629,13726],{},[737,17631,17632,17635,17638],{},[755,17633,17634],{},"Hibbard",[755,17636,17637],{},"2^k - 1: 1, 3, 7, 15, ...",[755,17639,17640],{},"O(n^1.5)",[737,17642,17643,17646,17649],{},[755,17644,17645],{},"Knuth",[755,17647,17648],{},"(3^k - 1)\u002F2: 1, 4, 13, 40, ...",[755,17650,17640],{},[737,17652,17653,17656,17659],{},[755,17654,17655],{},"Sedgewick",[755,17657,17658],{},"1, 5, 19, 41, 109, ...",[755,17660,17661],{},"O(n^(4\u002F3))",[737,17663,17664,17667,17670],{},[755,17665,17666],{},"Ciura (empirical)",[755,17668,17669],{},"1, 4, 10, 23, 57, 132, 301, 701",[755,17671,17672],{},"Best known in practice",[15,17674,17675],{},"The implementation above uses Shell's original sequence (n\u002F2). For better performance, use Knuth's sequence:",[32,17677,17679],{"className":76,"code":17678,"language":78,"meta":41,"style":41},"def shell_sort_knuth(numbers: list[int]) -> list[int]:\n    \"\"\"Shell sort with Knuth's gap sequence.\"\"\"\n    array_length = len(numbers)\n\n    # Generate Knuth gaps: 1, 4, 13, 40, 121, ...\n    gap = 1\n    while gap \u003C array_length \u002F\u002F 3:\n        gap = gap * 3 + 1\n\n    while gap >= 1:\n        for i in range(gap, array_length):\n            current_value = numbers[i]\n            position = i\n\n            while position >= gap and numbers[position - gap] > current_value:\n                numbers[position] = numbers[position - gap]\n                position -= gap\n\n            numbers[position] = current_value\n\n        gap \u002F\u002F= 3\n\n    return numbers\n",[39,17680,17681,17698,17703,17713,17717,17722,17730,17747,17763,17767,17779,17791,17799,17807,17811,17833,17845,17853,17857,17865,17869,17878,17882],{"__ignoreMap":41},[82,17682,17683,17685,17688,17690,17692,17694,17696],{"class":84,"line":85},[82,17684,89],{"class":88},[82,17686,17687],{"class":92}," shell_sort_knuth",[82,17689,1627],{"class":96},[82,17691,101],{"class":100},[82,17693,3503],{"class":96},[82,17695,101],{"class":100},[82,17697,119],{"class":96},[82,17699,17700],{"class":84,"line":122},[82,17701,17702],{"class":125},"    \"\"\"Shell sort with Knuth's gap sequence.\"\"\"\n",[82,17704,17705,17707,17709,17711],{"class":84,"line":129},[82,17706,3776],{"class":96},[82,17708,141],{"class":88},[82,17710,1471],{"class":100},[82,17712,3783],{"class":96},[82,17714,17715],{"class":84,"line":135},[82,17716,222],{"emptyLinePlaceholder":221},[82,17718,17719],{"class":84,"line":147},[82,17720,17721],{"class":258},"    # Generate Knuth gaps: 1, 4, 13, 40, 121, ...\n",[82,17723,17724,17726,17728],{"class":84,"line":176},[82,17725,17441],{"class":96},[82,17727,141],{"class":88},[82,17729,2260],{"class":100},[82,17731,17732,17734,17736,17738,17740,17742,17745],{"class":84,"line":199},[82,17733,270],{"class":88},[82,17735,17460],{"class":96},[82,17737,425],{"class":88},[82,17739,13047],{"class":96},[82,17741,631],{"class":88},[82,17743,17744],{"class":100}," 3",[82,17746,523],{"class":96},[82,17748,17749,17751,17753,17755,17757,17759,17761],{"class":84,"line":218},[82,17750,17581],{"class":96},[82,17752,141],{"class":88},[82,17754,17460],{"class":96},[82,17756,170],{"class":88},[82,17758,17744],{"class":100},[82,17760,10397],{"class":88},[82,17762,2260],{"class":100},[82,17764,17765],{"class":84,"line":225},[82,17766,222],{"emptyLinePlaceholder":221},[82,17768,17769,17771,17773,17775,17777],{"class":84,"line":236},[82,17770,270],{"class":88},[82,17772,17460],{"class":96},[82,17774,1728],{"class":88},[82,17776,1348],{"class":100},[82,17778,523],{"class":96},[82,17780,17781,17783,17785,17787,17789],{"class":84,"line":247},[82,17782,363],{"class":88},[82,17784,1536],{"class":96},[82,17786,369],{"class":88},[82,17788,1228],{"class":100},[82,17790,17484],{"class":96},[82,17792,17793,17795,17797],{"class":84,"line":262},[82,17794,5888],{"class":96},[82,17796,141],{"class":88},[82,17798,13496],{"class":96},[82,17800,17801,17803,17805],{"class":84,"line":267},[82,17802,17497],{"class":96},[82,17804,141],{"class":88},[82,17806,12168],{"class":96},[82,17808,17809],{"class":84,"line":276},[82,17810,222],{"emptyLinePlaceholder":221},[82,17812,17813,17815,17817,17819,17821,17823,17825,17827,17829,17831],{"class":84,"line":282},[82,17814,17515],{"class":88},[82,17816,13810],{"class":96},[82,17818,1728],{"class":88},[82,17820,17460],{"class":96},[82,17822,3664],{"class":88},[82,17824,17526],{"class":96},[82,17826,186],{"class":88},[82,17828,17531],{"class":96},[82,17830,3461],{"class":88},[82,17832,13540],{"class":96},[82,17834,17835,17837,17839,17841,17843],{"class":84,"line":299},[82,17836,17540],{"class":96},[82,17838,141],{"class":88},[82,17840,17526],{"class":96},[82,17842,186],{"class":88},[82,17844,17549],{"class":96},[82,17846,17847,17849,17851],{"class":84,"line":304},[82,17848,17554],{"class":96},[82,17850,10745],{"class":88},[82,17852,17559],{"class":96},[82,17854,17855],{"class":84,"line":313},[82,17856,222],{"emptyLinePlaceholder":221},[82,17858,17859,17861,17863],{"class":84,"line":319},[82,17860,17568],{"class":96},[82,17862,141],{"class":88},[82,17864,5951],{"class":96},[82,17866,17867],{"class":84,"line":330},[82,17868,222],{"emptyLinePlaceholder":221},[82,17870,17871,17873,17875],{"class":84,"line":335},[82,17872,17581],{"class":96},[82,17874,17584],{"class":88},[82,17876,17877],{"class":100}," 3\n",[82,17879,17880],{"class":84,"line":349},[82,17881,222],{"emptyLinePlaceholder":221},[82,17883,17884,17886],{"class":84,"line":355},[82,17885,568],{"class":88},[82,17887,3534],{"class":96},[24,17889,1816],{"id":1815},[15,17891,17892],{},[19,17893,17894],{},"Time Complexity: O(n log²n)",[43,17896,17897,17903,17908],{},[46,17898,17899,17902],{},[19,17900,17901],{},"Best case — O(n log n)",": When the array is already sorted, the inner loop doesn't execute shifts, but the gap iterations still run.",[46,17904,17905,17907],{},[19,17906,10895],{},": Depends on the gap sequence. With Shell's original n\u002F2 sequence, the worst case is O(n²). With better sequences (Sedgewick, Ciura), it approaches O(n log²n) or better.",[46,17909,17910,17912],{},[19,17911,10889],{},": Approximately O(n^1.25) to O(n^1.5) depending on the gap sequence.",[15,17914,17915],{},"The exact complexity of Shell sort remains an open research question — no one has proven a tight bound for all gap sequences.",[15,17917,17918],{},[19,17919,13192],{},[15,17921,17922],{},"Shell sort is in-place, requiring only a few variables for the gap, current value, and position.",[24,17924,17926],{"id":17925},"when-to-use-shell-sort","When to Use Shell Sort",[43,17928,17929,17935,17940,17946],{},[46,17930,17931,17934],{},[19,17932,17933],{},"Medium-sized arrays (100–10,000 elements)",": Significantly faster than O(n²) sorts, with simpler implementation than quicksort or merge sort.",[46,17936,17937,17939],{},[19,17938,13224],{},": In-place, no recursion, and good performance make it ideal for constrained environments.",[46,17941,17942,17945],{},[19,17943,17944],{},"When simplicity matters",": Easier to implement correctly than quicksort, with much better performance than insertion sort.",[46,17947,17948,17951],{},[19,17949,17950],{},"When worst-case matters more than average",": With a good gap sequence, Shell sort avoids the O(n²) worst case that afflicts basic insertion sort.",[24,17953,1938],{"id":1937},[43,17955,17956,17962,17967],{},[46,17957,17958,17961],{},[19,17959,17960],{},"Very large datasets",": True O(n log n) algorithms (quicksort, merge sort, heap sort) are faster for large n.",[46,17963,17964,17966],{},[19,17965,13240],{},": Shell sort is not stable — the gap comparisons can reorder equal elements.",[46,17968,17969,17972],{},[19,17970,17971],{},"Predictable performance needed",": The performance depends heavily on the gap sequence, which complicates analysis.",[24,17974,1998],{"id":1997},[731,17976,17977,17985],{},[734,17978,17979],{},[737,17980,17981,17983],{},[740,17982,742],{},[740,17984,2009],{},[750,17986,17987,17993,17999,18006],{},[737,17988,17989,17991],{},[755,17990,13266],{},[755,17992,782],{},[737,17994,17995,17997],{},[755,17996,13273],{},[755,17998,3075],{},[737,18000,18001,18003],{},[755,18002,13280],{},[755,18004,18005],{},"Partially (benefits from existing order)",[737,18007,18008,18011],{},[755,18009,18010],{},"Gap-dependent",[755,18012,18013],{},"Yes — performance varies with sequence choice",[850,18015,852],{},{"title":41,"searchDepth":122,"depth":122,"links":18017},[18018,18019,18020,18021,18022,18023,18024,18025],{"id":892,"depth":122,"text":893},{"id":4622,"depth":122,"text":4623},{"id":69,"depth":122,"text":70},{"id":17599,"depth":122,"text":17600},{"id":1815,"depth":122,"text":1816},{"id":17925,"depth":122,"text":17926},{"id":1937,"depth":122,"text":1938},{"id":1997,"depth":122,"text":1998},"Learn how Shell sort improves on insertion sort by comparing elements at decreasing gap intervals.",{"timeComplexity":18028,"spaceComplexity":3903},"O(n log²n)","\u002Flearn\u002Fshell-sort","shell",{"title":17295,"description":18026},"learn\u002Fshell-sort","7Bn9s8fKd_bCYFuBfkxmYz7KKfeU-jcD_eChAniBK_0",{"id":18035,"title":18036,"body":18037,"category":9638,"complexity":862,"date":862,"description":18487,"difficulty":864,"extension":865,"meta":18488,"navigation":221,"order":122,"path":18489,"publishedAt":870,"relatedAlgorithmId":18490,"seo":18491,"stem":18492,"__hash__":18493},"learn\u002Flearn\u002Fsliding-window.md","Sliding Window Technique",{"type":8,"value":18038,"toc":18479},[18039,18043,18046,18050,18053,18192,18195,18199,18202,18390,18394,18409,18416,18420,18423,18440,18444,18470,18474,18477],[11,18040,18042],{"id":18041},"the-sliding-window-technique","The Sliding Window Technique",[15,18044,18045],{},"The sliding window is an algorithmic pattern for processing contiguous subarrays or substrings in O(n) time. Instead of recalculating results from scratch for every possible window position, you maintain a running computation and update it incrementally as the window moves.",[24,18047,18049],{"id":18048},"fixed-size-window","Fixed-Size Window",[15,18051,18052],{},"When the problem specifies an exact window size, the pattern is straightforward:",[32,18054,18056],{"className":76,"code":18055,"language":78,"meta":41,"style":41},"def max_sum_fixed_window(numbers: list[int], window_size: int) -> int:\n    \"\"\"Find the maximum sum of any contiguous subarray of the given size.\"\"\"\n    # Initialize with the first window\n    window_sum = sum(numbers[:window_size])\n    best_sum = window_sum\n\n    # Slide the window: add the new right element, remove the old left element\n    for right_edge in range(window_size, len(numbers)):\n        left_edge = right_edge - window_size\n        window_sum += numbers[right_edge] - numbers[left_edge]\n        best_sum = max(best_sum, window_sum)\n\n    return best_sum\n",[39,18057,18058,18080,18085,18090,18103,18113,18117,18122,18140,18154,18169,18181,18185],{"__ignoreMap":41},[82,18059,18060,18062,18065,18067,18069,18072,18074,18076,18078],{"class":84,"line":85},[82,18061,89],{"class":88},[82,18063,18064],{"class":92}," max_sum_fixed_window",[82,18066,1627],{"class":96},[82,18068,101],{"class":100},[82,18070,18071],{"class":96},"], window_size: ",[82,18073,101],{"class":100},[82,18075,607],{"class":96},[82,18077,101],{"class":100},[82,18079,523],{"class":96},[82,18081,18082],{"class":84,"line":122},[82,18083,18084],{"class":125},"    \"\"\"Find the maximum sum of any contiguous subarray of the given size.\"\"\"\n",[82,18086,18087],{"class":84,"line":129},[82,18088,18089],{"class":258},"    # Initialize with the first window\n",[82,18091,18092,18095,18097,18100],{"class":84,"line":135},[82,18093,18094],{"class":96},"    window_sum ",[82,18096,141],{"class":88},[82,18098,18099],{"class":100}," sum",[82,18101,18102],{"class":96},"(numbers[:window_size])\n",[82,18104,18105,18108,18110],{"class":84,"line":147},[82,18106,18107],{"class":96},"    best_sum ",[82,18109,141],{"class":88},[82,18111,18112],{"class":96}," window_sum\n",[82,18114,18115],{"class":84,"line":176},[82,18116,222],{"emptyLinePlaceholder":221},[82,18118,18119],{"class":84,"line":199},[82,18120,18121],{"class":258},"    # Slide the window: add the new right element, remove the old left element\n",[82,18123,18124,18126,18129,18131,18133,18136,18138],{"class":84,"line":218},[82,18125,982],{"class":88},[82,18127,18128],{"class":96}," right_edge ",[82,18130,369],{"class":88},[82,18132,1228],{"class":100},[82,18134,18135],{"class":96},"(window_size, ",[82,18137,1545],{"class":100},[82,18139,13486],{"class":96},[82,18141,18142,18145,18147,18149,18151],{"class":84,"line":225},[82,18143,18144],{"class":96},"        left_edge ",[82,18146,141],{"class":88},[82,18148,18128],{"class":96},[82,18150,186],{"class":88},[82,18152,18153],{"class":96}," window_size\n",[82,18155,18156,18159,18161,18164,18166],{"class":84,"line":236},[82,18157,18158],{"class":96},"        window_sum ",[82,18160,2257],{"class":88},[82,18162,18163],{"class":96}," numbers[right_edge] ",[82,18165,186],{"class":88},[82,18167,18168],{"class":96}," numbers[left_edge]\n",[82,18170,18171,18174,18176,18178],{"class":84,"line":247},[82,18172,18173],{"class":96},"        best_sum ",[82,18175,141],{"class":88},[82,18177,16114],{"class":100},[82,18179,18180],{"class":96},"(best_sum, window_sum)\n",[82,18182,18183],{"class":84,"line":262},[82,18184,222],{"emptyLinePlaceholder":221},[82,18186,18187,18189],{"class":84,"line":267},[82,18188,568],{"class":88},[82,18190,18191],{"class":96}," best_sum\n",[15,18193,18194],{},"This runs in O(n) because each element is added once and removed once.",[24,18196,18198],{"id":18197},"variable-size-window-expandcontract","Variable-Size Window (Expand\u002FContract)",[15,18200,18201],{},"When the window size isn't fixed, you use two pointers and dynamically grow or shrink the window:",[32,18203,18205],{"className":76,"code":18204,"language":78,"meta":41,"style":41},"def longest_substring_without_repeats(text: str) -> int:\n    \"\"\"Find the length of the longest substring without repeating characters.\"\"\"\n    left_pointer = 0\n    longest_length = 0\n    characters_in_window = set()\n\n    for right_pointer in range(len(text)):\n        current_character = text[right_pointer]\n\n        # Contract: shrink window until the repeat is removed\n        while current_character in characters_in_window:\n            characters_in_window.remove(text[left_pointer])\n            left_pointer += 1\n\n        # Expand: add the new character\n        characters_in_window.add(current_character)\n\n        # Update best answer\n        current_window_length = right_pointer - left_pointer + 1\n        longest_length = max(longest_length, current_window_length)\n\n    return longest_length\n",[39,18206,18207,18225,18230,18239,18248,18259,18263,18281,18291,18295,18300,18312,18317,18326,18330,18335,18340,18344,18349,18367,18379,18383],{"__ignoreMap":41},[82,18208,18209,18211,18214,18217,18219,18221,18223],{"class":84,"line":85},[82,18210,89],{"class":88},[82,18212,18213],{"class":92}," longest_substring_without_repeats",[82,18215,18216],{"class":96},"(text: ",[82,18218,10347],{"class":100},[82,18220,607],{"class":96},[82,18222,101],{"class":100},[82,18224,523],{"class":96},[82,18226,18227],{"class":84,"line":122},[82,18228,18229],{"class":125},"    \"\"\"Find the length of the longest substring without repeating characters.\"\"\"\n",[82,18231,18232,18235,18237],{"class":84,"line":129},[82,18233,18234],{"class":96},"    left_pointer ",[82,18236,141],{"class":88},[82,18238,233],{"class":100},[82,18240,18241,18244,18246],{"class":84,"line":135},[82,18242,18243],{"class":96},"    longest_length ",[82,18245,141],{"class":88},[82,18247,233],{"class":100},[82,18249,18250,18253,18255,18257],{"class":84,"line":147},[82,18251,18252],{"class":96},"    characters_in_window ",[82,18254,141],{"class":88},[82,18256,1135],{"class":100},[82,18258,1138],{"class":96},[82,18260,18261],{"class":84,"line":176},[82,18262,222],{"emptyLinePlaceholder":221},[82,18264,18265,18267,18270,18272,18274,18276,18278],{"class":84,"line":199},[82,18266,982],{"class":88},[82,18268,18269],{"class":96}," right_pointer ",[82,18271,369],{"class":88},[82,18273,1228],{"class":100},[82,18275,161],{"class":96},[82,18277,1545],{"class":100},[82,18279,18280],{"class":96},"(text)):\n",[82,18282,18283,18286,18288],{"class":84,"line":218},[82,18284,18285],{"class":96},"        current_character ",[82,18287,141],{"class":88},[82,18289,18290],{"class":96}," text[right_pointer]\n",[82,18292,18293],{"class":84,"line":225},[82,18294,222],{"emptyLinePlaceholder":221},[82,18296,18297],{"class":84,"line":236},[82,18298,18299],{"class":258},"        # Contract: shrink window until the repeat is removed\n",[82,18301,18302,18304,18307,18309],{"class":84,"line":247},[82,18303,4945],{"class":88},[82,18305,18306],{"class":96}," current_character ",[82,18308,369],{"class":88},[82,18310,18311],{"class":96}," characters_in_window:\n",[82,18313,18314],{"class":84,"line":262},[82,18315,18316],{"class":96},"            characters_in_window.remove(text[left_pointer])\n",[82,18318,18319,18322,18324],{"class":84,"line":267},[82,18320,18321],{"class":96},"            left_pointer ",[82,18323,2257],{"class":88},[82,18325,2260],{"class":100},[82,18327,18328],{"class":84,"line":276},[82,18329,222],{"emptyLinePlaceholder":221},[82,18331,18332],{"class":84,"line":282},[82,18333,18334],{"class":258},"        # Expand: add the new character\n",[82,18336,18337],{"class":84,"line":299},[82,18338,18339],{"class":96},"        characters_in_window.add(current_character)\n",[82,18341,18342],{"class":84,"line":304},[82,18343,222],{"emptyLinePlaceholder":221},[82,18345,18346],{"class":84,"line":313},[82,18347,18348],{"class":258},"        # Update best answer\n",[82,18350,18351,18354,18356,18358,18360,18363,18365],{"class":84,"line":319},[82,18352,18353],{"class":96},"        current_window_length ",[82,18355,141],{"class":88},[82,18357,18269],{"class":96},[82,18359,186],{"class":88},[82,18361,18362],{"class":96}," left_pointer ",[82,18364,406],{"class":88},[82,18366,2260],{"class":100},[82,18368,18369,18372,18374,18376],{"class":84,"line":330},[82,18370,18371],{"class":96},"        longest_length ",[82,18373,141],{"class":88},[82,18375,16114],{"class":100},[82,18377,18378],{"class":96},"(longest_length, current_window_length)\n",[82,18380,18381],{"class":84,"line":335},[82,18382,222],{"emptyLinePlaceholder":221},[82,18384,18385,18387],{"class":84,"line":349},[82,18386,568],{"class":88},[82,18388,18389],{"class":96}," longest_length\n",[24,18391,18393],{"id":18392},"why-its-on-not-on2","Why It's O(n), Not O(n^2)",[15,18395,18396,18397,18400,18401,18404,18405,18408],{},"The inner ",[39,18398,18399],{},"while"," loop might seem like it makes this quadratic, but count total pointer movements: ",[39,18402,18403],{},"right_pointer"," moves forward n times, and ",[39,18406,18407],{},"left_pointer"," moves forward at most n times total (it never moves backward). Each element is processed at most twice. Total work: O(2n) = O(n).",[15,18410,18411,18412,18415],{},"This is ",[19,18413,18414],{},"amortized analysis"," — the inner loop doesn't run n times per iteration, it runs n times total across all iterations.",[24,18417,18419],{"id":18418},"the-expandcontract-mental-model","The Expand\u002FContract Mental Model",[15,18421,18422],{},"Think of the window as a caterpillar crawling along the array:",[43,18424,18425,18431,18437],{},[46,18426,10910,18427,18430],{},[19,18428,18429],{},"right pointer"," is the head — always moving forward, exploring",[46,18432,10910,18433,18436],{},[19,18434,18435],{},"left pointer"," is the tail — catches up when the window becomes invalid",[46,18438,18439],{},"Both pointers only move right — that's what guarantees O(n)",[24,18441,18443],{"id":18442},"classic-problems","Classic Problems",[43,18445,18446,18452,18458,18464],{},[46,18447,18448,18451],{},[19,18449,18450],{},"Maximum sum subarray of size k"," (fixed window)",[46,18453,18454,18457],{},[19,18455,18456],{},"Longest substring without repeating characters"," (variable window)",[46,18459,18460,18463],{},[19,18461,18462],{},"Minimum window substring"," (variable, hard — expand to satisfy, contract to minimize)",[46,18465,18466,18469],{},[19,18467,18468],{},"Maximum of all subarrays of size k"," (fixed + monotonic deque)",[24,18471,18473],{"id":18472},"when-to-recognize-the-pattern","When to Recognize the Pattern",[15,18475,18476],{},"Ask yourself: \"Am I looking at contiguous subarrays\u002Fsubstrings, and can I express the problem as maintaining some property over a window?\" If yes, sliding window likely applies.",[850,18478,852],{},{"title":41,"searchDepth":122,"depth":122,"links":18480},[18481,18482,18483,18484,18485,18486],{"id":18048,"depth":122,"text":18049},{"id":18197,"depth":122,"text":18198},{"id":18392,"depth":122,"text":18393},{"id":18418,"depth":122,"text":18419},{"id":18442,"depth":122,"text":18443},{"id":18472,"depth":122,"text":18473},"Learn how the sliding window pattern transforms O(n^2) brute-force solutions into elegant O(n) algorithms for subarray and substring problems.",{"timeComplexity":2077,"spaceComplexity":3903},"\u002Flearn\u002Fsliding-window","fixed-window",{"title":18036,"description":18487},"learn\u002Fsliding-window","gNgBLwnJsUk9T1-9e3doSZtISIALPBurvDECZ_EnOIw",{"id":18495,"title":18496,"body":18497,"category":5751,"complexity":862,"date":862,"description":19255,"difficulty":2462,"extension":865,"meta":19256,"navigation":221,"order":85,"path":19257,"publishedAt":2079,"relatedAlgorithmId":2508,"seo":19258,"stem":19259,"__hash__":19260},"learn\u002Flearn\u002Fstacks.md","Stacks",{"type":8,"value":18498,"toc":19243},[18499,18502,18509,18511,18584,18587,18589,18608,18611,18613,18616,18622,18624,18863,18867,18870,19063,19065,19069,19072,19076,19079,19083,19121,19123,19179,19183,19196,19199,19201,19241],[11,18500,18496],{"id":18501},"stacks",[15,18503,18504,18505,18508],{},"A stack is a linear data structure that follows the ",[19,18506,18507],{},"Last-In, First-Out (LIFO)"," principle. Think of a stack of plates — you can only add or remove plates from the top. The last plate placed on top is the first one you take off. This simple constraint makes stacks surprisingly powerful for solving many programming problems.",[24,18510,4496],{"id":4495},[731,18512,18513,18523],{},[734,18514,18515],{},[737,18516,18517,18519,18521],{},[740,18518,4505],{},[740,18520,11177],{},[740,18522,4369],{},[750,18524,18525,18537,18549,18563,18574],{},[737,18526,18527,18532,18535],{},[755,18528,18529],{},[39,18530,18531],{},"push(item)",[755,18533,18534],{},"Add an element to the top",[755,18536,3903],{},[737,18538,18539,18544,18547],{},[755,18540,18541],{},[39,18542,18543],{},"pop()",[755,18545,18546],{},"Remove and return the top element",[755,18548,3903],{},[737,18550,18551,18558,18561],{},[755,18552,18553,11187,18555],{},[39,18554,11186],{},[39,18556,18557],{},"top()",[755,18559,18560],{},"View the top element without removing it",[755,18562,3903],{},[737,18564,18565,18569,18572],{},[755,18566,18567],{},[39,18568,14467],{},[755,18570,18571],{},"Check if the stack is empty",[755,18573,3903],{},[737,18575,18576,18580,18582],{},[755,18577,18578],{},[39,18579,14479],{},[755,18581,14482],{},[755,18583,3903],{},[15,18585,18586],{},"All operations run in constant time because they only interact with the top of the stack.",[24,18588,893],{"id":892},[895,18590,18591,18597,18603],{},[46,18592,18593,18596],{},[19,18594,18595],{},"Push",": Place a new element on top of the stack. Increment the top pointer.",[46,18598,18599,18602],{},[19,18600,18601],{},"Pop",": Remove the element at the top. Decrement the top pointer. Return the removed element.",[46,18604,18605,18607],{},[19,18606,12353],{},": Read the element at the top without modifying the stack.",[15,18609,18610],{},"The stack maintains a single pointer (or index) tracking the current top position. No searching, shifting, or reordering is ever needed.",[24,18612,4623],{"id":4622},[15,18614,18615],{},"Starting with an empty stack:",[32,18617,18620],{"className":18618,"code":18619,"language":37},[35],"push(10) → Stack: [10]         (top = 10)\npush(20) → Stack: [10, 20]    (top = 20)\npush(30) → Stack: [10, 20, 30] (top = 30)\npop()    → Returns 30, Stack: [10, 20] (top = 20)\npeek()   → Returns 20, Stack: [10, 20] (unchanged)\npop()    → Returns 20, Stack: [10] (top = 10)\n",[39,18621,18619],{"__ignoreMap":41},[24,18623,70],{"id":69},[32,18625,18627],{"className":76,"code":18626,"language":78,"meta":41,"style":41},"class Stack:\n    \"\"\"Stack implementation using a Python list.\"\"\"\n\n    def __init__(self):\n        self._items = []\n\n    def push(self, item) -> None:\n        \"\"\"Add an element to the top of the stack.\"\"\"\n        self._items.append(item)\n\n    def pop(self):\n        \"\"\"Remove and return the top element. Raises error if empty.\"\"\"\n        if self.is_empty():\n            raise IndexError(\"Pop from empty stack\")\n        return self._items.pop()\n\n    def peek(self):\n        \"\"\"Return the top element without removing it.\"\"\"\n        if self.is_empty():\n            raise IndexError(\"Peek at empty stack\")\n        return self._items[-1]\n\n    def is_empty(self) -> bool:\n        \"\"\"Check if the stack has no elements.\"\"\"\n        return len(self._items) == 0\n\n    def size(self) -> int:\n        \"\"\"Return the number of elements in the stack.\"\"\"\n        return len(self._items)\n",[39,18628,18629,18638,18643,18647,18655,18665,18669,18682,18687,18693,18697,18706,18711,18719,18732,18741,18745,18753,18758,18766,18779,18793,18797,18809,18814,18830,18834,18846,18851],{"__ignoreMap":41},[82,18630,18631,18633,18636],{"class":84,"line":85},[82,18632,2534],{"class":88},[82,18634,18635],{"class":92}," Stack",[82,18637,523],{"class":96},[82,18639,18640],{"class":84,"line":122},[82,18641,18642],{"class":125},"    \"\"\"Stack implementation using a Python list.\"\"\"\n",[82,18644,18645],{"class":84,"line":129},[82,18646,222],{"emptyLinePlaceholder":221},[82,18648,18649,18651,18653],{"class":84,"line":135},[82,18650,1176],{"class":88},[82,18652,2546],{"class":100},[82,18654,4753],{"class":96},[82,18656,18657,18659,18661,18663],{"class":84,"line":147},[82,18658,2559],{"class":100},[82,18660,14559],{"class":96},[82,18662,141],{"class":88},[82,18664,493],{"class":96},[82,18666,18667],{"class":84,"line":176},[82,18668,222],{"emptyLinePlaceholder":221},[82,18670,18671,18673,18676,18678,18680],{"class":84,"line":199},[82,18672,1176],{"class":88},[82,18674,18675],{"class":92}," push",[82,18677,14588],{"class":96},[82,18679,1188],{"class":100},[82,18681,523],{"class":96},[82,18683,18684],{"class":84,"line":218},[82,18685,18686],{"class":125},"        \"\"\"Add an element to the top of the stack.\"\"\"\n",[82,18688,18689,18691],{"class":84,"line":225},[82,18690,2559],{"class":100},[82,18692,14604],{"class":96},[82,18694,18695],{"class":84,"line":236},[82,18696,222],{"emptyLinePlaceholder":221},[82,18698,18699,18701,18704],{"class":84,"line":247},[82,18700,1176],{"class":88},[82,18702,18703],{"class":92}," pop",[82,18705,4753],{"class":96},[82,18707,18708],{"class":84,"line":262},[82,18709,18710],{"class":125},"        \"\"\"Remove and return the top element. Raises error if empty.\"\"\"\n",[82,18712,18713,18715,18717],{"class":84,"line":267},[82,18714,307],{"class":88},[82,18716,2658],{"class":100},[82,18718,11499],{"class":96},[82,18720,18721,18723,18725,18727,18730],{"class":84,"line":276},[82,18722,11504],{"class":88},[82,18724,11507],{"class":100},[82,18726,161],{"class":96},[82,18728,18729],{"class":125},"\"Pop from empty stack\"",[82,18731,296],{"class":96},[82,18733,18734,18736,18738],{"class":84,"line":282},[82,18735,2655],{"class":88},[82,18737,2658],{"class":100},[82,18739,18740],{"class":96},"._items.pop()\n",[82,18742,18743],{"class":84,"line":299},[82,18744,222],{"emptyLinePlaceholder":221},[82,18746,18747,18749,18751],{"class":84,"line":304},[82,18748,1176],{"class":88},[82,18750,11479],{"class":92},[82,18752,4753],{"class":96},[82,18754,18755],{"class":84,"line":313},[82,18756,18757],{"class":125},"        \"\"\"Return the top element without removing it.\"\"\"\n",[82,18759,18760,18762,18764],{"class":84,"line":319},[82,18761,307],{"class":88},[82,18763,2658],{"class":100},[82,18765,11499],{"class":96},[82,18767,18768,18770,18772,18774,18777],{"class":84,"line":330},[82,18769,11504],{"class":88},[82,18771,11507],{"class":100},[82,18773,161],{"class":96},[82,18775,18776],{"class":125},"\"Peek at empty stack\"",[82,18778,296],{"class":96},[82,18780,18781,18783,18785,18787,18789,18791],{"class":84,"line":335},[82,18782,2655],{"class":88},[82,18784,2658],{"class":100},[82,18786,14655],{"class":96},[82,18788,186],{"class":88},[82,18790,189],{"class":100},[82,18792,3224],{"class":96},[82,18794,18795],{"class":84,"line":349},[82,18796,222],{"emptyLinePlaceholder":221},[82,18798,18799,18801,18803,18805,18807],{"class":84,"line":355},[82,18800,1176],{"class":88},[82,18802,11445],{"class":92},[82,18804,10773],{"class":96},[82,18806,4921],{"class":100},[82,18808,523],{"class":96},[82,18810,18811],{"class":84,"line":360},[82,18812,18813],{"class":125},"        \"\"\"Check if the stack has no elements.\"\"\"\n",[82,18815,18816,18818,18820,18822,18824,18826,18828],{"class":84,"line":375},[82,18817,2655],{"class":88},[82,18819,1471],{"class":100},[82,18821,161],{"class":96},[82,18823,4806],{"class":100},[82,18825,14698],{"class":96},[82,18827,343],{"class":88},[82,18829,233],{"class":100},[82,18831,18832],{"class":84,"line":384},[82,18833,222],{"emptyLinePlaceholder":221},[82,18835,18836,18838,18840,18842,18844],{"class":84,"line":390},[82,18837,1176],{"class":88},[82,18839,11415],{"class":92},[82,18841,10773],{"class":96},[82,18843,101],{"class":100},[82,18845,523],{"class":96},[82,18847,18848],{"class":84,"line":395},[82,18849,18850],{"class":125},"        \"\"\"Return the number of elements in the stack.\"\"\"\n",[82,18852,18853,18855,18857,18859,18861],{"class":84,"line":412},[82,18854,2655],{"class":88},[82,18856,1471],{"class":100},[82,18858,161],{"class":96},[82,18860,4806],{"class":100},[82,18862,14832],{"class":96},[24,18864,18866],{"id":18865},"classic-problem-balanced-parentheses","Classic Problem: Balanced Parentheses",[15,18868,18869],{},"One of the most common stack applications is checking whether brackets are balanced:",[32,18871,18873],{"className":76,"code":18872,"language":78,"meta":41,"style":41},"def is_balanced(expression: str) -> bool:\n    \"\"\"Check if parentheses, brackets, and braces are balanced.\"\"\"\n    stack = []\n    opening = \"({[\"\n    closing = \")}]\"\n    pairs = {\")\": \"(\", \"}\": \"{\", \"]\": \"[\"}\n\n    for char in expression:\n        if char in opening:\n            stack.append(char)\n        elif char in closing:\n            if not stack or stack[-1] != pairs[char]:\n                return False\n            stack.pop()\n\n    return len(stack) == 0\n",[39,18874,18875,18893,18898,18906,18916,18926,18967,18971,18982,18993,18998,19009,19035,19041,19046,19050],{"__ignoreMap":41},[82,18876,18877,18879,18882,18885,18887,18889,18891],{"class":84,"line":85},[82,18878,89],{"class":88},[82,18880,18881],{"class":92}," is_balanced",[82,18883,18884],{"class":96},"(expression: ",[82,18886,10347],{"class":100},[82,18888,607],{"class":96},[82,18890,4921],{"class":100},[82,18892,523],{"class":96},[82,18894,18895],{"class":84,"line":122},[82,18896,18897],{"class":125},"    \"\"\"Check if parentheses, brackets, and braces are balanced.\"\"\"\n",[82,18899,18900,18902,18904],{"class":84,"line":129},[82,18901,2879],{"class":96},[82,18903,141],{"class":88},[82,18905,493],{"class":96},[82,18907,18908,18911,18913],{"class":84,"line":135},[82,18909,18910],{"class":96},"    opening ",[82,18912,141],{"class":88},[82,18914,18915],{"class":125}," \"({[\"\n",[82,18917,18918,18921,18923],{"class":84,"line":147},[82,18919,18920],{"class":96},"    closing ",[82,18922,141],{"class":88},[82,18924,18925],{"class":125}," \")}]\"\n",[82,18927,18928,18931,18933,18936,18939,18941,18944,18946,18949,18951,18954,18956,18959,18961,18964],{"class":84,"line":176},[82,18929,18930],{"class":96},"    pairs ",[82,18932,141],{"class":88},[82,18934,18935],{"class":96}," {",[82,18937,18938],{"class":125},"\")\"",[82,18940,11094],{"class":96},[82,18942,18943],{"class":125},"\"(\"",[82,18945,7295],{"class":96},[82,18947,18948],{"class":125},"\"}\"",[82,18950,11094],{"class":96},[82,18952,18953],{"class":125},"\"{\"",[82,18955,7295],{"class":96},[82,18957,18958],{"class":125},"\"]\"",[82,18960,11094],{"class":96},[82,18962,18963],{"class":125},"\"[\"",[82,18965,18966],{"class":96},"}\n",[82,18968,18969],{"class":84,"line":199},[82,18970,222],{"emptyLinePlaceholder":221},[82,18972,18973,18975,18977,18979],{"class":84,"line":218},[82,18974,982],{"class":88},[82,18976,10374],{"class":96},[82,18978,369],{"class":88},[82,18980,18981],{"class":96}," expression:\n",[82,18983,18984,18986,18988,18990],{"class":84,"line":225},[82,18985,307],{"class":88},[82,18987,10374],{"class":96},[82,18989,369],{"class":88},[82,18991,18992],{"class":96}," opening:\n",[82,18994,18995],{"class":84,"line":236},[82,18996,18997],{"class":96},"            stack.append(char)\n",[82,18999,19000,19002,19004,19006],{"class":84,"line":247},[82,19001,3346],{"class":88},[82,19003,10374],{"class":96},[82,19005,369],{"class":88},[82,19007,19008],{"class":96}," closing:\n",[82,19010,19011,19013,19015,19018,19021,19024,19026,19028,19030,19032],{"class":84,"line":262},[82,19012,378],{"class":88},[82,19014,2300],{"class":88},[82,19016,19017],{"class":96}," stack ",[82,19019,19020],{"class":88},"or",[82,19022,19023],{"class":96}," stack[",[82,19025,186],{"class":88},[82,19027,189],{"class":100},[82,19029,192],{"class":96},[82,19031,515],{"class":88},[82,19033,19034],{"class":96}," pairs[char]:\n",[82,19036,19037,19039],{"class":84,"line":267},[82,19038,4972],{"class":88},[82,19040,1592],{"class":100},[82,19042,19043],{"class":84,"line":276},[82,19044,19045],{"class":96},"            stack.pop()\n",[82,19047,19048],{"class":84,"line":282},[82,19049,222],{"emptyLinePlaceholder":221},[82,19051,19052,19054,19056,19059,19061],{"class":84,"line":299},[82,19053,568],{"class":88},[82,19055,1471],{"class":100},[82,19057,19058],{"class":96},"(stack) ",[82,19060,343],{"class":88},[82,19062,233],{"class":100},[24,19064,1816],{"id":1815},[15,19066,19067],{},[19,19068,15238],{},[15,19070,19071],{},"Every stack operation (push, pop, peek) takes constant time. There's no traversal — you always work with the top element directly.",[15,19073,19074],{},[19,19075,1846],{},[15,19077,19078],{},"The stack uses space proportional to the number of elements stored. If you push n items, you need O(n) space.",[24,19080,19082],{"id":19081},"when-to-use-stacks","When to Use Stacks",[43,19084,19085,19091,19097,19103,19109,19115],{},[46,19086,19087,19090],{},[19,19088,19089],{},"Function call management",": Every programming language uses a call stack to track function invocations, local variables, and return addresses.",[46,19092,19093,19096],{},[19,19094,19095],{},"Undo\u002FRedo operations",": Text editors push each action onto a stack. Undo pops the last action; redo uses a second stack.",[46,19098,19099,19102],{},[19,19100,19101],{},"Expression evaluation",": Compilers and calculators use stacks to evaluate arithmetic expressions and convert between infix, prefix, and postfix notation.",[46,19104,19105,19108],{},[19,19106,19107],{},"Backtracking algorithms",": DFS, maze solving, and puzzle solvers use stacks (explicitly or via recursion) to track the path and backtrack when stuck.",[46,19110,19111,19114],{},[19,19112,19113],{},"Browser history",": The back button uses a stack of previously visited pages.",[46,19116,19117,19120],{},[19,19118,19119],{},"Syntax parsing",": Compilers use stacks to match brackets, validate HTML tags, and parse nested structures.",[24,19122,15350],{"id":15349},[731,19124,19125,19135],{},[734,19126,19127],{},[737,19128,19129,19131,19133],{},[740,19130,742],{},[740,19132,15361],{},[740,19134,15364],{},[750,19136,19137,19147,19158,19169],{},[737,19138,19139,19141,19144],{},[755,19140,5566],{},[755,19142,19143],{},"Last in, first out",[755,19145,19146],{},"First in, first out",[737,19148,19149,19152,19155],{},[755,19150,19151],{},"Add",[755,19153,19154],{},"Push to top",[755,19156,19157],{},"Enqueue to back",[737,19159,19160,19163,19166],{},[755,19161,19162],{},"Remove",[755,19164,19165],{},"Pop from top",[755,19167,19168],{},"Dequeue from front",[737,19170,19171,19173,19176],{},[755,19172,5572],{},[755,19174,19175],{},"Undo, DFS, parsing",[755,19177,19178],{},"BFS, scheduling, buffering",[24,19180,19182],{"id":19181},"array-vs-linked-list-implementation","Array vs. Linked List Implementation",[43,19184,19185,19190],{},[46,19186,19187,19189],{},[19,19188,12596],{}," (shown above): Simple, cache-friendly, amortized O(1) push. May need resizing.",[46,19191,19192,19195],{},[19,19193,19194],{},"Linked list-based",": O(1) push\u002Fpop without resizing, but uses extra memory for node pointers and has worse cache performance.",[15,19197,19198],{},"For most applications, the array-based implementation is preferred.",[24,19200,1998],{"id":1997},[731,19202,19203,19211],{},[734,19204,19205],{},[737,19206,19207,19209],{},[740,19208,742],{},[740,19210,2009],{},[750,19212,19213,19220,19227,19233],{},[737,19214,19215,19217],{},[755,19216,15428],{},[755,19218,19219],{},"LIFO (Last-In, First-Out)",[737,19221,19222,19225],{},[755,19223,19224],{},"Push\u002FPop",[755,19226,3903],{},[737,19228,19229,19231],{},[755,19230,15443],{},[755,19232,15446],{},[737,19234,19235,19238],{},[755,19236,19237],{},"Thread-safe",[755,19239,19240],{},"No (requires synchronization)",[850,19242,10088],{},{"title":41,"searchDepth":122,"depth":122,"links":19244},[19245,19246,19247,19248,19249,19250,19251,19252,19253,19254],{"id":4495,"depth":122,"text":4496},{"id":892,"depth":122,"text":893},{"id":4622,"depth":122,"text":4623},{"id":69,"depth":122,"text":70},{"id":18865,"depth":122,"text":18866},{"id":1815,"depth":122,"text":1816},{"id":19081,"depth":122,"text":19082},{"id":15349,"depth":122,"text":15350},{"id":19181,"depth":122,"text":19182},{"id":1997,"depth":122,"text":1998},"Learn how the stack data structure works with Last-In-First-Out (LIFO) ordering, its operations, and real-world applications.",{"timeComplexity":3903,"spaceComplexity":2077},"\u002Flearn\u002Fstacks",{"title":18496,"description":19255},"learn\u002Fstacks","67tvMESYewW5ZZ4c16_0ZBGybQZYFZdk26ALFh_gDH8",1795004069076]