LeetCode Weekly Contest 248: Problem Solutions Explained

Updated on Nov 03,2025

Table of Contents

This blog post provides comprehensive solutions and explanations for the initial three problems presented in LeetCode's Weekly Contest 248. We will explore effective strategies, code implementation, and underlying logic behind each problem, aiming to clarify the approaches for future coding contests and deepen your understanding of core algorithm concepts. This analysis focuses on making complex problems more accessible and enhancing coding skills.

Key Points

Build Array from Permutation: Understanding array manipulation using a permutation to construct a new array.

Eliminate Maximum Number of Monsters: Applying sorting and logical reasoning to eliminate the most monsters before any reach your city.

Count Good Numbers: Understanding the concepts of even and prime digits, as well as modular arithmetic to count valid number strings.

Code Implementation: Provide clear C++ code examples to demonstrate practical solutions.

Algorithmic Concepts: Cover core algorithmic ideas, such as sorting, array manipulation, and modular exponentiation.

LeetCode Weekly Contest 248 Problem Solutions

Build Array from Permutation: Detailed Solution

The 'Build Array from Permutation' problem requires constructing a new array from a given zero-based permutation array. This means creating an array 'ans' of the same length as 'nums', where 'ans[i]' is 'nums[nums[i]]' for each 'i'. The goal is to apply the given permutation to create a new array based on the original array's indices.

Understanding the Problem Statement

Given a zero-based permutation 'nums' (0-indexed), the task is to build an array 'ans' of the same length where each element 'ans[i]' is equal to 'nums[nums[i]]'. This effectively involves rearranging the elements of 'nums' based on the values at each index. This can be visualized through Example 1 below:

Input: nums = [0,2,1,5,3,4]
Output: [0,1,2,4,5,3]

In this example, the new 'ans' array is constructed by following the rule 'ans[i] = nums[nums[i]]'. So, 'ans[0] = nums[nums[0]] = nums[0] = 0', 'ans[1] = nums[nums[1]] = nums[2] = 1', and so on.

Algorithmic Approach

The problem can be solved using a simple iteration:

  1. Initialize a new array, 'ans', of the same size as 'nums'.
  2. Iterate through 'nums', computing each 'ans[i]' as 'nums[nums[i]]'.
  3. Return the resulting 'ans' array.

    This method ensures the construction of 'ans' according to the permutation mapping. The key is to correctly apply the index mapping as defined in the problem.

C++ Implementation

Here's the C++ code to implement the solution:

#include <vector>
using namespace std;

class Solution {
public:
    vector<int> buildArray(vector<int>& nums) {
        int n = nums.size();
        vector<int> ans(n);
        for (int i = 0; i < n; i++) {
            ans[i] = nums[nums[i]];
        }
        return ans;
    }
};

This code initializes 'ans' and then uses a loop to correctly map each element from 'nums' to its corresponding position in 'ans'.

Complexity Analysis

  • Time Complexity: O(n), as it iterates once through the entire array.
  • Space Complexity: O(n), due to the creation of a new array of the same size.

The simplicity of the algorithm ensures both efficiency and readability.

Using this method, you can build the array as requested efficiently, correctly rearranging the numbers according to the provided rules.

Eliminate Maximum Number of Monsters: Strategy and Code

The problem 'Eliminate Maximum Number of Monsters' involves a scenario where monsters are approaching a city at varying speeds and distances. The goal is to maximize the number of monsters eliminated before any monster reaches the city.

Problem Overview

Given two arrays, 'dist' and 'speed', representing the initial distances of 'n' monsters from the city and their respective speeds, the task is to eliminate as many monsters as possible. Each minute, you can eliminate one monster. If a monster reaches the city exactly at the start of a minute, it counts as a loss.

Example Scenario:

Input: dist = [1,3,4], speed = [1,1,1]
Output: 3

In this example, you can eliminate all three monsters. At the start of minute 0, you eliminate the first monster. At the start of minute 1, you eliminate the second monster, and so on.

Algorithmic Strategy

  1. Calculate Arrival Times: Determine the time at which each monster will reach the city by dividing its initial distance by its speed.
  2. Sort Arrival Times: Sort the arrival times in ascending order. This helps in prioritizing the monsters that will reach the city earliest.
  3. Simulate Elimination: Iterate through the sorted arrival times. If you can eliminate a monster before it arrives, increment the count of eliminated monsters and proceed to the next. If a monster reaches the city at the same time you are trying to eliminate it, you lose, and the process stops.

