### Loser_'s blog

By Loser_, 2 years ago,

I just completed CSES Sorting and Searching section problems. And I didn't find any editorials for this. So I am writing my own approach for the problems.Please do correct me if I made any mistakes and do share your approach for the problems.

My solutions are here

## complete editorial for CSES coding platform of all 27 problems in Sorting and Searching section.

1.Distinct Numbers

Editorial
idea

2.Apartments

Editorial
idea

3.Ferris Wheel

Editorial
idea

4.Concert Tickets

Editorial
idea

5.Restaurant Customers

Editorial
idea

6.Movie Festival

Editorial
idea

7.Sum of Two Values

Editorial
idea

8.Maximum Subarray Sum

Editorial
idea

9.Stick Lengths

Editorial
idea

10.Playlist

Editorial
idea

11.Towers

Editorial
idea

12.Traffic Lights

Editorial
idea

13.Room Allocation

Editorial
idea

14.Factory Machines

Editorial
idea

Editorial
idea

Editorial
idea

17.Sum of Three Values

Editorial
idea

18.Sum of Four Values

Editorial
idea

19.Nearest Smaller Values

Editorial
idea

20.Subarray Sums I

Editorial
idea

21.Subarray Sums II

Editorial
idea

22.Subarray Divisibility

Editorial
idea

23.Array Division

Editorial
idea

24.Sliding Median

Editorial
idea

25.Sliding Cost

Editorial
idea

26.Movie Festival II

Editorial
idea

27.Maximum Subarray Sum II

Editorial
idea

• +4

 » 2 years ago, # |   0 Thank You so much
•  » » 2 years ago, # ^ |   0 Welcome
 » 2 years ago, # |   0 thanks
•  » » 2 years ago, # ^ |   0 welcome
 » 23 months ago, # | ← Rev. 2 →   0 .
 » 23 months ago, # |   0 Thanks a lot,man
 » 22 months ago, # |   0 too helpful, thanks
 » 22 months ago, # |   0 how is this working in 25th problem sliding costabs(p-a[i+m])-abs(P-a[i]) and if m is even we decrease the extra value p-Pcan someone explain why the common elements in the the windows are not considered for new cost ? Please explain the math behind it
•  » » 22 months ago, # ^ | ← Rev. 2 →   0 In this problem,everytime we check for a window of k elements.First we check for first k elements and store it's mid value in P(capital). Then with each iteration we erase the first value from window and add the next value from the array.See,if the initial set is 2 3 4 after iteration it's 3 4 5.After the iteration mid value is p(small).Now after the new value added to set the cost is abs(p-a[i+m]) and the previous cost is abs(P-a[i]).So the change of total cost d is simply the difference between these two.Now when it's come to even value ,Like this one- 8 4 2 4 3 5 8 1 2 1 Here the previous window is 2 3 4 5 and after 1st iteration 3 4 8 5. P(capital)=3, p(small)=4; Unlike the odd k ,even k has two mid value. So either 1st mid value gives you the min cost or the 2nd mid value. If you notice then P(capital) is 1st mid value, p(small) is 2nd mid value. That's the reason we simply erase the extra value(it's either add to total cost or decreases).I hope it makes sense.
•  » » » 22 months ago, # ^ |   +4 If you notice then P(capital) is 1st mid value, p(small) is 2nd mid value this statement is not always true.You just explained the code, I want some kind of mathematical proof of why this works ? Why changing median doesn't effect cumulative cost of the common elements is the windows ?
•  » » » 19 months ago, # ^ | ← Rev. 2 →   0 Yes a mathematical proof would be helpful.
 » 22 months ago, # |   0 Thanks a lot!
 » 22 months ago, # |   0 I guess for question number 10 sliding window concept will be much more intuitive. Here is my ac solution, #include using namespace std; int main() { int n; cin>>n; vectork(n); for(int i=0;i>k[i]; setst; int ans = 0,j=0; for(int i=0;i
