Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Leetcode #34

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions leetcode/1367.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
#include <memory>
#include <stdexcept>

struct list_node {
int val;
list_node *next;
list_node(int x) : val(x), next(nullptr) {}
list_node(int x, list_node *next) : val(x), next(next) {}
};

struct tree_node {
int val;
tree_node *left;
tree_node *right;
tree_node(int x) : val(x), left(nullptr), right(nullptr) {}
tree_node(int x, tree_node *left, tree_node *right) : val(x), left(left), right(right) {}
};

bool is_subpath_impl(list_node*, tree_node*);
bool is_subpath(list_node* head, tree_node* root) {
if (!root) return false;
return is_subpath_impl(head, root) or is_subpath(head, root->left) or is_subpath(head, root->right);
}
bool is_subpath_impl(list_node* listNode, tree_node* treeNode) {
if (!listNode) return true;
if (!treeNode) return false;
if (listNode->val != treeNode->val) return false;
return is_subpath_impl(listNode->next, treeNode->right) or is_subpath_impl(listNode->next, treeNode->left);
}

using std::unique_ptr;
using std::make_unique;

int main() {
unique_ptr<list_node> ln0 = make_unique<list_node>(1);
unique_ptr<list_node> ln1 = make_unique<list_node>(2, ln0.get());
unique_ptr<list_node> list = make_unique<list_node>(2, ln1.get());

unique_ptr<tree_node> leaf = make_unique<tree_node>(1);
unique_ptr<tree_node> l1 = make_unique<tree_node>(2, leaf.get(), nullptr);
unique_ptr<tree_node> l2 = make_unique<tree_node>(2, nullptr, l1.get());
unique_ptr<tree_node> tree = make_unique<tree_node>(2, l2.get(), nullptr);

if (!is_subpath(list.get(), tree.get())) throw std::domain_error("Test failed.");
}
84 changes: 84 additions & 0 deletions leetcode/1367.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ListNode {
pub val: i32,
pub next: Option<Box<ListNode>>
}

impl ListNode {
#[inline]
fn new(val: i32) -> Self {
ListNode {
next: None,
val
}
}
}

#[derive(Debug, Eq, PartialEq)]
pub struct TreeNode {
pub val: i32,
pub left: Option<Rc<RefCell<TreeNode>>>,
pub right: Option<Rc<RefCell<TreeNode>>>,
}

impl TreeNode {
#[inline]
pub fn new(val: i32, left: Option<Rc<RefCell<TreeNode>>>, right: Option<Rc<RefCell<TreeNode>>>) -> Self {
TreeNode {
val,
left,
right
}
}
}

use std::rc::Rc;
use std::cell::RefCell;

pub fn is_sub_path(head: Option<Box<ListNode>>, root: Option<Rc<RefCell<TreeNode>>>) -> bool {
is_sub_path_internal(head.as_ref(), root.as_ref())
}

fn is_sub_path_internal(head: Option<&Box<ListNode>>, root: Option<&Rc<RefCell<TreeNode>>>) -> bool {
if root.is_none() {
return false;
}

let root_ref = root.unwrap().borrow();

is_sub_path_impl(head, root) ||
is_sub_path_internal(head, root_ref.left.as_ref()) ||
is_sub_path_internal(head, root_ref.right.as_ref())
}

fn is_sub_path_impl(list_node: Option<&Box<ListNode>>, tree_node: Option<&Rc<RefCell<TreeNode>>>) -> bool {
if list_node.is_none() {
return true;
}
if tree_node.is_none() {
return false;
}

let list_node = list_node.unwrap();
let tree_node_ref = tree_node.unwrap().borrow();

if list_node.val == tree_node_ref.val {
is_sub_path_impl(list_node.next.as_ref(), tree_node_ref.left.as_ref()) ||
is_sub_path_impl(list_node.next.as_ref(), tree_node_ref.right.as_ref())
} else {
false
}
}

