LeetCode: Arrays 101: Introduction – Solutions


LeetCode is a good place to practice programming by solving problems of all levels!

After you solve a problem, you’ll get access to all submitted solutions, sorted by time and memory usage. That’s a nice way to compare your code to others and see what you did well and where you can improve.

Here’s my solutions for the Arrays 101: Introduction card:

Max Consecutive Ones


class Solution:
    def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
        max_counter = 0
        counter = 0
        for i in nums:
            if i == 1:
                counter += 1
                if counter > max_counter:
                    max_counter = counter
                counter = 0
        if counter > max_counter:
            max_counter = counter
        return max_counter

Find Numbers with Even Number of Digits


class Solution:

    def is_even(value):
        return len(str(value)) % 2 == 0

    def findNumbers(self, nums: List[int]) -> int:
        return_value = 0
        for number in nums:
            if self.is_even(number):
                return_value += 1
        return return_value

Squares of a Sorted Array


When writing code like this be careful because you’re altering the A list in place.

class Solution:
    def sortedSquares(self, A: List[int]) -> List[int]:
        for index, num in enumerate(A):
            A[index] = num ** 2
        return sorted(A)

Thanks for reading!

If you like what I’m writing, don’t forget to subscribe! 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.