{"record":{"id":"75c91b977191fcdd","repo":"TheAlgorithms/C-Sharp","slug":"key-key-already-exists-in-avl-tree","errorCode":null,"errorMessage":"Key \"{key}\" already exists in AVL tree.","messagePattern":"Key \"(.+?)\" already exists in AVL tree\\.","errorType":"exception","errorClass":"ArgumentException","httpStatus":null,"severity":"error","filePath":"DataStructures/AVLTree/AVLTree.cs","lineNumber":360,"sourceCode":"            {\n                node.Left = Add(node.Left, key);\n            }\n        }\n        else if (compareResult > 0)\n        {\n            if (node.Right is null)\n            {\n                var newNode = new AvlTreeNode<TKey>(key);\n                node.Right = newNode;\n            }\n            else\n            {\n                node.Right = Add(node.Right, key);\n            }\n        }\n        else\n        {\n            throw new ArgumentException($\"\"\"Key \"{key}\" already exists in AVL tree.\"\"\");\n        }\n\n        // Check all of the new node's ancestors for imbalance and perform\n        // necessary rotations\n        node.UpdateBalanceFactor();\n\n        return Rebalance(node);\n    }\n\n    /// <summary>\n    ///     Recursive function to remove node from tree.\n    /// </summary>\n    /// <param name=\"node\">Node to check for key.</param>\n    /// <param name=\"key\">Key value to remove.</param>\n    /// <returns>New node with key removed.</returns>\n    private AvlTreeNode<TKey>? Remove(AvlTreeNode<TKey>? node, TKey key)\n    {\n        if (node == null)","sourceCodeStart":342,"sourceCodeEnd":378,"githubUrl":"https://github.com/TheAlgorithms/C-Sharp/blob/96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c/DataStructures/AVLTree/AVLTree.cs#L342-L378","documentation":"AVLTree.Add throws ArgumentException when the key being inserted compares equal to an existing key under the tree's comparer. AVL trees enforce unique keys to keep the balance invariant well-defined, so a duplicate insert is rejected with a message naming the key. Unlike AATree.Add, this exception carries no nameof parameter argument.","triggerScenarios":"Calling Add(key) with a key already present per the comparer; recursive self-call Add(node, key) hitting the equal-key branch; inserting duplicate entries from a batch.","commonSituations":"Loading records with repeated IDs; case-insensitive comparers collapsing keys thought distinct; replaying an operation log that re-inserts existing keys.","solutions":["Check Contains(key) before Add","Catch ArgumentException and skip or log the duplicate","Deduplicate input by the same comparer before inserting","Switch to a multimap-style structure if duplicate keys must be stored"],"exampleFix":"// before\navl.Add(key);\n// after\ntry { avl.Add(key); } catch (ArgumentException) { /* key already present - skip */ }","handlingStrategy":"validation","validationCode":"if (avlTree.Contains(key)) { /* skip or update */ } else { avlTree.Add(key); }","typeGuard":"bool canInsert(AVLTree<TKey,TValue> t, TKey key) => !t.Contains(key);","tryCatchPattern":"try { avlTree.Add(key); } catch (ArgumentException ex) when (ex.Message.Contains(\"already exists\")) { /* duplicate - handle */ }","preventionTips":["Check Contains before Add","Deduplicate input using the same comparer the tree uses","Be aware of comparer-driven key equality (e.g. case-insensitivity)","Use an upsert/update method instead of Add for idempotent writes"],"tags":["data-structures","avl-tree","duplicate-key"],"backgroundTag":"file-already-exists","analyzedSha":"96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c","analyzedAt":"2026-09-13T17:04:01.438Z","contentChangedAt":"2026-09-13T17:04:01.438Z","schemaVersion":2},"datasetVersion":"2026-09-16T04:17:20.429Z"}