This approach ensures that you are always dealing with the most immediate threat first.

C++ Code Implementation

Here's a C++ implementation of this strategy:

#include <vector>
#include <algorithm>

using namespace std;

class Solution {
public:
    int eliminateMaximum(vector<int>& dist, vector<int>& speed) {
        int n = dist.size();
        vector<double> arrivalTimes(n);

        for (int i = 0; i < n; ++i) {
            arrivalTimes[i] = (double)dist[i] / speed[i];
        }

        sort(arrivalTimes.begin(), arrivalTimes.end());

        int eliminated = 0;
        for (int i = 0; i < n; ++i) {
            if (arrivalTimes[i] > i) {
                eliminated++;
            } else {
                break;
            }
        }

        return eliminated;
    }
};

This code calculates arrival times, sorts them, and then simulates the elimination process. The loop breaks as soon as a monster arrives at the city at or before the elimination attempt.

Time and Space Complexity

  • Time Complexity: O(n log n), dominated by the sorting step.
  • Space Complexity: O(n), due to the creation of the 'arrivalTimes' vector.

The efficient sorting and subsequent linear scanning offer a balance between speed and resource usage.

By calculating, sorting, and simulating, you can effectively maximize the number of monsters eliminated, thereby defending your city successfully.

Understanding the nuances of this simulation can help in other similar resource management problems.

Count Good Numbers: Detailed Analysis and C++ Implementation

The 'Count Good Numbers' problem challenges us to find how many digit strings of length 'n' can be formed under specific constraints. A digit string is considered 'good' if the digits at even indices are even and the digits at odd indices are prime.

Understanding Good Numbers

As the zero-based indexing shows, there are specific numbers at even positions, which are even digits and there should be prime numbers for any odd positions to be deemed good. The goal is to determine the count of such good digit strings.

The rules defining a 'good' string are:

  • Digits at even indices (0, 2, 4, ...) must be even (0, 2, 4, 6, 8).
  • Digits at odd indices (1, 3, 5, ...) must be prime (2, 3, 5, 7).

For example:

  • '2582' is good because the digits at even indices (2 and 8) are even and the digits at odd indices (5 and 2) are prime.
  • '3245' is not good because 3 is at an even index but is not even.

Prime and Even Number Counts

  • There are 5 even digits: 0, 2, 4, 6, and 8.
  • There are 4 prime digits: 2, 3, 5, and 7.

Modular Exponentiation

Since the answer may be very large, it should be returned modulo 10^9 + 7. Modular exponentiation can be used to compute large exponents under modulo.

Mathematical Approach

Given these constraints, here’s the mathematical formulation to solve the problem:

If the string length is 'n',

  • The number of even positions is 'ceil(n/2)'.
  • The number of odd positions is 'floor(n/2)'.

Thus, the number of 'good' strings is '5ceil(n/2) * 4floor(n/2)'.

C++ Code Implementation

Here's the C++ code that reflects this approach:

#define ll long long
const int M = 1e9+7;

ll mod(ll x){
    return ((x%M) + M) %M;
}

ll mul(ll a, ll b){
    return mod(mod(a) * mod(b));
}

ll modPow(ll a, ll b) {
    ll result = 1;
    while (b > 0) {
        if (b % 2 == 1)
            result = mul(result, a);

        a = mul(a, a);
        b /= 2;
    }
    return result;
}

int countGoodNumbers(long long n) {
    ll evenCount = (n + 1) / 2;
    ll oddCount = n / 2;

    ll evenPower = modPow(5, evenCount);
    ll oddPower = modPow(4, oddCount);

    return mul(evenPower, oddPower);
}

This code calculates the number of even and odd positions and uses modular exponentiation to compute '5evenCount * 4oddCount' modulo 'M'.

Complexity Analysis

  • Time Complexity: O(log n), due to the use of modular exponentiation.
  • Space Complexity: O(1), as it uses only a constant amount of extra space.

This log-time solution enables efficient computation, even for very large values of 'n'. The use of predefined mod power and multiplication functions streamlines the modular arithmetic. This code addresses each part of the issue in a clear and succinct manner.

How to Use LeetCode Solutions

Step-by-step guidance on implementing the code solutions

To effectively utilize these LeetCode solutions:

1. Understand the Problem: Carefully read and comprehend the problem statement. Ensure you grasp the requirements and constraints.

