{"record":{"id":"5556492b7a8b4049","repo":"donnemartin/interactive-coding-challenges","slug":"index-cannot-be-negative","errorCode":null,"errorMessage":"Index cannot be negative","messagePattern":"Index cannot be negative","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"bit_manipulation/insert_m_into_n/insert_m_into_n_solution.ipynb","lineNumber":120,"sourceCode":"   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"## Code\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 1,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"class Bits(object):\\n\",\n    \"\\n\",\n    \"    def insert_m_into_n(self, m, n, i, j):\\n\",\n    \"        if None in (m, n, i, j):\\n\",\n    \"            raise TypeError('Argument cannot be None')\\n\",\n    \"        if i < 0 or j < 0:\\n\",\n    \"            raise ValueError('Index cannot be negative')\\n\",\n    \"        left_mask = -1 << (j + 1)\\n\",\n    \"        right_mask = (1 << i) - 1\\n\",\n    \"        n_mask = left_mask | right_mask\\n\",\n    \"        # Clear bits from j to i, inclusive\\n\",\n    \"        n_cleared = n & n_mask\\n\",\n    \"        # Shift m into place before inserting it into n\\n\",\n    \"        m_mask = m << i\\n\",\n    \"        return n_cleared | m_mask\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"## Unit Test\"\n   ]\n  },\n  {","sourceCodeStart":102,"sourceCodeEnd":138,"githubUrl":"https://github.com/donnemartin/interactive-coding-challenges/blob/358f2cc60426d5c4c3d7d580910eec9a7b393fa9/bit_manipulation/insert_m_into_n/insert_m_into_n_solution.ipynb#L102-L138","documentation":"Bits.insert_m_into_n raises ValueError('Index cannot be negative') when i or j is negative. These define the inclusive bit window [i, j] in n that m is inserted into; negative positions have no meaning for the mask arithmetic (left_mask = -1 << (j+1), right_mask = (1 << i) - 1).","triggerScenarios":"insert_m_into_n(2, 15, -1, 3) or insert_m_into_n(2, 15, 2, -3); also i, j computed from a subtraction like j = end - start that went negative.","commonSituations":"Window bounds derived from lengths or offsets that underflow; sign errors when parsing index specs from user input or JSON.","solutions":["Clamp: i = max(i, 0) and j = max(j, i) when a degenerate window is acceptable","Validate 0 <= i <= j before calling and reject bad specs with your own error","Fix the arithmetic producing the negative bound"],"exampleFix":"# before\nbits.insert_m_into_n(m, n, start - 2, end)\n\n# after\ni = max(start - 2, 0)\nbits.insert_m_into_n(m, n, i, end)","handlingStrategy":"validation","validationCode":"if i < 0 or j < 0:\n    raise ValueError(f'i and j must be non-negative, got i={i}, j={j}')\nbits.insert_m_into_n(m, n, i, j)","typeGuard":"def valid_window(i, j) -> bool:\n    return isinstance(i, int) and isinstance(j, int) and 0 <= i <= j","tryCatchPattern":"try:\n    result = bits.insert_m_into_n(m, n, i, j)\nexcept ValueError as e:\n    if 'negative' in str(e):\n        i, j = abs(i), abs(j)\n        result = bits.insert_m_into_n(m, n, i, j)\n    else:\n        raise","preventionTips":["Validate 0 <= i <= j when parsing window specs","Use max(0, ...) on computed bounds","Reject malformed user-supplied indexes early with clear messages"],"tags":["python","value-error","negative-index","bit-manipulation"],"backgroundTag":"negative-index-validation","analyzedSha":"358f2cc60426d5c4c3d7d580910eec9a7b393fa9","analyzedAt":"2026-08-28T10:16:54.480Z","schemaVersion":2},"datasetVersion":"2026-08-28T11:17:15.048Z"}