How C++, Java, Python, Go, and JavaScript Handle Multi-Language Algorithm Optimization Differently

Multi-language algorithm optimization in the leetcode-master repository leverages language-specific data structures—such as C++ unordered_map, Java HashMap, Python dict, Go map, and JavaScript Object—to achieve O(n) time complexity while respecting each language's memory model and idiomatic patterns.

The youngyangyang04/leetcode-master repository maintains a comprehensive collection of LeetCode solutions where the same algorithmic logic is implemented across C++, Java, Python, Go, and JavaScript. While the high-level approach remains constant—typically utilizing hash-based lookups for problems like Two Sum—each language implementation exploits native constructs to minimize time and space overhead.

Core Optimization Strategy Across Languages

Every implementation in problems/0001.两数之和.md targets O(n) time complexity by replacing the brute-force O(n²) nested loop with a single-pass hash lookup. The repository explicitly documents this optimization in the "思路" section, noting that hash tables provide constant-time existence checks.

However, the choice of hash table implementation varies by language to maximize performance:

  • C++: Uses std::unordered_map rather than std::map to avoid O(log n) red-black tree overhead
  • Java: Uses java.util.HashMap with explicit containsKey checks, contrasting with a commented-out TreeMap alternative
  • Python: Uses the built-in dict type with amortized O(1) performance
  • Go: Uses the built-in map type with the "comma-ok" idiom for existence testing
  • JavaScript: Uses plain objects {} as hash tables, guarding against undefined false positives

Language-Specific Implementation Details

C++: std::unordered_map for Average O(1) Performance

The C++ implementation in problems/0001.两数之和.md explicitly selects std::unordered_map over std::map because the hash table provides average O(1) insertion and lookup, while the tree-based std::map would impose O(log n) overhead.

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        std::unordered_map<int,int> map;
        for (int i = 0; i < nums.size(); ++i) {
            auto it = map.find(target - nums[i]);
            if (it != map.end()) return {it->second, i};
            map.insert({nums[i], i});
        }
        return {};
    }
};

Source: problems/0001.两数之和.md (lines 93-106)

The code uses auto for iterator type deduction and pair<int,int> for insertion, following modern C++ idioms that minimize boilerplate while maintaining zero-cost abstraction.

Java: HashMap with Explicit Complexity Trade-offs

The Java implementation mirrors the C++ approach but includes a commented-out TreeMap version to demonstrate the O(log n) versus O(1) trade-off explicitly.

public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        int complement = target - nums[i];
        if (map.containsKey(complement)) {
            return new int[]{map.get(complement), i};
        }
        map.put(nums[i], i);
    }
    return new int[0];
}

Source: problems/0001.两数之和.md (lines 31-44)

The implementation uses Map.containsKey() for existence testing rather than get() followed by null checking, which avoids ambiguity when hash values themselves might be null (though HashMap permits null keys, the pattern remains idiomatic).

Python: Built-in dict with Amortized O(1) Performance

Python's implementation leverages the built-in dict type, which is implemented as a hash table with amortized O(1) performance. The code uses enumerate for clean index-value iteration.

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        records = {}
        for idx, val in enumerate(nums):
            if target - val in records:
                return [records[target - val], idx]
            records[val] = idx
        return []

Source: problems/0001.两数之和.md (lines 14-22)

The Python version also includes an alternative using set for membership testing only, but retains the dict for the primary solution because the problem requires returning indices, which sets cannot store.

Go: Built-in map with Comma-Ok Idiom

Go's implementation uses the language's built-in map type, which is a hash table with O(1) average-case performance. The code demonstrates Go's idiomatic "comma-ok" pattern for checking key existence.

func twoSum(nums []int, target int) []int {
    m := make(map[int]int)
    for i, num := range nums {
        complement := target - num
        if idx, ok := m[complement]; ok {
            return []int{idx, i}
        }
        m[num] = i
    }
    return nil
}

Source: problems/0001.两数之和.md (lines 27-34)

The if idx, ok := m[complement]; ok pattern explicitly separates the value retrieval from the existence check, preventing the zero-value confusion that could occur if the map returned 0 for missing keys.

JavaScript: Plain Object as Hash Table

The JavaScript implementation uses a plain object {} as a hash table, leveraging V8's optimized property access which approaches O(1) in modern engines. The code guards against undefined to avoid false positives when checking for key existence.

var twoSum = function(nums, target) {
  let hash = {};
  for (let i = 0; i < nums.length; i++) {
    if (hash[target - nums[i]] !== undefined) {
      return [i, hash[target - nums[i]]];
    }
    hash[nums[i]] = i;
  }
  return [];
};

