LeetCode 1961: Check If String Is a Prefix of Array Solution

Master LeetCode problem 1961 (Check If String Is a Prefix of Array), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1961. Check If String Is a Prefix of Array

Problem Explanation

Explanation:

To solve this problem, we can iterate through the array of words and concatenate them one by one until the concatenated string matches the input string s. If at any point the concatenated string becomes longer than s, we can immediately return false. If the concatenated string matches s, we return true.

  • Algorithm:

    1. Initialize an empty string concatenated.
    2. Iterate through the array of words.
    3. For each word, concatenate it to the concatenated string.
    4. Check if the concatenated string matches the input string s.
    5. If the concatenated string matches s, return true.
    6. If the concatenated string becomes longer than s, return false.
    7. Return false at the end if no match is found.
  • Time Complexity: O(N) where N is the total number of characters in the input string s and all words in the array.

  • Space Complexity: O(N) for the concatenated string.

:

Solution Code

class Solution {
    public boolean isPrefixString(String s, String[] words) {
        String concatenated = "";
        for (String word : words) {
            concatenated += word;
            if (concatenated.equals(s)) {
                return true;
            }
            if (concatenated.length() > s.length()) {
                return false;
            }
        }
        return false;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1961 (Check If String Is a Prefix of Array)?

This page provides optimized solutions for LeetCode problem 1961 (Check If String Is a Prefix of Array) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1961 (Check If String Is a Prefix of Array)?

The time complexity for LeetCode 1961 (Check If String Is a Prefix of Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1961 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1961 in Java, C++, or Python.

Back to LeetCode Solutions