This is a cpp page dedicated to general tips and code I’ve written in the past for CPP, helpful as a quick reference while coding
Basics
Types
//simply an integer
int num;
Printing
Simple printing
//Declare integer
n = 2;
// Print a string followed by the number
std::cout << "Before swapping: " << n << std::endl;
Printing all elements in a vector
Printing an array
String manipulation
This section shows the functions from the standard library to quickly manipulate string data
Code segment that converts string data to both upper and lowercase, also shows how to iterate through string variable quickly
#include <iostream>
#include <string>
#include <vector>
#include <functional>
//needed for std::less functions
std::string make_string_lower_case(std::string str)
{
//in this function, str[i] and chars are manipulated by their ASCII values
int len = abs(str.length());
for (int i = 0; i < len; i++)
{
if (str[i] >= 'A' && str[i] <= 'Z')
{
str[i] = str[i] + 32;
}
}
return str;
}
std::string make_string_upper_case(std::string str)
{
//in this function, str[i] and chars are manipulated by their ASCII values
int len = abs(str.length());
for (int i = 0; i < len; i++)
{
if (str[i] >= 'a' && str[i] <= 'z')
{
str[i] = str[i] - 32;
}
}
return str;
}
std::string make_lower_case_string_func(std::string str)
{
//in this function, str[i] and chars are manipulated by their ASCII values
int len = abs(str.length());
for (int i = 0; i < len; i++)
{
char c = std::tolower(str[i]);
str[i] = c;
}
return str;
}
std::string make_upper_case_string_func(std::string str)
{
//in this function, str[i] and chars are manipulated by their ASCII values
int len = abs(str.length());
for (int i = 0; i < len; i++)
{
char c = std::toupper(str[i]);
str[i] = c;
}
return str;
}
int find_substring(std::string str, std::string sub)
{
int len = abs(str.length());
int sub_len = abs(sub.length());
for (int i = 0; i < len; i++)
{
if (str[i] == sub[0])
{
for (int j = 1; j < sub_len; j++)
{
if (str[i + j] != sub[j])
{
break;
}
if (j == sub_len - 1)
{
//return index of first character of substring
return i;
}
}
}
}
return -1;
}
//find the index of multiple instances of a substring in a string
std::vector<int> find_substrings_multi(std::string str, std::string sub)
{
std::vector<int> indexes;
int len = abs(str.length());
int sub_len = abs(sub.length());
for (int i = 0; i < len; i++)
{
if (str[i] == sub[0])
{
for (int j = 1; j < sub_len; j++)
{
if (str[i + j] != sub[j])
{
break;
}
if (j == sub_len - 1)
{
indexes.push_back(i);
}
}
}
}
return indexes;
}
std::vector<std::string> split_string_by_char(std::string str, char c)
{
std::vector<std::string> split_vector;
std::string temp = "";
int len = abs(str.length());
for (int i = 0; i < len; i++)
{
if (str[i] == c)
{
split_vector.push_back(temp);
temp = "";
}
else
{
temp += str[i];
}
}
split_vector.push_back(temp);
return split_vector;
}
std::string trim_start_and_end(std::string str)
{
int len = abs(str.length());
int start = 0;
int end = len - 1;
while (str[start] == ' ')
{
start++;
}
while (str[end] == ' ')
{
end--;
}
return str.substr(start, end - start + 1);
}
int main()
{
//Section of code that switches strings from uppercase to lower case
std::cout << "## String manipulation basics:: Converting to LOWERCASE and UPPERCASE" << std::endl;
std::string str = "ThisISanINputString";
std::cout << make_string_lower_case(str) << std::endl;
std::cout << make_string_upper_case(str) << std::endl;
std::string lowercase_example = make_lower_case_string_func(str);
std::cout << "using to lower: " << lowercase_example << std::endl;
std::cout << "using to upper: " << make_upper_case_string_func(str) << std::endl;
std::cout << "## String manipulation basics:: Finding substrings" << std::endl;
//find a substring in a string, see above defined lowercase_example
std::string sub_target = "utst";
std::cout << "Finding the index of utst in thisisaninputstring: " << find_substring(lowercase_example, sub_target) << std::endl;
std::cout << "## String manipulation basics:: Erasing substrings" << std::endl;
//remove the substring from the string
int index = find_substring(lowercase_example, sub_target);
if (index != -1)
{
lowercase_example.erase(index, sub_target.length());
std::cout << "Example of erasing the substring from the lowercase example string: " << lowercase_example << std::endl;
}
//find multiple instances of a substring in a string
std::string main_multi_sub_search = "TheWizardIsInABlizzard";
std::string sub_multi_search = "iz";
std::vector<int> indexes = find_substrings_multi(main_multi_sub_search, sub_multi_search);
//print out the indexes of the substring
int len = indexes.size();
for (int i = 0; i < len; i++)
{
std::cout << "Index "<< i << " of substring: " << indexes[i] << std::endl;
}
//replace substring with another substring
std::cout << "## Replacing iz with ZZ in TheWizardIsInABlizzard..." << std::endl;
std::string replace_sub = "iz";
std::string replace_with = "ZZ";
std::string new_string = main_multi_sub_search;
for (int i = 0; i < len; i++)
{
new_string.replace(indexes[i], replace_sub.length(), replace_with);
}
std::cout << "original string: " << main_multi_sub_search << std::endl;
std::cout << "new string: " << new_string << std::endl;
std::cout << "## String manipulation basics:: Inserting substrings" << std::endl;
//insert a substring into a string
std::string insert_sub = "ZZ";
std::string insert_into = "TheWizardIsInABlizzard";
std::string new_insert_string = insert_into;
new_insert_string.insert(3, insert_sub);
std::cout << "original string: " << insert_into << std::endl;
std::cout << "new string: " << new_insert_string << std::endl;
std::cout << "## String manipulation basics:: Comparing Strings" << std::endl;
//compare two strings
std::string compare_str1 = "hello";
std::string compare_str2 = "hello";
std::string compare_str3 = "world";
//When using compare, it is generally understood that if the return value is 0, the strings are equal, other cases are not equal
std::cout << "Comparing hello and hello: " << compare_str1.compare(compare_str2) << std::endl;
std::cout << "Comparing hello and world: " << compare_str1.compare(compare_str3) << std::endl;
// Compare two strings using the < operator
std::cout << "Is 'hello' = 'hello'? " << (compare_str1 == compare_str2 ? "true" : "false") << std::endl;
std::cout << "Is 'hello' = 'world'? " << (compare_str1 == compare_str3 ? "true" : "false") << std::endl;
std::cout << "## String manipulation basics:: Concatinating Strings" << std::endl;
//concatenate two strings
std::string concat_str1 = "hello";
std::string concat_str2 = "world";
std::string concat_str3 = concat_str1 + " " + concat_str2;
std::cout << "Concatenated string: " << concat_str3 << std::endl;
std::cout << "## String manipulation basics:: Spliting string by characters" << std::endl;
//split a string by characters
std::string split_str = "Hello world I'm Kevin";
std::vector<std::string> split_vector = split_string_by_char(split_str, ' ');
len = split_vector.size();
for (int i = 0; i < len; i++)
{
std::cout << "Split string " << i << ": " << split_vector[i] << std::endl;
}
std::cout << "## String manipulation basics:: Trimming Whitespace of string" << std::endl;
//trim whitespace from a string
std::string trim_str = " Hello world I'm Kevin ";
return 0;
}
Code segment
Vector Manipulation
List manipulation
For Loops
Pointers, references, declarations and considerations
####
Simple Libraries and things to track
Byte Manipulation
Operations
Results
For loops
int SIZE = 5;
for(int i=0;i<SIZE;i++){
//do something for each iteration;
}
Bitwise Operations
int a = 5;
int b = 4;
int res_or = a|b;
int res_and = a&b;
Challenge 1: Coding a bit swapping algorithm for job prep in interview
Given 3 positives numbers a, b and c. Return the minimum flips required in some bits of a and b to make ( a OR b == c ). (bitwise OR operation). Flip operation consists of change any single bit 1 to 0 or change the bit 0 to 1 in their binary representation.
Input: a = 2, b = 6, c = 5 Output: 3 Explanation: After flips a = 1 , b = 4 , c = 5 such that (a OR b == c) Example 2:
Input: a = 4, b = 2, c = 7 Output: 1 Example 3:
Input: a = 1, b = 2, c = 3 Output: 0
The solution below shows how to iterate through binary sequences and update key information, will also need to be familiar with XOR and AND binary manipulation operations. It’s really just a simple for loop at the end of the day, just update binary key manipulation features.
class Solution {
public:
int minFlips(int a, int b, int c) {
int placehldr;
// checks or operation of a|b
placehldr = a|b;
std::cout << "Result of XOR a|b: " << placehldr << std::endl;
if((a|b)==c){
return 0;
}else{
int flip_number = 0;
while(a!=0 | b!=0 | c!=0){
placehldr = c&1;
std::cout << "Result of c&1: " << placehldr << std::endl;
// if the c value LSB is 1 (i.e. an odd number), basically an if statement to check the 1 coloumn of binary
if((c&1) == 1){
// if the LSB of a and b are both 0, we'll need to flip once
if((a&1) == 0 && (b&1) == 0){
flip_number++;
}
}else{
// since using or, if c LSB is equal to 0, both will need to be 0, hence we any bits equal to one
flip_number += (a&1)+(b&1);
}
//shuffle all bits to the right for updated
a >>= 1;
b >>= 1;
c >>= 1;
}
return flip_number;
}
}
};
Challenge 2: Binary tree BST to GST solution
Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.
As a reminder, a binary search tree is a tree that satisfies these constraints:
The left subtree of a node contains only nodes with keys less than the node’s key. The right subtree of a node contains only nodes with keys greater than the node’s key. Both the left and right subtrees must also be binary search trees
Input: root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8] Output: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8] Example 2:
Input: root = [0,null,1] Output: [1,null,1]
Constraints:
The number of nodes in the tree is in the range [1, 100]. 0 <= Node.val <= 100 All the values in the tree are unique
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int sum;
void recursive_update(TreeNode* root){
if(root->right != nullptr){
recursive_update(root->right);
}
sum += root->val;
root->val = sum;
if (root->left != nullptr){
recursive_update(root->left);
}
}
TreeNode* bstToGst(TreeNode* root) {
sum=0;
recursive_update(root);
return root;
}
};
Alternative Solution
class Solution {
public:
TreeNode* bstToGst(TreeNode* root) {
int acc_sum = 0;
sum_node(root,acc_sum);
return root;
}
void sum_node(TreeNode* node, int& acc_sum){
if (node == NULL) return;
sum_node(node->right,acc_sum);
node->val += acc_sum;
acc_sum = node->val;
sum_node(node->left, acc_sum);
}
};
An example of custom sorting parameters for a vector sorting algorithm
You are given four integers row, cols, rCenter, and cCenter. There is a rows x cols matrix and you are on the cell with the coordinates (rCenter, cCenter).
Return the coordinates of all cells in the matrix, sorted by their distance from (rCenter, cCenter) from the smallest distance to the largest distance. You may return the answer in any order that satisfies this condition.
The distance between two cells (r1, c1) and (r2, c2) is | r1 - r2 | + | c1 - c2 | . |
Example 1:
Input: rows = 1, cols = 2, rCenter = 0, cCenter = 0 Output: [[0,0],[0,1]] Explanation: The distances from (0, 0) to other cells are: [0,1] Example 2:
Input: rows = 2, cols = 2, rCenter = 0, cCenter = 1 Output: [[0,1],[0,0],[1,1],[1,0]] Explanation: The distances from (0, 1) to other cells are: [0,1,1,2] The answer [[0,1],[1,1],[0,0],[1,0]] would also be accepted as correct. Example 3:
Input: rows = 2, cols = 3, rCenter = 1, cCenter = 2 Output: [[1,2],[0,2],[1,1],[0,1],[1,0],[0,0]] Explanation: The distances from (1, 2) to other cells are: [0,1,1,2,2,3] There are other answers that would also be accepted as correct, such as [[1,2],[1,1],[0,2],[1,0],[0,1],[0,0]].
class Solution {
public:
vector<vector<int>> allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) {
vector<vector<int>> ans;
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
ans.push_back({r, c});
}
}
sort(ans.begin(), ans.end(), DistFromCenterSorter(rCenter, cCenter));
return ans;
}
private:
struct DistFromCenterSorter {
int rCenter;
int cCenter;
DistFromCenterSorter(int rCenter, int cCenter) {
this->rCenter = rCenter;
this->cCenter = cCenter;
}
bool operator()(const vector<int>& cell1, const vector<int>& cell2) {
return distFromCenter(cell1) < distFromCenter(cell2);
}
int distFromCenter(const vector<int>& cell) {
return abs(cell[0] - this->rCenter) + abs(cell[1] - this->cCenter);
}
};
};
You really need to start paying attention muthafucker
class Solution {
public:
vector<vector<int>> allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) {
vector<vector<int>> matrix_data;
vector<int> array_ref;
int count_ = 0;
int dist;
for(int r_=0;r_<rows;r_++){
for(int c_=0;c_<cols;c_++){
dist = abs(r_ - rCenter) + abs(c_ - cCenter);
if (array_ref.size()==0)//infers the matrix data is also empty
{
array_ref.push_back(dist);
matrix_data.push_back({r_,c_});
}else{
int index = std::distance(array_ref.begin(), lower_bound(array_ref.begin(), array_ref.end(), dist));
array_ref.insert(array_ref.begin()+index,dist);
matrix_data.insert(matrix_data.begin()+index, {r_,c_});
}
}
}
return matrix_data;
}
};
Traversal Binary Tree
Given the root of a binary search tree, return a balanced binary search tree with the same node values. If there is more than one answer, return any of them.
A binary search tree is balanced if the depth of the two subtrees of every node never differs by more than 1.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void traverse_tree(TreeNode* node, vector<int>& sv_){
if(node!=nullptr){
traverse_tree(node->right,sv_);
traverse_tree(node->left,sv_);
sv_.push_back(node->val);
}
}
void buildBST_from_values(TreeNode* root, vector<int> sorted_values){
if (sorted_values.size()==1){
root->val = sorted_values[0];
return;
}
int mid_index = std::distance(sorted_values.begin(), sorted_values.begin() + sorted_values.size() / 2);
root->val = sorted_values[mid_index];
std::vector<int> left_vector_branch(sorted_values.begin(), sorted_values.begin() + mid_index);
if (!left_vector_branch.empty()) {
root->left = new TreeNode();
buildBST_from_values(root->left,left_vector_branch);
}
std::vector<int> right_vector_branch(sorted_values.begin() + mid_index+1, sorted_values.end());
if (!right_vector_branch.empty()) {
// The vector is empty
root->right = new TreeNode();
buildBST_from_values(root->right,right_vector_branch);
}
std::cout << "iteration run" << std::endl;
return;
}
TreeNode* balanceBST(TreeNode* root) {
vector<int> sorted_values;
traverse_tree(root,sorted_values);
sort(sorted_values.begin(), sorted_values.end());
TreeNode* new_tree = new TreeNode();
buildBST_from_values(new_tree, sorted_values);
return new_tree;
}
};
Finding the longest substring in a string with no repeating characterisitics
class Solution {
public:
int lengthOfLongestSubstring(string s) {
//find all unique characters in a string
int max_unique_len = 1;
const char* char_arr = s.c_str();
int string_len = s.length();
int comparison_len;
vector<char> insubstring;
//let's do it the simple way first
for(int i1=0;i1<string_len-1;i1++){
comparison_len=1;
insubstring.clear();
insubstring.push_back(char_arr[i1]);
for (int i2=i1+1;i2<string_len;i2++){
// if(char_arr[i1]!=char_arr[i2]){
if(find(insubstring.begin(), insubstring.end(), char_arr[i2]) == insubstring.end()){
comparison_len+=1;
insubstring.push_back(char_arr[i2]);
}else{
break;
}
if (comparison_len>max_unique_len){
max_unique_len=comparison_len;
}
}
}
return max_unique_len;
}
};
List reversal and investigation
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
void recursive_get_num(ListNode* node, string& sv_){
if(node!=nullptr){
recursive_get_num(node->next,sv_);
string s = to_string(node->val);
sv_.append(s);
}
}
ListNode* recursive_assign_int_to_nodelist(ListNode* node, string& parser){
//take the last number of integer while removing it from the value
if(!parser.empty()){
string lastchar{parser.back()};
int value_for_node = stoi(lastchar);
parser.pop_back();
node->val = value_for_node;
if(parser.find_first_not_of('\0') != std::string::npos){
node->next = new ListNode();
recursive_assign_int_to_nodelist(node->next,parser);
}
}
return node;
}
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
auto ret_val = new ListNode();
string num1;
string num2;
recursive_get_num(l1, num1);
recursive_get_num(l2, num2);
int value1 = stoi(num1);
int value2 = stoi(num2);
int sum_ = value1 + value2;
string sum = to_string(sum_);
std::cout << sum << std::endl;
ret_val = recursive_assign_int_to_nodelist(ret_val,sum);
return ret_val;
}
};
Challenge: Find line on point in data structure
class Solution {
public:
int maxPoints(vector<vector<int>>& points) {
vector<LineInfo> lines;
int number_of_points;
int p1x, p2x, p1y, p2y;
// for(int 0=0;0<number_of_points;0++){
while (!points.empty()){
number_of_points = points.size();
for(int i2=1;i2<number_of_points;i2++){
//if the points are not the same index
if(0!=i2){
//calculate gradient between the points
p1x = points[0][0];
p2x = points[i2][0];
p1y = points[0][1];
p2y = points[i2][1];
std::cout << "comparing {" << p1x << ", " << p1y << "}, {" << p2x << ", " << p2y << "}";
//rise p2y - p1y ==/run == p2x - p1x
double rise = p2y - p1y;
double run = p2x - p1x;
double b_=0;
double X_=0;
double Y_=0;
double gradient = 0;
string _type = "N";
if(run==0){
//this is unique line case in which y = const
X_ = p1x;
_type = "x";
std::cout << " A vertical straight line along X axis: " << X_ << std::endl;
}else if (rise==0){
//this is unique line case in which x = const
Y_ = p1y;
_type = "y";
std::cout << " A horizonal straight line along Y axis: " << Y_ << std::endl;
}else{
gradient = rise/run;
//y = mx + b, therefore b = y-mx
b_ = p2y-(gradient*p2x);
_type = "d";
std::cout << " With a gradient of " << gradient << " and a b value: " << b_ << std::endl;
}
update_line_vector_counter(lines, gradient, b_, X_, Y_, _type, points[i2]);
}
}
//remove the first element of the vector
points.erase(points.begin());
}
//return maximum value in array
//sort the lines in ascending order of count size
std::sort(lines.begin(), lines.end(), LineInfoCountSorter());
return lines[0].points_on_line.size()+1;
}
private:
struct LineInfo {
double gradient;
double b; // y-intercept
int count;
double x_; // Used only for vertical lines
double y_; // Used only for horizontal lines
string type; //
vector<vector<int>> points_on_line;
// Constructor for lines with a gradient and y-intercept
LineInfo(double gradient, double b, int count = 1) : gradient(gradient), b(b), count(count), x_(0), y_(0), type("d") {}
// Constructor for vertical lines (x = constant)
LineInfo(double x, int count = 1) : gradient(0), b(0), count(count), x_(x), y_(0), type("x") {}
// Constructor for horizontal lines (y = constant)
LineInfo(double y, bool isHorizontal, int count = 1) : gradient(0), b(0), count(count), x_(0), y_(y), type("y") {}
};
struct LineInfoCountSorter {
bool operator()(const LineInfo& line1, const LineInfo& line2) {
// return line1.count < line2.count; // Sort in ascending order of count
return line1.points_on_line.size() > line2.points_on_line.size();// Use > for descending order
}
};
/*Type is then line type, i.e. diagonal ('d'), x const ('x'), or y const ('y')*/
void update_line_vector_counter(std::vector<LineInfo>& lines, double grad, double b, double x, double y, string type, vector<int> point){
if(type != "x" && type != "y" && type != "d"){
throw std::invalid_argument( "Invalid line type parsed: " + type);
}
bool invector = false;
for (auto& line : lines) {
if (
(type=="d" && line.type == type && line.gradient == grad && line.b == b)
|| (type=="x" && line.type == type && line.x_ == x)
|| (type=="y" && line.type == type && line.y_ == y)
) {
bool invec = (find(line.points_on_line.begin(), line.points_on_line.end(), point) == line.points_on_line.end());
if (invec){
line.points_on_line.push_back(point);
}
line.count+=1;
invector = true;
break;
}
}
if(!invector){
if (type=="d"){
LineInfo newline(grad,b);
newline.points_on_line.push_back(point);
lines.push_back(newline);
} else
if (type=="x"){
LineInfo newline(x);
newline.points_on_line.push_back(point);
lines.push_back(newline);
} else
if (type=="y"){
LineInfo newline(y,true);
newline.points_on_line.push_back(point);
lines.push_back(newline);
} else{
throw std::invalid_argument( "Invalid line type parsed: " + type);
}
}
}
};
#include <iostream>
#include <vector>
using namespace std;
std::vector<std::string> unique_names(const std::vector<std::string>& names1, const std::vector<std::string>& names2)
{
std::vector<std::string> ret_val;
ret_val.insert(ret_val.end(),names2.begin(),names2.end());
ret_val.insert(ret_val.end(),names1.begin(),names1.end());
std::sort(ret_val.begin(),ret_val.end());
auto it = std::unique(ret_val.begin(),ret_val.end());
ret_val.erase(it, ret_val.end());
return ret_val;
//
//names1.erase(it,names1.end());
//throw std::logic_error("Waiting to be implemented");
//return names1;
}
#ifndef RunTests
int main()
{
std::vector<std::string> names1 = {"Ava", "Emma", "Olivia"};
std::vector<std::string> names2 = {"Olivia", "Sophia", "Emma"};
std::vector<std::string> result = unique_names(names1, names2);
for(auto element : result)
{
std::cout << element << ' '; // should print Ava Emma Olivia Sophia
}
}
#endif