Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Leetcode] 771. Jewels and Stones #26

Open
rmorabia opened this issue Feb 26, 2019 · 3 comments
Open

[Leetcode] 771. Jewels and Stones #26

rmorabia opened this issue Feb 26, 2019 · 3 comments

Comments

@rmorabia
Copy link

rmorabia commented Feb 26, 2019

Link: https://leetcode.com/problems/jewels-and-stones/

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:

Example 2:

Input: J = "z", S = "ZZ"
Output: 0
@rmorabia
Copy link
Author

rmorabia commented Feb 26, 2019

var numJewelsInStones = function (J, S) {
  let count = 0
  for (let i = 0; i < S.length; i++) {
    if (J.includes(i)) {
      count++
    }
  }
  return count
}

This is O(n^2).

@rmorabia
Copy link
Author

rmorabia commented Feb 26, 2019

var numJewelsInStones = function (J, S) {
  // Convert J to object
  // No ordering issues like arrays
  // KEYS ARE UNIQUE, values are not!
  const obj = {}
  for (let i = 0; i < J.length; i++) {
    obj[J[i]] = 1
  }

  // For every value in S, if the key in object exists, bam slam.
  let counter = 0
  for (let i = 0; i < S.length; i++) {
    if (obj[S[i]]) {
    counter++
    }
  }
  return counter
}

This is O(n). Accessing the object is constant time.

@cs-cordero
Copy link

cs-cordero commented Feb 27, 2019

Python Solution.

Time: O(J+S)
Space: O(J)

    def numJewelsInStones(self, J: str, S: str) -> int:
        jewels = set(J)
        return sum(stone in jewels for stone in S)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants