Why does LeetCode use solution class? Does the class ever help?

This is LeetCode question #1. I was wondering why LeetCode likes to use a solution class. I reformat the solution to a function without a class and call it:

def twoSum2(nums, target):
    hashmap = {}
    for i in range(len(nums)):
        complement = target - nums[i]
        if complement in hashmap:
            return [i, hashmap[complement]]
        hashmap[nums[i]] = i

nums1 = [2,7,11,15]
target1 = 9
sol2 = twoSum2(nums1, target1)
print(sol2)

Output:

[1, 0]

This is LeetCode’s solution class:

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        hashmap = {}
        for i in range(len(nums)):
            complement = target - nums[i]
            if complement in hashmap:
                return [i, hashmap[complement]]
            hashmap[nums[i]] = i

How may I call it? When I call it, my PyCharm could not even read it. It does not even understand what “List” means and I got an error. I am trying to do it but I can’t call the solution class provided by leetcode:

sol1 = Solution()
sol11 = sol1.twoSum(nums1, target1)
print(sol11)

How may I call the solution class? Would anyone write such a class in practical work? Thank you!!

Everyone has opinions. I tend to lean more toward functional
programming than object-oriented, and Python can be used for either
(or a mix of the two). To me, that example looks sort of like
someone set a C++ programmer loose with Python, but you certainly
can create usable programs where every last thing is instantiated
from a custom class, if that’s how you prefer to model your code.

1 Like

Java programmer, not C++. Fear of free-standing functions is a classic Java infliction. This code has Java, or maybe C#, written all over it.

The missing import that causes it to fail is

from typing import List
1 Like