fn main() {
let mut list = ListNode::new(2);
list.next = Some(Box::new(ListNode::new(2)));
list.next.as_mut().unwrap().next = Some(Box::new(ListNode::new(1)));

let leaf = TreeNode::new(1, None, None);
let l1 = TreeNode::new(2, Some(Rc::new(RefCell::new(leaf))), None);
let l2 = TreeNode::new(2, None, Some(Rc::new(RefCell::new(l1))));
let tree = TreeNode::new(2, Some(Rc::new(RefCell::new(l2))), None);

assert!(is_sub_path(Some(Box::new(list)), Some(Rc::new(RefCell::new(tree)))))
}
27 changes: 27 additions & 0 deletions leetcode/2044.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
#include <cmath>
#include <unordered_map>
#include <vector>

using std::max;

int
solve(std::vector<int> const& nums, int& curMax, std::unordered_map<int ,int>& freqs,
int const curOr = 0, std::vector<int>::size_type const i = 0)
{
freqs[curOr]++;
curMax = max(curMax, curOr);
if (i == nums.size()) return curMax;
for (vector<int>::size_type j = i; j < nums.size(); j++)
curMax = max(curMax, solve(nums, curMax, freqs, curOr | nums[j], j + 1));
return curMax;
}

int
countMaxOrSubsets(vector<int>& nums)
{
std::unordered_map<int, int> freqs;
int curMax = 0;
return freqs[solve(nums, curMax, freqs)];
}

int main() {}
90 changes: 90 additions & 0 deletions leetcode/3043.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
#include <algorithm>
#include <vector>

#include <gtest/gtest.h>

using std::vector;

struct node {
node* next[10] = {};
};

int count_digits(int i) {
int ans = 0;
while (i > 0) {
i /= 10;
ans++;
}
return ans;
}

static int p10s[] = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000};

node arr2tree(vector<int> const& arr) {
node root;
for (const int a : arr) {
node* node_ptr = &root;
const int n = count_digits(a);
for (int i = 0; i < n; i++) {
const int d = (a / p10s[n - i - 1]) % 10;
if (!node_ptr->next[d]) node_ptr->next[d] = new node();
node_ptr = node_ptr->next[d];
}
}
return root;
}

int f(node root, int a) {
const int n = count_digits(a);
node* node_ptr = &root;
int ans = 0;
for (int i = 0; i < n; i++) {
const int d = (a / p10s[n - i - 1]) % 10;
if (!node_ptr->next[d]) return ans;
ans++;
node_ptr = node_ptr->next[d];
}
return ans;
}

void free(node* node_ptr) {
for (int i = 0; i < 10; i++) if (node_ptr->next[i]) free(node_ptr->next[i]);
delete node_ptr;
}

void free(node root) {
vector<node*> nodes;
for (int i = 0; i < 10; i++) if (root.next[i]) free(root.next[i]);
}

int longest_common_prefix(vector<int> const& arr1, vector<int> const& arr2) {
node root = arr2tree(arr1);
int ans = 0;
for (const int a : arr2) ans = std::max(ans, f(root, a));
free(root);
return ans;
}

TEST(longest_common_prefix, warming_up) {
const vector<int> arr1{1, 10, 100};
const vector<int> arr2{1000};
EXPECT_EQ(longest_common_prefix(arr1, arr2), 3); }

TEST(longest_common_prefix, four) {
const vector<int> arr1{10987654, 123, 87654321, 654321};
const vector<int> arr2{109876, 1234567, 87654321, 654};
EXPECT_EQ(longest_common_prefix(arr1, arr2), 8); }

TEST(longest_common_prefix, five) {
const vector<int> arr1{123987, 567890, 234567, 890123, 456789};
const vector<int> arr2{908123, 456123, 789012, 234567};
EXPECT_EQ(longest_common_prefix(arr1, arr2), 6); }

TEST(longest_common_prefix, six) {
const vector<int> arr1{1248,364524,73264823,2937935};
const vector<int> arr2{73249,94895,656324,239583,1249};
EXPECT_EQ(longest_common_prefix(arr1, arr2), 3); }

int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS(); }
86 changes: 86 additions & 0 deletions leetcode/592.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
#include <cstdlib>
#include <numeric>
#include <string>
#include <string_view>
#include <tuple>
#include <utility>
#include <vector>

#include <gtest/gtest.h>

using std::make_pair;
using std::pair;
using std::string_view;

