Untitled

Anonymous
python
02/12/2026 9:52 AM
2.5 KB
8
Indexable
from collections import defaultdict 
def maxdistance(arr):
    hashmap = defaultdict(int) 
    maxlen = 0
    for i in range(len(arr)):
        if arr[i] in hashmap:
            d = i - hashmap[arr[i]] 
            if d > maxlen:
                maxlen = d 
        else:
            hashmap[arr[i]] = i 
    return maxlen 
### problem2 counting pairs with sum x 
def count_sum(arr,x):
    answer = 0 
    hashmap = defaultdict(int) 
    for nums in arr:
        comp = x -  nums 
        if comp in hashmap:  
            answer = answer + hashmap[comp] 
        hashmap[nums] += 1 
    return answer 
##  problem3 returning the index of the unique element 
def find_unique(s):
    hashmap = defaultdict(int) 
    for char in s:
        hashmap[char] += 1 
    for i in range(len(s)):
        if hashmap[s[i]] == 1:
            return i 
    return -1 
## problem 4 to find common elements 
class Solution:

    def commonChars(self, words: List[str]) -> List[str]:
        words_size = len(words)
        result = []

        # Initialize common_character_counts with the characters from the first word
        common_character_counts = collections.Counter(words[0])

        for i in range(1, words_size):
            # Count characters in the current word
            current_character_counts = collections.Counter(words[i])

            # Update the common character counts to keep the minimum counts
            for letter in common_character_counts.keys():
                common_character_counts[letter] = min(
                    common_character_counts[letter],
                    current_character_counts[letter],
                )

        # Collect the common characters based on the final counts
        for letter, count in common_character_counts.items():
            for _ in range(count):
                result.append(letter)

        return result
Editor is loading...
Leave a Comment