← Home

1540. Can Convert String in K Moves

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
straightforward implementationC++Markdown
154

I like to read this solution as a small machine: keep the useful information, throw away the noise. For 1540. Can Convert String in K Moves, the solution in this repository is mainly a straightforward implementation solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: straightforward implementation.

Guide

When?

This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are canConvertString, diff, used, nextseq, counter.

Guide

Why?

The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.

  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(N), space: O(1)
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 212 ms, faster than 100.00% of C++ online submissions for Can Convert String in K Moves.
02//Memory Usage: 176.3 MB, less than 33.33% of C++ online submissions for Can Convert String in K Moves.
03class Solution {
04public:
05    bool canConvertString(string s, string t, int k) {
06        int n = s.size();
07        if(t.size() != n) return false;
08        
09        vector<int> diff(n, 0);
10        vector<bool> used(k+1, false); //1-based
11        vector<int> nextseq(26); //[1-25], (moves, seq)
12        iota(nextseq.begin(), nextseq.end(), 0);
13        for(int i = 0; i < n; ++i){
14            diff[i] = t[i] - s[i];
15            if(diff[i] == 0) continue;
16            if(diff[i] < 0) diff[i] += 26;
17            // cout << i << " th char, need " << diff[i] << " moves" << endl;
18            if(diff[i] > k) return false;
19            
20            int seq = nextseq[diff[i]];
21            // while(seq <= k && used[seq]){
22            //     seq += 26;
23            // }
24            if(seq <= k){
25                // cout << "we can shift this char in " << seq << " th move" << endl;
26                used[seq] = true;
27                nextseq[diff[i]] += 26;
28            }else{
29                //cannot find a move in sequence to place diff[i]
30                // cout << "cannot find" << endl;
31                return false;
32            }
33        }
34        
35        return true;
36    }
37};
38
39//counter
40//https://leetcode.com/problems/can-convert-string-in-k-moves/discuss/779903/JavaPython-3-O(n)-Count-the-shift-displacement-w-brief-explanation-and-analysis.
41//Runtime: 172 ms, faster than 100.00% of C++ online submissions for Can Convert String in K Moves.
42//Memory Usage: 18 MB, less than 33.33% of C++ online submissions for Can Convert String in K Moves.
43//time: O(N), space: O(1)
44class Solution {
45public:
46    bool canConvertString(string s, string t, int k) {
47        int n = s.size();
48        
49        if(t.size() != n) return false;
50        
51        vector<int> counter(26, 0);
52        
53        for(int i = 0; i < n; ++i){
54            int diff = t[i] - s[i];
55            if(diff < 0) diff += 26;
56            //no op
57            if(diff == 0) continue;
58            
59            //diff + counter[diff]*26: how many moves we need
60            if(k < diff + counter[diff]*26){
61                return false;
62            }
63            
64            ++counter[diff];
65        }
66        
67        return true;
68    }
69};

Cost

Complexity

Time
O(N), space: O(1)
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.