{
  "slug": "array-insert",
  "title": "Insert into an Array",
  "category": "Arrays",
  "difficulty": "easy",
  "complexity": {
    "time": "O(n)",
    "space": "O(1)"
  },
  "idea": "To insert at position p, every element from p onward slides one place right to open a slot — that shifting is why array insertion is O(n).",
  "code": [
    "insert(a, p, x):",
    "    shift a[p..] right by one",
    "    a[p] = x",
    "    length += 1"
  ],
  "example": {
    "array": [
      4,
      8,
      15,
      16,
      23
    ],
    "target": 10,
    "at": 2
  },
  "invariant": "Each step is the real data structure at that step — the picture is a pure function of it.",
  "stepCount": 4,
  "steps": [
    {
      "i": 0,
      "op": "say",
      "caption": "Insert 10 at index 2.",
      "note": null,
      "codeLine": 1,
      "stats": null,
      "array": [
        4,
        8,
        15,
        16,
        23
      ],
      "focus": [
        null,
        null,
        null,
        null,
        null
      ],
      "markers": [],
      "regions": []
    },
    {
      "i": 1,
      "op": "read",
      "caption": "Everything from index 2 onward slides one place right to open a slot.",
      "note": null,
      "codeLine": 2,
      "stats": null,
      "array": [
        4,
        8,
        15,
        16,
        23
      ],
      "focus": [
        null,
        null,
        "read",
        "read",
        "read"
      ],
      "markers": [],
      "regions": []
    },
    {
      "i": 2,
      "op": "insert",
      "caption": "10 drops into the open slot at index 2.",
      "note": null,
      "codeLine": 3,
      "stats": null,
      "array": [
        4,
        8,
        10,
        15,
        16,
        23
      ],
      "focus": [
        null,
        null,
        "insert",
        null,
        null,
        null
      ],
      "markers": [
        {
          "name": "p",
          "index": 2,
          "tone": "bound"
        }
      ],
      "regions": []
    },
    {
      "i": 3,
      "op": "settle",
      "caption": "Inserted. The array grew by one — length is now 6.",
      "note": null,
      "codeLine": 4,
      "stats": null,
      "array": [
        4,
        8,
        10,
        15,
        16,
        23
      ],
      "focus": [
        null,
        null,
        "settled",
        null,
        null,
        null
      ],
      "markers": [],
      "regions": []
    }
  ]
}