2. Review the Approach: Review the algorithmic approach and strategy provided in the explanation. Understand why a particular method was chosen to solve the problem efficiently.

3. Study the Code:

  • Analyze the C++ code provided. Pay attention to how variables are declared, how the loops and conditional statements are structured, and how the logic of the algorithm is translated into code.
  • Make sure you understand each line. Use comments to explain what the code does at each step.

4. Compile the Code:

  • Copy the C++ code into a suitable development environment (e.g., Visual Studio, Code::Blocks, or an online compiler like LeetCode's built-in compiler).
  • Compile the code using a C++ compiler. Resolve any syntax errors or warnings.

5. Test the Code:

  • Use the example test cases provided to test your implementation. Compare the expected output with the actual output produced by your code. Run custom test cases to further validate its correctness.
  • Address any issues that arise during testing. Debugging might be necessary to correct errors in logic or implementation.

6. Optimize the Code:

  • Evaluate the time and space complexity of your solution. Check if there are ways to reduce the algorithm’s resource usage while still maintaining correctness.
  • Review best practices for coding and efficiency, and apply optimizations as necessary.

7. Submit the Solution:

  • Once confident, submit your solution to LeetCode for evaluation. If the submission is accepted, you have successfully solved the problem.
  • If the submission is not accepted, examine the feedback provided. Common feedback includes wrong answers, runtime errors, or exceeding time or memory limits. Address these issues and resubmit.

8. Review and Reflect:

  • After a successful submission, review and reflect on the problem and your solution. Compare your approach and code with those of other users to learn new techniques or optimizations.
  • Consolidate your knowledge by documenting key aspects of the solution. Take notes on useful strategies, syntax nuances, and common pitfalls.

LeetCode Pricing Plans

Overview of LeetCode's Subscription Tiers

LeetCode offers both free and premium (paid) subscription tiers, each designed to cater to different levels of users and needs.

  • Free Tier: This tier provides access to a wide range of problems and community content, which is suitable for beginners and casual users.
  • Premium Tier: This tier includes additional features such as access to premium problems, company-specific questions, debugging tools, and an enhanced user experience.

Pricing Details:

The table below outlines the pricing and key features of LeetCode Premium plans:

Plan Type Pricing Key Features
Monthly $35/month Access to all premium questions, company-specific questions, debugging tools, no ads.
Yearly $159/year All features of the monthly plan, but with a discounted yearly rate.

Benefits of Premium:

  1. Access to Premium Questions: Practice on problems not available to free users, enhancing preparation.
  2. Company-Specific Questions: Tailor your study to target specific companies, increasing the chances of acing interviews.
  3. Debugging Tools: Utilize advanced debugging features to identify and correct errors effectively.
  4. No Ads: Enjoy an ad-free experience, focusing solely on coding.

LeetCode's tiered pricing allows users to choose the plan that best aligns with their preparation goals and budgetary constraints.

Build Array from Permutation: Advantages and Disadvantages

👍 Pros

Simplicity: Easy to understand and implement.

Efficiency: Time complexity of O(n).

Direct Application: Directly follows the problem requirements.

👎 Cons

Space Complexity: Requires additional O(n) space for the new array.

In-Place Modification Not Possible: Cannot modify the original array in place.

Key Features of the LeetCode Platform

Comprehensive Toolset for Coding Practice

LeetCode provides a robust and feature-rich environment for software engineers to enhance their coding and algorithmic skills. Here are some core features:

1. Extensive Problem Set:

  • Large collection of coding problems covering a wide range of data structures and algorithms.
  • Problems are classified by difficulty, topic, and frequency.

2. Online Judge (OJ) System:

  • Immediate feedback on code submissions with detailed reports including execution time and memory usage.
  • Support for multiple programming languages such as C++, Java, Python, and JavaScript.

3. Code Editor:

  • Built-in code editor with syntax highlighting, auto-completion, and customizable settings.
  • Option to debug and test code before submission.

4. Discussion Forums:

  • Community platform for sharing solutions, discussing approaches, and seeking help from peers and experts.
  • Upvote and downvote solutions to highlight the most helpful and efficient ones.

5. Mock Interviews:

  • Simulate real interview experiences with timed scenarios and structured interview formats.
  • Provides insights and areas for improvement.

6. Study Plans:

  • Structured study plans designed to help users focus on specific topics or prepare for interviews.
  • Curated lists of problems tailored to each plan.

7. Premium Features:

  • Exclusive access to company-specific questions, helping users target top-tier companies.
  • Advanced debugging tools and an ad-free experience.

These features collectively create an environment conducive to learning and perfecting coding skills, tailored to the needs of both novice and experienced programmers.

Use Cases: LeetCode in Action

Real-World Applications of LeetCode Skills

LeetCode isn't just a platform for competitive coding; it serves numerous practical purposes for software engineers and students:

  1. Interview Preparation:

    • Targeted practice on commonly asked interview questions.
    • Familiarization with the types of problems and constraints used in technical interviews.
  2. Skill Development:

    • Learning and reinforcing data structure and algorithm concepts.
    • Improving problem-solving abilities in a structured manner.
  3. Resume Building:

    • Demonstrates competency to potential employers by showcasing a history of solved problems.
    • Highlights proficiency in critical coding skills.
  4. Competitive Programming:

    • Participating in coding contests to improve speed and efficiency in problem-solving.
    • Gaining recognition and rewards in the coding community.
  5. On-the-Job Performance:

    • Applying algorithmic knowledge to optimize and improve code in real-world projects.
    • Facilitating better design and coding decisions.

LeetCode is a versatile tool that benefits developers throughout their career, from landing their first job to optimizing their existing code and skills.

Frequently Asked Questions

What is the 'Build Array from Permutation' problem about?
The 'Build Array from Permutation' problem involves constructing a new array by applying a given permutation to the indices of the original array. The aim is to rearrange elements based on this permutation.
How do I effectively 'Eliminate Maximum Number of Monsters'?
To maximize the number of monsters eliminated, you need to calculate the arrival time of each monster, sort these times, and then simulate the elimination process. You prioritize the monsters that will arrive soonest and eliminate them before they reach the city.
What makes a digit string 'good' in 'Count Good Numbers'?
A digit string is considered 'good' if its digits at even indices are even numbers and the digits at odd indices are prime numbers. These are the core criteria for creating valid strings in this problem.
How can modular exponentiation help in 'Count Good Numbers'?
Modular exponentiation is crucial for efficiently calculating large powers modulo a number. This ensures the computations remain within reasonable bounds, preventing overflow issues, and facilitating accurate results.
Why is the time complexity important in these LeetCode problems?
Time complexity indicates how the runtime of an algorithm increases as the input size grows. Aiming for lower time complexities (e.g., O(n log n), O(log n)) allows the solutions to handle large datasets efficiently, complying with LeetCode's performance requirements.

Related Questions

What are some related algorithmic concepts to these LeetCode problems?
The problems discussed touch upon several critical algorithmic concepts: Permutation: The 'Build Array from Permutation' problem directly uses the concept of permutations to rearrange elements, a fundamental topic in combinatorics and algorithm design. Understanding permutations is crucial in many array manipulation and combinational optimization problems. Greedy Algorithms: The 'Eliminate Maximum Number of Monsters' problem utilizes a greedy strategy, where we make the locally optimal choice at each step—eliminating the closest monster first—to achieve a global optimum. Greedy algorithms are widely used in optimization problems for their simplicity and efficiency. Sorting Algorithms: Sorting is a fundamental algorithmic technique applied in 'Eliminate Maximum Number of Monsters' to arrange the monster arrival times. Mastery of sorting algorithms like merge sort, quicksort, and heapsort is essential in many problem-solving scenarios. Modular Arithmetic: Crucial for the 'Count Good Numbers' problem, modular arithmetic is fundamental in cryptography, number theory, and computer science. It enables calculations with large numbers by performing arithmetic operations with a modulus, preventing overflow and simplifying computations. Recursion: Recursion is a problem-solving technique where a function calls itself within its definition. It can be used to solve complex problems by breaking them down into smaller, more manageable sub-problems. Modular exponentiation can be implemented recursively or iteratively, showcasing recursion's utility. Data Structures: Effective usage of data structures like arrays and vectors is crucial for managing and manipulating data in these problems. Choosing the right data structure often simplifies the algorithmic process and improves efficiency. For example, arrays provide constant-time access by index, which is beneficial in the 'Build Array from Permutation' problem. These algorithmic concepts are broadly applicable and form the basis for solving a wide variety of coding challenges, making a solid understanding of these topics essential for any software engineer or computer science student. The complexity and elegance of many algorithmic solutions often depend on mastering these underlying principles.

Most people like