LeetCode 3006: Find Beautiful Indices in the Given Array I Solution

Master LeetCode problem 3006 (Find Beautiful Indices in the Given Array I), a medium 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.

3006. Find Beautiful Indices in the Given Array I

Problem Explanation

Explanation

To solve this problem, we can iterate through the given string s and check for each index if it forms a beautiful index. For each index i, we check if the substring starting at i and having length a.length is equal to string a. If it is, we then search for an index j such that the substring starting at j and having length b.length is equal to string b and the absolute difference between i and j is less than or equal to k.

We can implement this by iterating through the string s, checking for each index if it is a beautiful index according to the conditions mentioned above. If an index is beautiful, we add it to the result array.

The time complexity of this solution is O(n * m) where n is the length of string s and m is the maximum of lengths of strings a and b. The space complexity is O(n) where n is the length of string s.

Solution Code

import java.util.ArrayList;
import java.util.List;

class Solution {
    public List<Integer> beautifulIndices(String s, String a, String b, int k) {
        List<Integer> result = new ArrayList<>();
        int alen = a.length();
        int blen = b.length();
        
        for (int i = 0; i <= s.length() - alen; i++) {
            if (s.substring(i, i + alen).equals(a)) {
                for (int j = 0; j <= s.length() - blen; j++) {
                    if (s.substring(j, j + blen).equals(b) && Math.abs(i - j) <= k) {
                        result.add(i);
                        break;
                    }
                }
            }
        }
        
        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 3006 (Find Beautiful Indices in the Given Array I)?

This page provides optimized solutions for LeetCode problem 3006 (Find Beautiful Indices in the Given Array I) 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 3006 (Find Beautiful Indices in the Given Array I)?

The time complexity for LeetCode 3006 (Find Beautiful Indices in the Given Array I) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 3006 on DevExCode?

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

Back to LeetCode Solutions