Source: problems/0001.两数之和.md (lines 44-50)

The explicit !== undefined check is necessary because JavaScript objects return undefined for missing properties, but undefined could theoretically be a stored value (though not in this specific algorithmic context).

Alternative Approaches and Trade-offs

Beyond the hash-table approach, problems/0001.两数之和.md includes a sorting + two-pointer implementation for C++, Java, Python, and Go. This alternative demonstrates the classic time-space trade-off:

  • Time Complexity: O(n log n) due to sorting
  • Space Complexity: O(1) extra space (excluding the sort operation's overhead)

The repository presents this variant to illustrate that while hash tables offer optimal O(n) time, they require O(n) space. Languages with efficient in-place sorting (like C++ with std::sort) can offer viable alternatives when memory is constrained.

Key Files in the Repository

File Languages Covered Optimization Insight
problems/0001.两数之和.md C++, Java, Python, Go, JavaScript, Rust, Swift, Scala, C#, Dart, PHP, C Demonstrates hash-table selection criteria and alternative sorting approaches across all supported languages
problems/算法模板.md C++, Java, Python, Go, JavaScript Generic algorithm templates (sliding-window, binary-search) showing how the same optimization patterns translate across languages
problems/链表理论基础.md C++, Java, Python, Go, JavaScript Memory management differences in pointer manipulation, crucial for understanding why C++ uses raw pointers while Java/Python use references
problems/图论深搜理论基础.md C++, Java, Python, Go, JavaScript Recursion depth limits and stack overflow considerations, explaining why Python requires explicit recursion limits while C++ handles deeper recursion natively
README.md – Documents the repository philosophy: "C++ 为主,配多语言实现" (C++ primary, with multi-language implementations), establishing the optimization priority framework

Summary

  • Hash-table selection drives the primary optimization across all languages, with each implementation choosing the fastest available map structure (unordered_map in C++, HashMap in Java, built-in dict/map in Python and Go, and plain objects in JavaScript).

  • Language idioms determine implementation details: C++ uses iterator-based find(), Java uses containsKey(), Python uses the in operator, Go uses the comma-ok pattern, and JavaScript uses undefined guards.

  • Complexity trade-offs are explicitly documented in the repository, with alternative sorting-based solutions provided to demonstrate the time-space trade-off when memory constraints prohibit O(n) auxiliary space.

  • Repository structure in youngyangyang04/leetcode-master maintains parallel implementations in problems/0001.两数之和.md and related files, ensuring consistent algorithmic logic while respecting each language's performance characteristics.

Frequently Asked Questions

Why does the C++ implementation use std::unordered_map instead of std::map?

The C++ implementation in problems/0001.两数之和.md explicitly chooses std::unordered_map because it provides average O(1) insertion and lookup via hashing, whereas std::map implements a red-black tree with O(log n) operations. For the Two Sum problem requiring single-pass existence checks, the hash table's constant time complexity is strictly superior.

How does Python's dict compare to Java's HashMap in terms of algorithmic optimization?

Both Python's built-in dict and Java's HashMap provide amortized O(1) average-case performance for insertions and lookups. However, Python's dict is optimized for the CPython interpreter with specialized key hashing and open addressing, while Java's HashMap handles object references and resizing policies differently. The repository shows Python using the in operator for existence checks, while Java uses explicit containsKey() method calls, reflecting each language's idiomatic patterns.

Why does the JavaScript solution check for undefined instead of using hasOwnProperty?

The JavaScript implementation in problems/0001.两数之和.md uses hash[target - nums[i]] !== undefined to check for key existence because it is more concise and performs sufficiently for the problem constraints. While hasOwnProperty would guard against prototype chain inheritance issues, the repository's solution uses a plain object {} initialized fresh in the function scope, eliminating prototype pollution risks. The explicit undefined check prevents false positives when the stored index is 0, which would be falsy in a simple truthiness check.

What alternative optimization approach does the repository provide when memory is constrained?

Beyond the standard hash-table approach requiring O(n) extra space, the repository includes a sorting + two-pointer implementation in problems/0001.两数之和.md for C++, Java, Python, and Go. This approach first sorts the array (O(n log n) time) then uses two pointers from opposite ends to find the complement pair (O(n) time), resulting in O(1) extra space complexity. This demonstrates the classic time-space trade-off, offering a viable alternative when the input array is large and auxiliary memory is limited.

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 →