
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Split List in C++
Suppose we have a list of integers called nums, we have to find whether we can partition the list into two sublists (non-empty) such that every number in the left part is strictly less than every number in the right part.
So, if the input is like [6,4,3,8,10], then the output will be true, as left = [6,4,3] and right = [8,10]
To solve this, we will follow these steps −
n := size of nums
Define an array right of size n
Define an array left of size n
left[0] := nums[0]
last element of right := last element of nums
-
for initialize i := 1, when i < n, update (increase i by 1), do −
left[i] := maximum of left[i - 1] and nums[i]
-
for initialize i := n - 2, when i >= 0, update (decrease i by 1), do −
right[i] := minimum of right[i + 1] and nums[i]
-
for initialize i := 0, when i < n - 1, update (increase i by 1), do −
-
if left[i] < right[i + 1], then −
return true
-
return false
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h> using namespace std; class Solution { public: bool solve(vector<int> &nums) { int n = nums.size(); vector<int> right(n); vector<int> left(n); left[0] = nums[0]; right.back() = nums.back(); for (int i = 1; i < n; i++) { left[i] = max(left[i - 1], nums[i]); } for (int i = n - 2; i >= 0; i--) { right[i] = min(right[i + 1], nums[i]); } for (int i = 0; i < n - 1; i++) { if (left[i] < right[i + 1]) return true; } return false; } }; main() { Solution ob; vector<int> v = {6,4,3,8,10}; cout << (ob.solve(v)); }
Input
{6,4,3,8,10}
Output
1