Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Basic Time Complexity Help
#1
Hello Everyone,

This is my first post so if do manage to do something incorrectly please let me know. The question i have is regarding time complexity. It is a basic question and i want to see if i have a proper grasp of bigO notation.

Language: Python 3
Problem: Leetcode 771

You're given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels.

The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive, so "a" is considered a different type of stone from "A".

Example 1:
  • Input: J = "aA", S = "aAAbbbb"
  • Output: 3

Example 2:
  • Input: J = "z", S = "ZZ"
  • Output: 0

Note:
S and J will consist of letters and have length at most 50.
The characters in J are distinct.

Here is my code:

class Solution:
    def numJewelsInStones(self, J: str, S: str) -> int:
        x = 0
        for jewels in J:
            x = x + S.count(jewels)
        return(x)
**Now the time complexity (MY GUESS):
Since I traverse through J (for loop), and given J can have a length at most 50 that gives me O(J.Len) worse case. Now inside my for loop i use the count() method, which checks the occurrence of each element and its time complexity is O(n), n being the len of the string is searches. For my case S can be of len 50 at worse case. So making the time complexity of my code O(J.len) * O(S.len)or O(J.len*S.len)?

Is that correct?
Reply
#2
Yes. But you can do it in O(len(J)) + O(len(S))
from collections import defaultdict

jewels = "aA"
stones = "aAAbbbb"
count = defaultdict(int)

for stone in stones: # O(len(stones))
    count[stone] += 1
    
for jewel in jewels: # O(len(jewels))
    try:
        print(f'{jewel}:{count[jewel]}')
    except ValueError:
        print(f'{jewel}:0')
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  What is the run time complexity of this code and please explain? samlee916 2 2,289 Nov-06-2020, 02:37 PM
Last Post: deanhystad
  [split] Time Complexity of Counting Mekire 9 7,692 Jan-10-2019, 11:09 AM
Last Post: Gribouillis
  Time complexity of dict vs attributes heras 6 3,760 Aug-24-2018, 10:18 PM
Last Post: Gribouillis
  How to calculate the mccabe complexity in module falke8? fuqianz 1 3,118 Oct-16-2017, 02:08 AM
Last Post: sparkz_alot

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020