Programming Practice C++
Describe differences Vectors and Array in C++
Vector is a sequential container. Vector is not index based. Array is a fixed-size sequential collection of elements of the same type. Array is index based. Vectors are dynamic in nature. Once the array is initialized it's size can't be changed. Vector occupies more memory as compared to array. Array is memory efficient data structure. Accessing time in vectors is more. Array elements are arranged in contiguous memory allocation so it accesses elements in constant time. Vectors can be only declared in C++. Arrays can be declared in any programming language like C, Java, Python, etc.
Describe Maps
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have the same key values. Some basic functions associated with Map: begin() - Returns an iterator to the first element in the map. end() - Returns an iterator to the theoretical element that follows the last element in the map. size() - Returns the number of elements in the map. max_size() - Returns the maximum number of elements that the map can hold. empty() - Returns whether the map is empty. pair insert(keyvalue, mapvalue) - Adds a new element to the map. erase(iterator position) - Removes the element at the position pointed by the iterator. erase(const g)- Removes the key-value 'g' from the map. clear() - Removes all the elements from the map. #include <iostream> #include <map> int main() { // Create a map of strings to integers std::map<std::string, int> map; // Insert some values into the map map["one"] = 1; map["two"] = 2; map["three"] = 3; // Get an iterator pointing to the first element in the map std::map<std::string, int>::iterator it = map.begin(); // Iterate through the map and print the elements while (it != map.end()) { std::cout << "Key: " << it->first << ", Value: " << it->second << std::endl; ++it; } return 0; }
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000 For example, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: I can be placed before V (5) and X (10) to make 4 and 9. X can be placed before L (50) and C (100) to make 40 and 90. C can be placed before D (500) and M (1000) to make 400 and 900. Given a roman numeral, convert it to an integer. Example 1: Input: s = "III" Output: 3 Explanation: III = 3. Example 2: Input: s = "LVIII" Output: 58 Explanation: L = 50, V= 5, III = 3. Example 3: Input: s = "MCMXCIV" Output: 1994 Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. Constraints: 1 <= s.length <= 15 s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M'). It is guaranteed that s is a valid roman numeral in the range [1, 3999].
approach If there are Numbers such as XL, IV, etc.Simply subtract the smaller number and add the larger number in next step.For example, if there is XL, ans =-10 in first step, ans=-10+50=40 in next step. Otherwise, just add the numbers. Complexity Time complexity: O(n) Code class Solution { public: int romanToInt(string s) { int ans=0; unordered_map <char,int> mp{ {'I',1},{'V',5},{'X',10},{'L',50},{'C',100},{'D',500},{'M',1000}}; for(int i=0;i<s.size();i++){ if(mp[s[i]]<mp[s[i+1]]){ //for cases such as IV,CM, XL, etc... ans=ans-mp[s[i]]; } else{ ans=ans+mp[s[i]]; } } return ans; } };
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. Example 1: Input: l1 = [2,4,3], l2 = [5,6,4] Output: [7,0,8] Explanation: 342 + 465 = 807. Example 2: Input: l1 = [0], l2 = [0] Output: [0] Example 3: Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] Output: [8,9,9,9,0,0,0,1] Constraints: The number of nodes in each linked list is in the range [1, 100]. 0 <= Node.val <= 9 It is guaranteed that the list represents a number that does not have leading zeros.
class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode* Answer = new ListNode(0); // Create a new linked list ListNode* Current_node = Answer; // Create a new node for validation } int carry = 0; // Create a variable to store value when > 9} while (l1 != NULL || l2 != NULL || carry !=0) { // while there is still l1 or l2, or a carry amount} int x = l1 ? l1 -> val : 0; // if l1 does not have a value set to zero} int y = l2 ? l2 -> val : 0; int sum = x + y + carry; carry = sum/10; Current_node -> next = new ListNode(sum%10); // add a new node holding onto the mod of sum} Current_node = Current_node -> next; // point the current node to the next node of Answer } l1 = l1 ? l1 -> next : NULL; // if not at end of list point to the next node. } l2 = l2 ? l2 -> next : NULL; } return Answer -> next; // return the dummy list with next pointing to first node. } } };
Given an integer x, return true if x is a palindrome , andfalseotherwise. Example 1: Input: x = 121 Output: true Explanation: 121 reads as 121 from left to right and from right to left. Example 2: Input: x = -121 Output: false Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. Example 3: Input: x = 10 Output: false Explanation: Reads 01 from right to left. Therefore it is not a palindrome. Constraints: -231 <= x <= 231 - 1 Follow up:Could you solve it without converting the integer to a string?
class Solution { public: bool isPalindrome(int x) { long long int copy=x; long long int rev=0; while(x!=0){ long long int rem; rem=x%10; rev=rev*10 +rem; x=x/10; } bool check=false; if(rev<0){ return check; } else if(rev==copy){ check=true; return check; }else return check; } };
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order. Example 1: Input: nums = [2,7,11,15], target = 9 Output: [0,1] Explanation: Because nums[0] + nums[1] == 9, we return [0, 1]. Example 2: Input: nums = [3,2,4], target = 6 Output: [1,2] Example 3: Input: nums = [3,3], target = 6 Output: [0,1] Constraints: 2 <= nums.length <= 104 -109 <= nums[i] <= 109 -109 <= target <= 109 Only one valid answer exists.
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { for (int i = 0; i < nums.size(); i++) { for (int j = i + 1; j < nums.size(); j++) { if (nums[i] + nums[j] == target) { return {i, j}; } } } return {}; } }; Complexity Time complexity: O(N^2); Space Complexity: O(1); ***OPTIMIZED*** #include <unordered_map> class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int, int> mp; // create map of ints for(int i = 0; i < nums.size(); i++){ if(mp.find(target - nums[i]) == mp.end()) //if map element not found mp[nums[i]] = i; // add value to map else return {mp[target - nums[i]], i}; //otherwise value was already in map and we return the value. } return {-1, -1}; } }; Time complexity: O(N); Space Complexity: O(N); Instead of finding X+Y = target, using target - y = x