Skip to content

Commit

Permalink
Check if There is a Valid Partition For The Array
Browse files Browse the repository at this point in the history
  • Loading branch information
hikjik committed Sep 5, 2023
1 parent 608ce74 commit 058578f
Show file tree
Hide file tree
Showing 4 changed files with 92 additions and 0 deletions.
1 change: 1 addition & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ add_task(check-if-array-is-sorted-and-rotated)
add_task(check-if-it-is-a-straight-line)
add_task(check-if-n-and-its-double-exist)
add_task(check-if-one-string-swap-can-make-strings-equal)
add_task(check-if-there-is-a-valid-partition-for-the-array)
add_task(checking-existence-of-edge-length-limited-paths)
add_task(cherry-pickup)
add_task(cherry-pickup-ii)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
add_catch(test_check_if_there_is_a_valid_partition_for_the_array test.cpp)
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
#pragma once

#include <vector>

class Solution {
public:
bool validPartition(const std::vector<int> &nums) {
const int n = nums.size();
switch (n) {
case 1:
return false;
case 2:
return valid2(0, nums);
case 3:
return valid3(0, nums);
}

auto a = false;
auto b = valid2(n - 2, nums);
auto c = valid3(n - 3, nums);

for (int i = n - 4; i >= 0; --i) {
const auto d = valid2(i, nums) & b | valid3(i, nums) & a;
a = b, b = c, c = d;
}

return c;
}

private:
bool valid2(int i, const std::vector<int> &nums) {
return nums[i] == nums[i + 1];
}

bool valid3(int i, const std::vector<int> &nums) {
return nums[i] == nums[i + 1] && nums[i] == nums[i + 2] ||
nums[i] == nums[i + 1] - 1 && nums[i] == nums[i + 2] - 2;
}
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
#include <catch.hpp>

#include <solution.hpp>

TEST_CASE("Simple") {
{
std::vector<int> nums{4, 4, 4, 5, 6};
REQUIRE(Solution().validPartition(nums));
}
{
std::vector<int> nums{4, 4, 4, 10, 10, 1, 2, 3, 9, 9};
REQUIRE(Solution().validPartition(nums));
}
{
std::vector<int> nums{4, 4, 4, 10, 10, 1, 2, 3, 50, 9, 9};
REQUIRE_FALSE(Solution().validPartition(nums));
}
{
std::vector<int> nums{1, 1, 1, 2};
REQUIRE_FALSE(Solution().validPartition(nums));
}
{
std::vector<int> nums{1, 2};
REQUIRE_FALSE(Solution().validPartition(nums));
}
{
std::vector<int> nums{1};
REQUIRE_FALSE(Solution().validPartition(nums));
}
{
std::vector<int> nums{1, 1};
REQUIRE(Solution().validPartition(nums));
}
{
std::vector<int> nums{1, 2, 3};
REQUIRE(Solution().validPartition(nums));
}
{
std::vector<int> nums{1, 1, 1};
REQUIRE(Solution().validPartition(nums));
}
{
std::vector<int> nums{1, 1, 2};
REQUIRE_FALSE(Solution().validPartition(nums));
}
{
std::vector<int> nums{993335, 993336, 993337, 993338,
993339, 993340, 993341};
REQUIRE_FALSE(Solution().validPartition(nums));
}
}

0 comments on commit 058578f

Please sign in to comment.