Solution 2 for Scaler Topics Fortnightly Contest - 25

Learn via video courses
Topics Covered

Build an AI-First Career, Master the Complete Skillset

Choose from our industry-leading programs designed for career success

NSDC Certified

Modern Software and AI Engineering Program

Master full-stack development with AI integration

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

Modern Data Science and ML with specialisation in AI

Advanced data science techniques with AI specialization

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

Advanced AIML with Specialisation in Agentic AI

Deep dive into AIML with focus on Agentic systems

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

DevOps, Cloud & AI Platform Engineering

Build and manage AI-powered cloud infrastructure

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

AI Engineering Advanced Certification by IIT-Roorkee

Premier AI engineering certification from IIT-Roorkee

3 MonthsDuration
AI-LedCurriculum
Career SupportSupport
Program highlights
Go to Program
NSDC Certified

AI Forward Deployed Engineer Program

Full-stack engineering, production AI and client-facing consulting

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program

Mesmerizing Necklace Arrangement

This article is part of the Scaler Topics Fortnightly Contest - 25

Solution Approach

We’ll utilize two arrays: prefixR[i] to represent the count of ‘R’ beads in the prefix of length i and prefixB[i] to denote the count of ‘B’ beads in the prefix of length i.

Consider two positions, i and j, where 0 ≤ i ≤ j ≤ n. Our objective is to remove all ‘B’ beads from the prefix ending at position i, from the suffix starting at position j, and also all ‘R’ beads between positions i and j. The minimum number of beads needed to be removed can be calculated as prefixB[i] + (prefixB[N] - prefixB[j]) + (prefixR[j] - prefixR[i]).

To achieve this, we can employ a two-pointer approach using nested loops. Iterate through all possible positions of i and j and compute the answer by considering the given conditions.

Time Complexity: O(N * N) Space Complexity: O(2 * N)

Sharpen Your Fundamentals with Free Learning

C++ Implementation

How Scaler Transformed Careers in Different Fields

₹23L
AVG CTC
SCALER PLACEMENT PROOF

Scaler learners achieved 2.5x salary growth with average post-Scaler CTC reaching ₹23L.

11,000+placements
650+companies
Verified data
Hiring Partners:
GoogleGoogleAmazonAmazonMicrosoftMicrosoftFlipkartFlipkartAdobeAdobe1200+ more

Java Implementation

Python Implementation