Skip to main content

Posts

Showing posts from March, 2020

Leet Code Problem #537. Complex Number Multiplication

Given two strings representing two complex numbers . You need to return a string representing their multiplication. Note i 2 = -1 according to the definition. Example 1: Input: "1+1i", "1+1i" Output: "0+2i" Explanation: (1 + i) * (1 + i) = 1 + i 2 + 2 * i = 2i,  and you need convert it to the form of 0+2i.   Solution in C++:     string complexNumberMultiply(string a, string b) {         int a1 = 0;         int a2 = 0;         int b1 = 0;         int b2 = 0;         string ret;         cal(a, a1, a2);         cal(b, b1, b2);         int real = a1 * b1 - a2 * b2;         int imag = a1 * b2 + a2 * b1;      ...

Most frequently asked interview question #15 with solution

A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules: For 1-byte character, the first bit is a 0, followed by its unicode code. For n-bytes character, the first n-bits are all one's, the n+1 bit is 0, followed by n-1 bytes with most significant 2 bits being 10. This is how the UTF-8 encoding would work: Char. number range | UTF-8 octet sequence (hexadecimal) | (binary) --------------------+--------------------------------------------- 0000 0000-0000 007F | 0xxxxxxx 0000 0080-0000 07FF | 110xxxxx 10xxxxxx 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx Given an array of integers representing the data, return whether it is a valid utf-8 encoding. Note: The input is an array of integers. Only the least significant 8 bits of each integer is used to store the data. This means each integer represents only 1 byte of data. Example 1: dat...

Most frequently asked interview question #14 with solution

Note: This is a companion problem to the System Design problem: Design TinyURL . TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk . Design the encode and decode methods for the TinyURL service. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL. Solution in C++: class Solution { public:     map<string, string> url;         // Encodes a URL to a shortened URL.     string encode(string longUrl) {         static int count = 0;         char *a = (char*)calloc(sizeof(char), 30);         ++count;         spr...

Most frequently asked interview question #13 with solution

Given the root node of a binary search tree, return the sum of values of all nodes with value between L and R (inclusive). The binary search tree is guaranteed to have unique values. Example 1: Input: root = [10,5,15,3,7,null,18] , L = 7 , R = 15 Output: 32     Solution in C++: /**  * Definition for a binary tree node.  * struct TreeNode {  *     int val;  *     TreeNode *left;  *     TreeNode *right;  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}  * };  */     int rangeSumBST(TreeNode* root, int L, int R) {             int sum = 0;         return cal_sum(root, L, R, sum);     }     int cal_sum (TreeNode* root, int L, int R, int &sum){         if(...

Most frequently asked interview question #12 with solution

Balanced  strings are those who have an equal quantity of 'L' and 'R' characters. Given a balanced string  s  split it in the maximum amount of balanced strings. Return the maximum amount of split balanced strings. Balanced  strings are those who have an equal quantity of 'L' and 'R' characters. Given a balanced string  s  split it in the maximum amount of balanced strings. Return the maximum amount of split balanced strings. Input: s = "RLRRLLRLRL" Output: 4 Solution in C++:     int balancedStringSplit(string s) {             int ret = 0;             int r_c = 0;             int l_c = 0;         for(int iter = 0; iter < s.length(); ++iter){               ...

Most frequently asked interview question #11 with solution

Given two arrays of integers  nums and index . Your task is to create target array under the following rules: Initially target array is empty. From left to right read nums[i] and index[i], insert at index index[i]  the value nums[i]  in  target array. Repeat the previous step until there are no elements to read in nums and index. Return the target array. It is guaranteed that the insertion operations will be valid. Input: nums = [0,1,2,3,4], index = [0,1,2,2,1] Output: [0,4,1,3,2] Explanation: nums index target 0 0 [0] 1 1 [0,1] 2 2 [0,1,2] 3 2 [0,1,3,2] 4 1 [0,4,1,3,2]   Solution in C++:   vector<int> createTargetArray(vector<int>& nums, vector<int>& index) { int *a = nullptr; int size = nums.size(); a = (int*)calloc(sizeof(int), size); a[0] = nums.at(0); ...

Most frequently asked interview question #10 with solution

We are given a list nums of integers representing a list compressed with run-length encoding. Consider each adjacent pair of elements [freq, val] = [nums[2*i], nums[2*i+1]]  (with i >= 0 ).  For each such pair, there are freq elements with value val concatenated in a sublist. Concatenate all the sublists from left to right to generate the decompressed list. Return the decompressed list. Input: nums = [1,2,3,4] Output: [2,4,4,4]   Solution in C++:   vector<int> decompressRLElist(vector<int>& nums) { vector<int> ret; for(int iter = 0; iter < nums.size();){ int i = 0; while(i < nums.at(iter)){ ++i; ret.push_back(nums.at(iter + 1)); } iter += 2; } return ret; }

Most frequently asked interview question #9 with solution

Given an integer number n , return the difference between the product of its digits and the sum of its digits. Example: n = 234 output = 15 which is ((2*3*4) - (2+3+4)) Solution in C++:     int subtractProductAndSum(int n) {             int sum = 0;             int prd = 0;             int tmp = 0;             bool is_first = true;         while(n != 0){             tmp = n % 10;             n   = n / 10;             sum += tmp;             if(is_first){    ...

Most frequently asked interview question #8 with solution

You're given strings J representing the types of stones that are jewels, and S representing the stones you have.  Each character in S is a type of stone you have.  You want to know how many of the stones you have are also jewels. The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive, so "a" is considered a different type of stone from "A" . Example 1: Input: J = "aA", S = "aAAbbbb" Output: 3    Solution in C++:   int numJewelsInStones(string J, string S) { int count[256] = {0}; int sol = 0; int iter = 0; for (iter = 0; iter < S.length(); ++iter){ ++count[S[iter]]; } for(iter = 0; iter < J.length(); ++iter){ sol += count[J[iter]]; } return sol; }  

Most frequently asked interview question #7 with solution

Given the array nums , for each nums[i] find out how many numbers in the array are smaller than it. That is, for each nums[i] you have to count the number of valid j's  such that  j != i and nums[j] < nums[i] . Return the answer in an array. Input: nums = [8,1,2,2,3] Output: [4,0,1,1,3] Solution in C++:     vector<int> smallerNumbersThanCurrent(vector<int>& nums) {                 int count[101] = {0};         int vect_size  = nums.size();                 for(int iter = 0; iter < vect_size; ++iter){                         ++count[nums.at(iter)];         }        ...

Most frequently asked interview question #6 with solution

Longest palindrome substring Solution in C++:     string longestPalindrome(string s) {             int low = 0;             int high = 0;             int start = 0;             int max   = 1;             int len   = s.length();         for(int iter = 1; iter < len; ++iter){                         //If the palindrome string is of type even aabbaa             low = iter - 1;             high = iter;   ...

Most frequently asked interview question #5 with solution

Given n non-negative integers a 1 , a 2 , ..., a n  , where each represents a point at coordinate ( i , a i ). n vertical lines are drawn such that the two endpoints of line i is at ( i , a i ) and ( i , 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water. Note:  You may not slant the container and n is at least 2. The above vertical lines are represented by array [4,8,4,5,6,4]. In this case, the max area of water (blue section) the container can contain is 48. Solution in C++:     int maxArea(vector<int>& height) {                     int max_area = 0;             int it   = 0;             int it_r = height.size() - 1;        ...

Most frequently asked interview question #4 with solution

Given a fixed length array arr of integers, duplicate each occurrence of zero, shifting the remaining elements to the right. Note that elements beyond the length of the original array are not written. Do the above modifications to the input array in place , do not return anything from your function. Solution in C++:     void duplicateZeros(vector<int>& arr) {                 int i = 0;                 int iter = 0;         //Calculating the index before which array get terminated             for(iter = 0; iter < arr.size(); ++i){                             //Case: If the digit is zero...

Most frequently asked interview question #3 with solution

We are given that the string "abc" is valid. From any valid string V , we may split  V into two pieces X and Y such that X + Y ( X concatenated with Y ) is equal to V .  ( X or Y may be empty.)  Then, X + "abc" + Y is also valid. If for example S = "abc" , then examples of valid strings are: "abc", "aabcbc", "abcabc", "abcabcababcc" .  Examples of invalid  strings are: "abccba" , "ab" , "cababc" , "bac" . Return true if and only if the given string  S  is valid. Solution in C++:      bool isValid(string S) {         vector<char> stack;         //Iterating over the characters of the string         for(int iter = 0; iter < S.length(); ++iter){                         //Case: Checking ...

Most frequently asked interview question #2 with solution

We have a string S of lowercase letters, and an integer array shifts . Call the shift of a letter, the next letter in the alphabet, (wrapping around so that 'z' becomes 'a' ). For example, shift('a') = 'b' , shift('t') = 'u' , and shift('z') = 'a' . Now for each shifts[i] = x , we want to shift the first i+1  letters of S , x times. Return the final string after all such shifts to S are applied. Solutions in C++: string shiftingLetters(string S, vector<int>& shifts) {             int sum = 0;             int iter = S.length() - 1;                 for(auto it = shifts.rbegin(); it != shifts.rend(); ++it, --iter){                         sum = sum + *it;  ...

Most frequently asked interview question #1 with solution

Given a string, find the length of the longest substring without repeating characters. Solution in C++:     int lengthOfLongestSubstring(string s) {                     int *char_index = (int*)malloc(sizeof(int) * 256);             int  max_len    = 1;             int  cur_len    = 1;                 if(s.length() == 0){             return 0;         }         //Initializing all the index values with -1 which means the character never appaered before         for(int iter = 0; iter < 256; ++ite...

String class in C++

In C++, another way of representing an array of characters is using Strings class. Using string class gives many advantages over Character array like: The size of the array has to be predefined if it is getting allocated statically(char arr[3]). In this case, there might be unused bytes which results in inefficient memory usage. But, in string class size won't be wasted as memory is allocated on need basis. There is a possibility of array decay in an array of characters(Array decay happens usually when an array of characters is passed as by the value of reference and the type or dimension is changed). Whereas in string class such problems don't arise as it uses objects. Characters array doesn't provide many inbuilt functions to handle operations on strings. Whereas in the string there are many inbuilt functions to do operations. Some of the built-in APIs provided by string class are: getline(cin, str): It is used to take input from the string. cin is also to take i...

Creating Self Signed SSL Certificates for HTTPS Communication

Self Signed CA: Create Private Key for Self Signed CA openssl ecparam -genkey -name secp256r1 | openssl ec -out ca.key     Create CA Certificate for Self Signed CA openssl req -new -x509 -days 36500 -key ca.key -out ca.pem -subj "/C=IN/ST=Karnataka/L=Bengaluru/O=company name/OU=Prod Operations Department/CN=prodops .domain.com   Verify the content of CA certificate openssl x509 -in ca.pem -noout -text Client CERTIFICATE: CLIENT_ID="<Client-Product>" e.g. CLIENT_ID="ClientID" CLIENT_SERIAL="<Client-Release-Number>" e.g. CLIENT_SERIAL="6889" Create Private Key for Client openssl ecparam -genkey -name secp256r1 | openssl ec -out  ${CLIENT_ID}_${CLIENT_SERIAL}.key                   Generate the Certificate Signing Request CSR openssl req -new -key ${CLIENT_ID}_${CLIENT_SERIAL}.key -out ${CLIENT_ID}_${CLIENT_SERIAL}.csr -subj "/C=IN/ST=Karnataka/L=Bengalur...

DataBases: Beginner to Expert(SQL and MySQL)

DataBase: An organized collection of information or data. SQL:  It stands for Standard Query Language. It is a standard language used to communicate with databases. It is used to update, delete, input the data into a database. It is used to perform tasks on a database.  Ex: SELECT * FROM Customers(It selects all the data related Customers table in the database) MySQL: It is a Relational Database Management System(RDBMS). It provides a platform(UI) for the user to access and interact with the database. There are many kinds of RDMS and MySQL is one of them. Other RDBMS available are: PostgreSQL Oracle SQL Server   RDBMS:   RDBMS is a collection of data organized into tables. Tables contain different columns and rows of different categories. If there are two tables where the information in one table is related to information in another table, then these two tables are relational and management of these two tables is called a relational D...

Saving firewall rules permanently in CentOS

There is no way to permanently add firewall rules in the Linux machine. But, one can make some changes so that whenever Linux is booting up it will load firewall rules which are already stored in some file. It can be achieved using iptables-save and iptables-restore to save and restore firewall rules. First, execute all the IPTable rules on the CentOS machine. Then save IPTable rules to some file like /etc/iptables.conf using the following command: $ iptables-save > /etc/iptables.conf   Add the following command in /etc/rc.local to reload the rules in every reboot. $ iptables-restore < /etc/iptables.conf After executing the above command change the permissions of rc.local to executable.   To check whether it is restoring the firewall rules or not, remove the firewall rules and restart the system. If the firewall rules which you stored using iptables-save > /etc/iptables.conf are present then it is working. Otherwise, repeat the above steps. ...

Configuring SSL Certificates for HTTP Server using OpenSSL

The SSL_CTX object uses a method as a connection method. The methods exist in a generic type (for client and server use), a server only types, and a client only type. the method can be of the TLS_method () : TLS_client_method () : TLS_server_method ():  SSL_CTX_new(): SSL_CTX_new() creates a new SSL_CTX object as framework to establish TLS/SSL or DTLS enabled connections. An SSL_CTX object is a reference counted. Creating an SSL_CTX object for the first time increments the reference count. Freeing it (using SSL_CTX_free) decrements it. When the reference count drops to zero, any memory or resources allocated to the SSL_CTX object are freed. SSL_CTX_up_ref() increments the reference count for an existing SSL_CTX structure. int SSL_CTX_set_cipher_list(SSL_CTX *ctx, const char *str): SSL_CTX_set_cipher_list() sets the list of available ciphers for ctx using the control string str . The format of the string is described in ciphers(1) . The list of ciphers is inhe...

Regular expressions in a nut shell

Definitions: Regular Expression: It is a sequence of characters used as a search pattern. Regular expression module API's: re.match(regExp, string, flags) : - It returns match object information like whether a pattern is matched or not                                   - The span of the match(starting and ending index)                                   - matched string                                   - Flags contain special handling.          ...