Jewels And Stones

  • 0

    Click here to see the full article post

  • 0

    Sorting of 2 strings(Say based on ASCII character, so all small letters would appear in the front followed by block letters as per ASCII code.
    Then compare each character in J with each character in S. Keep track of the previously visited place in each string visited.
    Then when once you reach end of string in one of the string, stop the while loop.

    Total time complexity,
    O(SlogS)--> sort the stone input, O(JlogJ)-->sort jewel input.'
    Max(O(J), O(S)) to check the matching.
    time complexity is O(SLogS) totally

  • 0

    Better solution here:

    public int numJewelsInStones(String J, String S) {
        boolean[] dictionary = new boolean[256];
        for(int i=0; i<J.length(); i++){
            dictionary[J.charAt(i)] = true;
        int count = 0;
        for(int i=0; i<S.length(); i++){
        return count;

  • 1

    One line solution in Javascript

    var numJewelsInStones = function(J, S) {
        return S.split("").reduce((count, ele) => J.includes(ele) ? count + 1 : count, 0);

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.