struct fraction {
constexpr fraction() : den(0), num(0), neg(false) {}
int den;
int num;
bool neg;
};

constexpr auto parse_number(string_view expr, const size_t i) -> pair<int, size_t> {
if (expr[i] == '1')
return i < expr.length() - 1 and expr[i + 1] == '0' ? make_pair(10, i + 2) : make_pair( 1, i + 1);
else
return {expr[i] - '0', i + 1};
}

constexpr auto parse_fraction(string_view expression, const size_t i = 0) -> pair<fraction, size_t> {
fraction f;
size_t j = i;
if (expression[j] == '+' or expression[j] == '-') {
f.neg = expression[j] == '-';
j++;
}
std::tie(f.num, j) = parse_number(expression, j);
j++;
std::tie(f.den, j) = parse_number(expression, j);
return {f, j};
}

constexpr auto reduce(const std::vector<fraction>& fs) -> fraction {
fraction result;
int prod = 1;
for (const fraction& f : fs)
prod *= f.den;
result.den = prod;
for (const fraction& f : fs)
result.num += (f.neg ? -1 : 1) * f.num * (prod / f.den);
const int gcd = std::gcd(result.num, result.den);
result.num /= gcd;
result.den /= gcd;
if (result.num < 0) {
result.num *= -1;
result.neg = true;
}
return result;
}

constexpr auto fraction_addition(std::string expression) -> std::string {
std::vector<fraction> fractions;
auto [f, i] = parse_fraction(expression);
fractions.push_back(f);
while (i < expression.length()) {
std::tie(f, i) = parse_fraction(expression, i);
fractions.push_back(f);
}
const fraction result = reduce(fractions);
return (result.neg ? "-" : "") + std::to_string(result.num) + "/" + std::to_string(result.den);
}

// try with <charconv>'s to_chars instead
//using namespace std::literals;
//static_assert(fraction_addition("-1/2+1/2") == "0/1");


TEST(FractionAddition, a) { EXPECT_EQ(fraction_addition("-1/2+1/2"), "0/1"); }
TEST(FractionAddition, b) { EXPECT_EQ(fraction_addition("-1/2+1/2+1/3"), "1/3"); }
TEST(FractionAddition, c) { EXPECT_EQ(fraction_addition(" 1/3-1/2"), "-1/6"); }

TEST(FractionAddition, d__expression_with_a_10) { EXPECT_EQ(fraction_addition("-5/2+10/3+7/9"), "29/18"); }

int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
54 changes: 54 additions & 0 deletions leetcode/650.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
#include <exception>
#include <iostream>
#include <string>
#include <tuple>
#include <queue>
#include <unordered_set>

struct hash {
std::size_t operator()(const std::tuple<int, int, int> &t) const {
auto h0 = std::hash<int>{}(std::get<0>(t));
auto h1 = std::hash<int>{}(std::get<1>(t));
auto h2 = std::hash<int>{}(std::get<2>(t));
return h0 ^ h1 ^ h2;
}
};

int min_steps(int n) {
std::queue<std::tuple<int, int, int>> Q;
Q.emplace(1, 0, 0);
std::unordered_set<std::tuple<int, int, int>, hash> Qed;
Qed.emplace(1, 0, 0);
while (!Q.empty()) {
const auto [a, b, c] = Q.front();
std::cout << ">> " << a << ' ' << b << ' ' << c << std::endl;
if (a == n) return c;
if (a > n) {
Q.pop();
continue;
}
if (b != a && !Qed.contains({a, a, c + 1})) {
Qed.emplace(a, a, c + 1);
Q.emplace(a, a, c + 1);
}
if (b != 0 && (a + b <= n) && !Qed.contains({a + b, b, c + 1})) {
Qed.emplace(a + b, b, c + 1);
Q.emplace(a + b, b, c + 1);
}
Q.pop();
}
return -1;
}

int main(int argc, char** argv) {
const int n = (argc <= 1 ? 10 : [argv](){
try {
const int x = std::stoi(argv[1]);
if (x < 1) throw std::exception{};
return x;
} catch (...) {
std::cerr << "Optional input argument must be an integer greater than zero.\n";
std::exit(1);
}}());
std::cout << min_steps(n) << '\n';
}
Loading
Loading