Memory-Efficient Solution Approaches in LeetCodeAnimation: O(1) Space Techniques Explained

The LeetCodeAnimation repository demonstrates memory-efficient solution approaches using constant O(1) auxiliary space through techniques like two-pointer scanning, in-place swapping, Floyd’s cycle detection, fixed-size counting buckets, bitwise operations, and in-place reversal.

The LeetCodeAnimation repository (available at MisterBooo/LeetCodeAnimation) contains a comprehensive collection of algorithmic solutions that deliberately minimize memory overhead. Across the C++, Python, and JavaScript implementations, the author consistently targets 空间复杂度 = O(1) (space complexity O(1)) by mutating input data structures in-place rather than allocating auxiliary containers. This article analyzes the specific memory-efficient solution approaches demonstrated in the source files, referencing actual function implementations and file paths from the repository.

Core O(1) Space Strategies Demonstrated

Two-Pointer Scanning and In-Place Partitioning

The most prevalent memory-efficient technique in the repository is two-pointer (fast-slow) scanning for array manipulation. This approach maintains a write pointer (k) and a read pointer (i), ensuring that only a constant number of integer variables are used regardless of input size.

In notes/LeetCode第283号问题:移动零.md (Move Zeroes), the solution implements a write-front pattern:

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int k = 0;                     // nums中, [0...k) 为非 0 元素
        for (int i = 0; i < nums.size(); ++i)
            if (nums[i])               // 非零 → 写到前端
                nums[k++] = nums[i];
        for (int i = k; i < nums.size(); ++i)
            nums[i] = 0;               // 剩余位置填 0
    }
};

Similarly, notes/LeetCode第75号问题:颜色分类.md (Sort Colors) demonstrates three-way partitioning (Dutch National Flag algorithm) using two boundary pointers (zero and two) and a current index. Elements are swapped in-place to their correct partitions without extra arrays:

class Solution {
public:
    void sortColors(vector<int> &nums) {
        int zero = -1;          // [0...zero] == 0
        int two  = nums.size(); // [two...n-1] == 2
        for (int i = 0; i < two; ) {
            if (nums[i] == 1) { i++; }
            else if (nums[i] == 2) {
                two--;
                swap(nums[i], nums[two]);
            } else { // nums[i] == 0
                zero++;
                swap(nums[zero], nums[i]);
                i++;
            }
        }
    }
};

Floyd’s Tortoise-and-Hare Cycle Detection

For linked list problems, the repository consistently applies Floyd’s Cycle Detection Algorithm (Tortoise and Hare) to achieve O(1) space complexity. This technique uses two pointers moving at different speeds (1× and 2×) to detect cycles without hash sets.

In notes/LeetCode第142号问题:Linked-List-Cycle-ii.md, the implementation finds the entry node of a cycle:

class Solution {
public:
    ListNode* detectCycle(ListNode* head) {
        ListNode *slow = head, *fast = head;
        while (fast && fast->next) {
            slow = slow->next;
            fast = fast->next->next;
            if (slow == fast) break;               // 相遇
        }
        if (!fast || !fast->next) return nullptr;   // 无环
        slow = head;
        while (slow != fast) {                      // 同速移动找到入口
            slow = slow->next;
            fast = fast->next;
        }
        return slow;
    }
};

Fixed-Size Counting Buckets

When problems involve bounded value ranges (e.g., lowercase English letters), the repository uses fixed-size counting arrays rather than hash maps. Since the array size is constant (e.g., 26 for alphabet), the space complexity remains O(1).

In notes/LeetCode第242号问题:Valid-Anagram.md, the anagram check uses a static frequency array:

// 使用长度为26的数组统计字符出现次数
// 空间复杂度: O(1) (固定大小数组)

Similarly, notes/LeetCode第268号问题:缺失数字.md (Missing Number) avoids extra arrays by using arithmetic progression or XOR operations, keeping auxiliary space to a single integer variable.

Bitwise XOR for Cancellation

For problems involving paired elements with one unique value, the repository demonstrates bitwise XOR operations to achieve O(1) space. XORing all elements cancels out pairs, leaving only the unique number.