•  » » 19 months ago, # ^ |   0 Hi, can you please share with me the expected time complexity of your code and how exactly could you determine if your code could pass the given test cases? It seems to me that complexity would be O(n^2) since there is a while loop inside the outer for loop?Yet your code seems to pass all the test cases within the accepted time limit, HOW?
•  » » » 19 months ago, # ^ |   0 the time complexity is $\mathcal O(N\log N)$ since it uses sliding window and a set. Sliding window uses two loops and takes $\mathcal O(N)$; notice that $j$ does not reset to $0$ and retains it's value every time $i$ increases.
 » 20 months ago, # |   0 For 10. Playlist I used two-pointer technique with sliding window concept, It is much more intuitive.Keep on increasing window length, while we have subarray a with unique numbers. As soon as we find a duplicate, we delete from the array till the subarray does not contain duplicate
•  » » 20 months ago, # ^ |   0 Main concept is — erase every $k$th element from the circular array(in I,$k=1$).Remember erase function is $O(n)$ so it definitely causes TLE.Use ordered set instead whose erase function complexity is $log(n)$. int n,k;cin>>n>>k; ordered_set josep; for(int i=1;i<=n;++i)josep.insert(i); int pos=0; while(josep.size()>1) { pos=(pos+k)%(int)josep.size(); cout<<*(josep.find_by_order(pos))<<' '; josep.erase(*(josep.find_by_order(pos))); pos%=(int)josep.size(); } cout<<*(josep.find_by_order(0))<
•  » » » 4 weeks ago, # ^ |   0 #include #include using namespace __gnu_pbds; using namespace std; template using ordered_set = tree, rb_tree_tag, tree_order_statistics_node_update>; int n,k; ordered_set s; int main() { scanf("%d%d",&n,&k);k--; for(int i=1;i<=n;++i) s.insert(i); int pos=0; while((int)s.size()>1) { pos=(pos+k)%(int)s.size(); printf("%d ",*(s.find_by_order(pos))); s.erase(*(s.find_by_order(pos))); pos%=(int)s.size(); } printf("%d\n",*(s.find_by_order(0))); return 0; } ordered_set should be used like this...
 » 20 months ago, # |   0 There are 35 problems in this section .
•  » » 20 months ago, # ^ |   0 They are newly added problems which I didn't solve entirely. If someone wants to contribute happy to add them all
 » 19 months ago, # |   0 In problem no 6 why it is necessary to sort elements based on ending time. Why can't we sort elements based on starting time?
•  » » 19 months ago, # ^ |   0 suppose there is a case 1 20 2 3 3 4 4 5 in this case when you select the movie that start early you will not be able to select another movie therefore it is better to sort movie that finish early so that we can select another movie if available.
 » 19 months ago, # | ← Rev. 2 →   0 Loser_ I tried everthing but test case 5 in ques 6 (Movie Festival) is giving run time errorLINK TO MY CODEi have given link to my code. Can anyone help?
•  » » 19 months ago, # ^ |   0 comparator should return false in equal case. Else it gives error. in sortbysecinc function (return a.second
•  » » » 19 months ago, # ^ |   0 Thank you so much for the reply. it worked.
 » 19 months ago, # |   0 Um.. Converting code to English words can't be called an editorial, but good job. Atleast people have some reference point where they can look for solutions.
 » 18 months ago, # |   0 Can someone explain the proof for 15-> Tasks and Deadlines ?
•  » » 9 months ago, # ^ |   0 Let's take the testcase given in the problem and write out all possible combinations: (10-6) + (12-11) + (15-19) => reward = 1 (10-6) + (15-14) + (12-19) => reward = -2 (15-8) + (10-14) + (12-19) => reward = -4 (15-8) + (12-13) + (10-19) => reward = -3 (12-5) + (10-11) + (15-19) => reward = 2 (12-5) + (15-13) + (10-19) => reward = 0 Observations: We can observe that the deadlines are always positive while calculating the solution. The other term(consisting of the duration) is the sum of individual durations. For example, the case with reward = 1 can be written as (10-6) + (12-(6+5)) + (15-(6+5+8)). Notice that the i-th duration we choose, gets repeated in calculating all the further terms. So it makes sense to choose the durations sorted in a non-decreasing order.
 » 18 months ago, # | ← Rev. 3 →   0 Can anyone please provide me a Multiset solution for the Apartments question?
•  » » 16 months ago, # ^ |   0 Maybe it's too late but here it is: https://cses.fi/paste/74d273db0c74039e225cdc/
•  » » » 16 months ago, # ^ |   0 Thanks a lot, I appreciate your effort.
 » 17 months ago, # |   0 Thank You so much. Really helpful
 » 16 months ago, # |   0 missing coin sum gfg linkhow it come in O(n) ? start with answer = 1 while(check next sum are possible or not)code : in c++ cin >> n; int count = 0; vi arr = i_vector(n); // input given array sortall(arr); int res = 1 ; for( int i = 0 ; i < n && arr[i] <= res ; i++ ) { res += arr[i ] ; } cout << res ;
 » 15 months ago, # |   0 for the Playlist question why it is getting AC for Map and TLE for Unordered_map.
•  » » 14 months ago, # ^ |   0 Bcs in worst case scenario map perform better than unordered_map .why this happens?. For this you need to know internal working of map.
•  » » » 14 months ago, # ^ |   0 Oh, now I get it. Thanks-
 » 14 months ago, # | ← Rev. 2 →   0 $O(n^2 \log n)$ solution for Sum of Four Values problem. Spoiler#include using namespace std; typedef long long ll; typedef vector vint; typedef vector vvint; typedef vector vbool; typedef vector vvbool; typedef pair pll; #define ff first #define ss second ll n, x; vint a; vector> twoSums; int main(){ cin >> n >> x; a.resize(n); for(int i = 0; i < n; i++){ cin >> a[i]; } for(int i = 0; i < n; i++){ for(int j = i + 1; j < n; j++) twoSums.push_back({a[i] + a[j], {i, j}}); } sort(twoSums.begin(), twoSums.end()); int l = 0, r = twoSums.size() - 1; while(l < r){ if(twoSums[l].ff + twoSums[r].ff < x){ l++; } else if(twoSums[l].ff + twoSums[r].ff > x){ r--; } else{ ll a = twoSums[l].ss.ff, b = twoSums[l].ss.ss, c = twoSums[r].ss.ff, d = twoSums[r].ss.ss; if(a == c or a == d or b == c or b == d){ if(l < r - 1 and twoSums[r - 1].ff == twoSums[r].ff) r--; else l++; } else{ cout << a + 1 << " " << b + 1 << " " << c + 1 << " " << d + 1; return 0; } } } cout << "IMPOSSIBLE"; return 0; } Explanation: We first find the sums which can be formed by two values in $x$ and store the sums in $twoSums$, in $O(n^2)$ time. Now, the problem boils down to "find if $x$ can be attainable using two values of $twoSums$ (note that these values must contain distinct indices)". So, we first sort the $twoSums$ array, which takes $O(n^2 \log n)$ time. And then, we run the two-pointer algo (takes $O(n^2)$ time) on $twoSums$ to check if $x$ is attainable using two values of $twoSums$.
 » 12 months ago, # | ← Rev. 3 →   0 I am having WA on Subarray Sums I. Could anyone please tell me what am I missing here?Code Link Thanks in advance
•  » » 12 months ago, # ^ | ← Rev. 2 →   0 Use long long for the currSum variable. The sum of the array values can go beyond INT_MAX.
•  » » » 12 months ago, # ^ |   0 Thanks Brother ...
 » 12 months ago, # |   0 Your solution of Subarray sum is very nice. I was using sliding window but your solution works for negative numbers too!
 » 10 months ago, # | ← Rev. 2 →   0 What exactly you did for creating ordered_multiset in 24th(Sliding Median) ? I created an ordered_set of pair {key,val} & stored some random number(but distinct) as val. Is there any better method to create ordered_multiset ? Btw, thanx for this blog!
•  » » 9 months ago, # ^ |   0 You need to change less to less_euqal Codetemplate using Multiset = tree, rb_tree_tag, tree_order_statistics_node_update>;
 » 8 months ago, # |   0 Thanks for the post. orz. Meme
•  » » 8 months ago, # ^ |   0
 » 8 months ago, # |   0 25th Sliding cost seems wrong, I am getting wrong O/P with your code for case: 10 5 4 6 10 4 3 8 8 10 8 9 Correct O/P: 9 11 11 11 7 3 Your O/P: 11 9 9 9 5 -1
 » 5 months ago, # |   0 THank YOu SO MUch...
 » 4 months ago, # |   0 How 18 — "Sum of 4 values" is working?, cause I think its complexity is n^3, and according to constraints that should not work. Can anyone explain?
•  » » 4 months ago, # ^ |   0 For the O(N^2) solution ,you can refer this Sum Of 4 Values
 » 7 weeks ago, # |   0 Thanks