Rating changes for last rounds are temporarily rolled back. They will be returned soon. ×

shubham_kr's blog

By shubham_kr, history, 4 years ago, In English

// Leetcode question :- https://leetcode.com/problems/number-of-matching-subsequences/ //Below C++ code gives TLE on submission since I have used temporary variables to avoid repetition and for better code quality.
int numMatchingSubseq(string s, vector& words) { int n = s.length(); vector<vector> arr(26); for(int i=0;i<n;i++) { arr[s[i]-'a'].push_back(i); }

int ans=0;

    for(int i=0;i<words.size();i++) {
        string str=words[i];
        int pr=0,j=0;
        for(j=0;j<str.length();j++) {
            vector<int> v = arr[str[j]-'a'];
            auto k = lower_bound(v.begin(),v.end(),pr);
            if(k==v.end()) break;
            pr = *k +1;
        }
        ans += (j==str.length());
    }

    return ans;
}

//Same code as above but the only thing I changed is, removed the temporary variables and it got ACCEPTED. int numMatchingSubseq(string s, vector& words) { int n = s.length(); vector<vector> arr(26); for(int i=0;i<n;i++) { arr[s[i]-'a'].push_back(i); }

int ans=0;

    for(int i=0;i<words.size();i++) {
        // string str=words[i];
        int pr=0,j=0;
        for(j=0;j<words[i].length();j++) {
            // vector<int> v = arr[words[i][j]-'a'];
            auto k = lower_bound(arr[words[i][j]-'a'].begin(),arr[words[i][j]-'a'].end(),pr);
            if(k==arr[words[i][j]-'a'].end()) break;
            pr = *k +1;
        }
        ans += (j==words[i].length());
    }

    return ans;
}

Since the main reason for TLE in the first version of code is the Copying of the data in temporary variables repeatedly. So, can anyone tell me the efficient way to use variables without making copies such as by using reference which is done by Java?

=> Just for reference, Java code using temporary variables got Accepted

public int lower_bound(ArrayList v,int key) { int l=0 , h = v.size()-1; while(l<h) { int mid = (l+h)/2; if(v.get(mid)>=key) h=mid; else l=mid+1; } return h; }

public int numMatchingSubseq(String s, String[] words) {
    int n = s.length();
    ArrayList<Integer> arr[] = new ArrayList[26];
    for(int i=0;i<26;i++) {
        arr[i] = new ArrayList<>();
    }
    for(int i=0;i<n;i++) {
        arr[s.charAt(i)-'a'].add(i);

    }

    int ans=0;

    for(int i=0;i<words.length;i++) {
        String str=words[i];
        int pr=0,j=0;
        for(j=0;j<str.length();j++) {

            ArrayList<Integer> v = arr[str.charAt(j)-'a'];
            if(arr[str.charAt(j)-'a'].size()==0 || v.get(v.size()-1)<pr)  break;
            int k = lower_bound(v,pr);
            pr = v.get(k) +1;
        }
        ans += (j==str.length()?1:0);
    }

    return ans;
}

Full text and comments »

  • Vote: I like it
  • 0
  • Vote: I do not like it