In notes/LeetCode第136号问题:只出现一次的数字.md (Single Number):

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        int ans = 0;
        for (int v : nums) ans ^= v;   // 成对消除
        return ans;
    }
};

In-Place Reversal Technique

Array rotation problems in the repository use the in-place reversal algorithm (reverse the whole array, then reverse sub-segments) to avoid creating copies of the data.

In notes/LeetCode第189号问题:Rotate-Array.md:

class Solution {
public:
    void rotate(vector<int>& nums, int k) {
        int n = nums.size();
        k %= n;
        reverse(nums.begin(), nums.end());          // 整体翻转
        reverse(nums.begin(), nums.begin() + k);    // 前 k 位翻转
        reverse(nums.begin() + k, nums.end());      // 后 n‑k 位翻转
    }
};

Bounded Heaps for Top-K Problems

For problems requiring only the top-k elements, the repository uses heaps (priority queues) with bounded size. By limiting the heap to k elements, the space complexity becomes O(k), which is effectively O(1) when k is a fixed problem constraint.

This approach is demonstrated in notes/LeetCode第347号问题:前K个高频元素.md (Top-K Frequent Elements).

Summary

  • Two-pointer scanning is the dominant O(1) space technique in the repository, used for partitioning arrays and moving elements in-place without auxiliary storage.
  • Floyd’s Tortoise and Hare algorithm provides constant-space cycle detection in linked lists, eliminating the need for hash-based visited tracking.
  • Fixed-size counting buckets (e.g., 26-character arrays) replace hash maps for bounded alphabets, maintaining O(1) auxiliary space.
  • Bitwise XOR operations cancel paired elements to isolate unique values using only a single integer variable.
  • In-place reversal rearranges array segments by reversing the whole structure then sub-segments, achieving rotation without extra buffers.
  • Bounded heaps restrict priority queue size to k elements, ensuring O(k) space complexity that remains constant for fixed k constraints.

Frequently Asked Questions

What does O(1) space complexity mean in the context of LeetCodeAnimation solutions?

O(1) space complexity means the algorithm uses a constant amount of extra memory regardless of input size. In the LeetCodeAnimation repository, this is achieved by mutating the input array or linked list directly (in-place modification) and using only a fixed number of primitive variables (pointers, integers, or small constant-size arrays like 26-character counters) rather than allocating data structures that grow with input size.

How does the two-pointer technique reduce space usage compared to using extra arrays?

The two-pointer technique eliminates the need for auxiliary storage by using indices to partition the existing array in-place. Instead of creating a new array to store filtered or sorted results (which would require O(n) space), the algorithm maintains a write pointer (e.g., k) and a read pointer (e.g., i). Valid elements are written directly to the front of the same array, overwriting previous values, while the trailing portion is filled with default values or ignored. This approach uses only O(1) extra space for the pointer variables.

When is Floyd's Tortoise and Hare algorithm preferred over hash sets for cycle detection?

Floyd’s Tortoise and Hare algorithm is preferred when memory efficiency is critical or when the linked list structure cannot be modified. Hash sets require O(n) space to store visited nodes, whereas Floyd’s algorithm uses only two pointers (O(1) space). The repository demonstrates this in notes/LeetCode第142号问题:Linked-List-Cycle-ii.md, where the algorithm detects the cycle and finds the entry node without auxiliary storage. This approach is essential in embedded systems or when processing massive linked lists where hash set overhead would be prohibitive.

Can the in-place reversal technique be applied to linked lists as well as arrays?

Yes, the in-place reversal technique is applicable to both arrays and linked lists, though the implementation differs. For arrays, the repository uses index-based swapping with std::reverse or manual swaps of segments (as seen in notes/LeetCode第189号问题:Rotate-Array.md). For linked lists, reversal involves reassigning next pointers iteratively while maintaining previous and current node references. While the raw analysis focuses primarily on array reversal (Rotate Array), the underlying principle—rearranging elements by modifying existing links rather than allocating new nodes—applies to linked list problems as well, achieving O(1) space complexity in both data structures.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →