< Back to forum

approach to this problem

Link To Problem

my approach- i made a copy of the array, and sorted the copy of the array...

now i traverse the given array,and find the correspoding position of the element in the sorted array...

now ,i check if there is any position in between the indexes of both of the position(i.e the given array,and the sorted) which is not allowed to swap.. if there is  then the answer is no....

here is the solution....

 My Code

but the tag that i saw in the question was of dfs...any approach on how dfs will be implemented...

Asked by: Shubham_Gupta on April 7, 2019, 6:34 p.m. Last updated on April 7, 2019, 6:34 p.m.


Enter your answer details below:


Enter your comment details below:




2 Answer(s)

avatar

Firstly, please use the fact that all elements are in range of 1 to n and occur exactly once. So do you need to create the vector "ss" that you have used and sort it? The position in sorted array of any element will be the element itself.

Second, this would have been my approach. Let us create islands using the provided binary string. A group of 1s and a single following 0 forms one island. Any other 0 forms another island.
Example, for the string: 1110110
We have two islands, [1110] and [110]

Similarly, for the string 0110010, we will get following islands [0], [110], [0], [10].

Now, any number in one island cannot jump to another island by any possible swapping. Any number in the island can move within the island by any possible swapping. So we just have to check that all numbers in an island are in the range of the island position. That is, if an island extends from 1st position to 4th position, all the elements in the orginal array in 1st to 4th position should be in the range [1,4]. Can't see use of DFS, nor sorting. Single traversal.

Siddharth_Garg last updated on April 7, 2019, 6:34 p.m. 0    Reply    Upvote   

avatar

THIS IS A TEST ANSWER. DONT BOTHER YOURSELF WITH THE CONTEN. THIS IS ONLY MEANT FOR TESTING PURPOSE. THANKS.

RECursion_Website_Tester last updated on April 7, 2019, 6:34 p.m. 0    Reply    Upvote   

Instruction to write good question
  1. 1. Write a title that summarizes the specific problem
  2. 2. Pretend you're talking to a busy colleague
  3. 3. Spelling, grammar and punctuation are important!

Bad: C# Math Confusion
Good: Why does using float instead of int give me different results when all of my inputs are integers?
Bad: [php] session doubt
Good: How can I redirect users to different pages based on session data in PHP?
Bad: android if else problems
Good: Why does str == "value" evaluate to false when str is set to "value"?

Refer to Stack Overflow guide on asking a good question.