SkylineWebZ

Adding one to number represented as array of digits

Add 1 to a non-negative number that is represented by an array of digits to increase the number that the digits represent. The digits are stored so that the array’s first entry is the most significant digit. Examples :  Input : [1, 2, 4] Output : [1, 2, 5] Input : [9, 9, 9] Output : [1, 0, 0, 0] Method: Take the actions listed below to add one to the number that is represented by the digits: Output 1 7 9 0 Time Complexity: O(n), where n is the size of the array. Auxiliary Space: O(1) An alternative method is to begin at the end of the vector and set the last element to 0 if it is 9, otherwise break the loop. C++ Java Python3 C# Go

Adding one to number represented as array of digits Read More »

Wildcard Matching In C,CPP,JAVA,PYTHON,C#,JS

Problem Statement: Wildcard Matching Given two strings s and p, return true if s matches p (with wildcard characters), and false otherwise. The string p can contain the following wildcard characters: Example: Example 1: Input: s = “aa”, p = “a*”Output: trueExplanation: “a*” matches “aa” because ‘*’ can match the second ‘a’. Example 2: Input: s = “mississippi”, p = “mis*is*p*.”Output: false Example 3: Input: s = “adceb”, p = “*a*b”Output: trueExplanation: The pattern “*a*b” matches the string “adceb”. Approach: The problem can be solved using Dynamic Programming (DP). The idea is to use a 2D DP table where dp[i][j] represents whether the substring s[0..i-1] matches the pattern p[0..j-1]. Steps: Dynamic Programming Solution: Python Code: def isMatch(s: str, p: str) -> bool: # dp[i][j] will be True if s[0…i-1] matches p[0…j-1] dp = [[False] * (len(p) + 1) for _ in range(len(s) + 1)] # Initial condition: empty string matches empty pattern dp[0][0] = True # If the pattern starts with ‘*’ it can match the empty string for j in range(1, len(p) + 1): if p[j – 1] == ‘*’: dp[0][j] = dp[0][j – 1] # Fill the dp table for i in range(1, len(s) + 1): for j in range(1, len(p) + 1): if p[j – 1] == s[i – 1] or p[j – 1] == ‘?’: dp[i][j] = dp[i – 1][j – 1] elif p[j – 1] == ‘*’: dp[i][j] = dp[i – 1][j] or dp[i][j – 1] # The bottom-right corner will contain the answer return dp[len(s)][len(p)] Explanation of the Code: Time and Space Complexity: Example Walkthrough: Example 1: Input: s = “aa”, p = “a*” The final result is True, as dp[2][2] = True. Example 2: Input: s = “mississippi”, p = “mis*is*p*.” Conclusion: The Wildcard Matching problem is efficiently solved using Dynamic Programming. By filling a DP table and considering all possible ways a wildcard can match a sequence of characters, we can determine if the string matches the pattern with wildcards * and ?. The time complexity of O(m * n) is suitable for handling reasonably large inputs, where m and n are the lengths of the string and the pattern, respectively.

Wildcard Matching In C,CPP,JAVA,PYTHON,C#,JS Read More »

Multiply Strings In C,CPP,JAVA,PYTHON,C#,JS

Problem Statement: Multiply Strings Given two non-negative integers num1 and num2 represented as strings, return the product of num1andnum2`, also as a string. Note: Example: Example 1: Input: num1 = “2”, num2 = “3”Output: “6” Example 2: Input: num1 = “123”, num2 = “456”Output: “56088” Example 3: Input: num1 = “0”, num2 = “0”Output: “0” Approach: Multiplying large numbers represented as strings without converting them to integers can be achieved using the standard method of multiplication that we learn in elementary school: long multiplication. Here’s the step-by-step breakdown: Algorithm: Code Implementation: Python: def multiply(num1: str, num2: str) -> str: # Edge case: if either number is “0”, the result is “0” if num1 == “0” or num2 == “0”: return “0” # Initialize the result array with zeros. The maximum length of the result # can be at most len(num1) + len(num2). result = [0] * (len(num1) + len(num2)) # Reverse num1 and num2 to make the multiplication easier num1 = num1[::-1] num2 = num2[::-1] # Perform multiplication for i in range(len(num1)): for j in range(len(num2)): # Multiply digits and add to the corresponding position in the result array product = int(num1[i]) * int(num2[j]) result[i + j] += product result[i + j + 1] += result[i + j] // 10 # Carry to the next position result[i + j] %= 10 # Keep only the single digit at the current position # The result array now contains the digits of the product in reverse order. # We need to remove any leading zeros. # Convert the result to a string result = result[::-1] # Skip leading zeros result_str = ”.join(map(str, result)).lstrip(‘0’) return result_str Explanation of the Code: Time and Space Complexity: Example Walkthrough: Example 1: Input: num1 = “123”, num2 = “456” Edge Case Examples: Example 2: Input: num1 = “0”, num2 = “123” Example 3: Input: num1 = “999”, num2 = “999” Conclusion: The Multiply Strings problem is solved by simulating the long multiplication process. This method avoids the use of built-in integer multiplication and provides an efficient solution with a time complexity of O(m * n). By handling carries and constructing the result step by step, we can multiply large numbers represented as strings and return the result as a string.

Multiply Strings In C,CPP,JAVA,PYTHON,C#,JS Read More »

Count and Say In C,CPP,JAVA,PYTHON,C#,JS

Problem Statement: Count and Say The Count and Say sequence is a sequence of strings where each term is derived from the previous one by describing the frequency and value of the consecutive digits in the string. For example: Given an integer n, generate the nth term of the Count and Say sequence. Input: Output: Example: Example 1: Input: n = 1Output: “1” Example 2: Input: n = 4Output: “1211” Approach: The process to generate the nth term in the Count and Say sequence involves the following steps: Algorithm: Code Implementation: Python: def countAndSay(n: int) -> str: # The first term in the sequence is always “1” result = “1” # Build the sequence iteratively for n-1 times for _ in range(1, n): next_result = “” count = 1 # Traverse through the current result string for i in range(1, len(result)): if result[i] == result[i – 1]: # If the current character is the same as the previous one, increment the count count += 1 else: # If the current character is different, append the count and character to next_result next_result += str(count) + result[i – 1] count = 1 # Reset count for the new character # Don’t forget to append the last group of characters next_result += str(count) + result[-1] # Update result for the next iteration result = next_result return result Explanation of Code: Time and Space Complexity: Example Walkthrough: Example 1: Input: n = 1 Example 2: Input: n = 4 Example 3: Input: n = 5 Edge Cases: Conclusion: The Count and Say problem can be solved efficiently using an iterative approach where each term is built from the previous one by counting and describing consecutive digits. This approach runs in linear time relative to the size of the terms, making it efficient enough for the given constraints.

Count and Say In C,CPP,JAVA,PYTHON,C#,JS Read More »

Longest Valid Parentheses In C,CPP,JAVA,PYTHON,C#,JS

Problem Statement: Longest Valid Parentheses Given a string containing just the characters ‘(‘ and ‘)’, find the length of the longest valid (well-formed) parentheses substring. Definition of Valid Parentheses: Input: Output: Example: Example 1: Input: s = “(()”Output: 2Explanation: The longest valid parentheses substring is “()”. Example 2: Input: s = “)()())”Output: 4Explanation: The longest valid parentheses substring is “()()”. Example 3: Input: s = “”Output: 0Explanation: The string is empty, so there is no valid parentheses substring. Approach: To solve this problem, we need to find the longest substring of valid parentheses. There are several approaches to solving this problem efficiently: Algorithm (Using Stack): Stack Approach Explanation: Code Implementation (Using Stack): Python: def longestValidParentheses(s: str) -> int: stack = [-1] # Initialize the stack with -1 to help with length calculations max_len = 0 for i, char in enumerate(s): if char == ‘(‘: stack.append(i) # Push the index of ‘(‘ onto the stack else: stack.pop() # Pop the last element when encountering ‘)’ if not stack: stack.append(i) # Push the current index as the base for the next valid substring else: max_len = max(max_len, i – stack[-1]) # Calculate the length of valid substring return max_len Explanation of Code: Time and Space Complexity: Edge Cases: Example Walkthrough: Example 1: Input: s = “(()” Example 2: Input: s = “)()())” Alternative Approaches: However, the stack approach provides the most intuitive and space-efficient solution for this problem.

Longest Valid Parentheses In C,CPP,JAVA,PYTHON,C#,JS Read More »

Substring with Concatenation of All Words In C,CPP,JAVA,PYTHON,C#,JS

Problem Statement: Substring with Concatenation of All Words Given a string s and a list of words words, you need to find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters. Each word in the list words has the same length. The length of the concatenated substring is the sum of the lengths of all the words, and the substring must consist of exactly one occurrence of each word from the list (in any order). Input: Output: Example: Example 1: Input: s = “barfoothefoobarman”, words = [“foo”, “bar”]Output: [0, 9]Explanation: The substring starting at index 0 is “barfoo”, and the substring starting at index 9 is “foobar”. Example 2: Input: s = “wordgoodgoodgoodbestword”, words = [“word”, “good”, “best”, “good”]Output: [8]Explanation: The substring starting at index 8 is “goodbestword”. Approach: Algorithm: Code Implementation: Python: from collections import Counterdef findSubstring(s, words): if not s or not words: return [] word_len = len(words[0]) word_count = len(words) word_map = Counter(words) # Frequency map of the words in ‘words’ result = [] # Sliding window of size word_len * word_count for i in range(word_len): left = i right = i current_count = 0 window_map = Counter() # Map to track the current window while right + word_len <= len(s): word = s[right:right + word_len] right += word_len if word in word_map: window_map[word] += 1 current_count += 1 # If the word count exceeds the expected count, move left pointer while window_map[word] > word_map[word]: left_word = s[left:left + word_len] window_map[left_word] -= 1 current_count -= 1 left += word_len # If we have found all words in the window, add to the result if current_count == word_count: result.append(left) else: # Reset the window if the word is not in the words list window_map.clear() current_count = 0 left = right return result Explanation: Time and Space Complexity: Example Walkthrough: Example 1: Input: s = “barfoothefoobarman”, words = [“foo”, “bar”] Example 2: Input: s = “wordgoodgoodgoodbestword”, words = [“word”, “good”, “best”, “good”]

Substring with Concatenation of All Words In C,CPP,JAVA,PYTHON,C#,JS Read More »

Find the Index of the First Occurrence in a String In C,CPP,JAVA,PYTHON,C#,JS

Problem Statement: Given a string s and a target character ch, your task is to find the index of the first occurrence of the character ch in the string s. If the character is not found, return -1. Input: Output: Example: Example 1: Input: s = “hello”, ch = ‘e’Output: 1Explanation: The first occurrence of ‘e’ is at index 1. Example 2: Input: s = “hello”, ch = ‘a’Output: -1Explanation: ‘a’ is not present in the string. Approach: To solve the problem, we can use a linear scan of the string s to look for the character ch. The first occurrence of ch in the string will be returned as the index. If no match is found, return -1. Algorithm: Code Implementation: C: #include <stdio.h>#include <string.h>int first_occurrence(char* s, char ch) { for (int i = 0; i < strlen(s); i++) { if (s[i] == ch) { return i; } } return -1;}int main() { char s[] = “hello”; char ch = ‘e’; int result = first_occurrence(s, ch); printf(“%d\n”, result); // Output: 1 return 0;} C++: #include <iostream>#include <string>using namespace std;int first_occurrence(string s, char ch) { for (int i = 0; i < s.length(); i++) { if (s[i] == ch) { return i; } } return -1;}int main() { string s = “hello”; char ch = ‘e’; cout << first_occurrence(s, ch) << endl; // Output: 1 return 0;} Java: public class Main { public static int firstOccurrence(String s, char ch) { for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == ch) { return i; } } return -1; } public static void main(String[] args) { String s = “hello”; char ch = ‘e’; System.out.println(firstOccurrence(s, ch)); // Output: 1 }} Python: def first_occurrence(s, ch): for i in range(len(s)): if s[i] == ch: return i return -1s = “hello”ch = ‘e’print(first_occurrence(s, ch)) # Output: 1 C#: using System;class Program { static int FirstOccurrence(string s, char ch) { for (int i = 0; i < s.Length; i++) { if (s[i] == ch) { return i; } } return -1; } static void Main() { string s = “hello”; char ch = ‘e’; Console.WriteLine(FirstOccurrence(s, ch)); // Output: 1 }} JavaScript: function firstOccurrence(s, ch) { for (let i = 0; i < s.length; i++) { if (s[i] === ch) { return i; } } return -1;}let s = “hello”;let ch = ‘e’;console.log(firstOccurrence(s, ch)); // Output: 1 Time Complexity: Space Complexity: Edge Cases:

Find the Index of the First Occurrence in a String In C,CPP,JAVA,PYTHON,C#,JS Read More »

The Importance of Data Analytics in Digital Marketing

Since the mid-19th century, marketers have been examining their strategies and approaches; nevertheless, today’s data analytics does not match those early marketing initiatives meant to maximize profits. Driven by digital technology, data analytics models track the value of every consumer action and touch point across many platforms and devices. Using sophisticated analytic tools to assess digital marketing campaigns. At every stage of the customer experience, more than eighty percent of marketing professionals base their judgments on facts.01 Those who can use these advanced techniques to obtain insightful marketing knowledge will shape digital strategy going forward. This paper delves deeply into data analytics in digital marketing. What it is, where the data comes from, and how it may be applied to increase the success of digital marketing initiatives. Digital Marketing Data Analytics: Definition Data analytics, as used in marketing, is the process of compiling and evaluating data. From many digital sources to provide practical understanding of a company’s digital marketing plan. By means of a customized experience, digital marketing analytics tools can stimulate fresh approaches, lower churn rate—that is. When consumers cease interacting with a company—and raise current customer value. Two, three Only 30% of companies had a clear data strategy. Although 94% of companies see data and analytics as vital for their digital transformation and expansion in 2020.4,5 5 By eliminating the guessing from marketing strategy and producing ideal value from a company’s marketing spend, data analytics helps companies be more efficient. Which three models of marketing analytics are there? Professional marketers apply three kinds of analytic models to develop, run, and maximize their marketing initiatives.5 Descriptive: Previous campaigns’ historical data is gathered, and this knowledge is applied to offer direction for next campaigns.Predictive. These data analytics models use insights from past marketing campaigns to try to predict consumers’ behavior. So that the company can develop a better-informed, more targeted campaign Prescriptive. These models compile data from all available touchpoints. Analyzing the impact of each company initiative and customer interaction. So helping the organization create highly targeted campaigns influencing customer behavior.These analytic models used together provide a whole picture of the success of marketing campaigns. How each business may more quickly reach its intended outcomes.sixth Where Does the Information Originate? Digital analytics’ raw data comes from many various sources. Hence lacking internal knowledge to make good use of it might be intimidating. Details on consumer interactions can originate from: Data from websites (tracking)Product data (most/least preferred attributes, conversion events, points of conflict)Keyword analysis. Social media interactions—digital marketing dataInternal customer data (transactions, accounts, complaints) 2These days, one may compile this kind of information in real time without direct customer interaction.Second Application of Marketing Analytics Data analytics helps marketers make sense of a lot of consumer data by means of insights that direct their brand, marketing, and product strategy development. By better understanding their market and consumers thanks to sophisticated data analytics approaches. Businesses may create more tailored digital marketing strategies, more individualized customer interactions, more customer pleasure, more efficiency and more profitability. Create thorough customer profiles. Combining information from many sources allows you to view the whole user path in one location. Customers arrived at your website, for instance, and you can observe how ad, social media, etc.? You may also view all of their activities, including questions or purchases of products.Two From an unmet demand and awareness of your goods or services to interaction with your firm, purchase and engagement, data analytics can show you the whole customer lifeline. These same consumers might even go on to share their experience with possible new clients, therefore acting as product or corporate champions.Eighth Align Customer Expectations with Product Performance By more precisely matching marketing campaigns and product features with customer expectations, your corporate marketing team may guarantee better outcomes using actionable data. This helps to lower the rate of turnover.Two Recognize Client Behaviour You have to be able to grasp and forecast consumer behavior patterns if you are to draw in business and modify your marketing and advertising strategies to fit their needs. Mail marketing systems, for instance, enable you track members to observe their responses—including social media sharing and likes. Increased revenues follow from more customer involvement.VII Create fresh ideas, new strategies, and new revenue sources. Given current consumer preferences, a corporation can more safely test consumer acquisition. Based on what the data indicates about consumer wants, it might produce a whole new product, improve product features, or modify an existing marketing plan. This can also open the path for fresh income sources.Two Create focused personalization. Ninety percent of skilled marketers linked tailored marketing to higher company revenues, according a Google marketing study.9 To produce very focused products, marketing analytics provides the comprehensive data you need about consumers. Based on consumer profiles, buying patterns, and browsing behavior, analytics tools can forecast and identify what consumers want—which also influences a better customer experience.TWO Track Campaign Success Using the correct analytics tools allows you to monitor the efficacy of your marketing campaign in real-time, thereby enabling your business to be more flexible in improving campaigns and strategy refining. For sponsored marketing campaigns especially, this is crucial since it enables you to maximize your ad expenditure. This means that marketing campaigns immediately relate to key indicators like the website traffic of your business and you can observe how different marketing channels applied—web, mobile, social media, etc.—have affect on customer behavior. This can then guide next plans and raise effectiveness.7.6, 6.0 In the marketing sector, return on investment (ROI) is absolutely vital. Marketing analytics links a company’s marketing activities to return on investment, therefore verifying its marketing budget. Demand Forecast Timely data and historical record analysis help you to identify trends and demand for goods and services by means of which Particularly at a company on a limited budget, predictive analytics provides the ability to envision the future and can be quite valuable.Seventh Digital marketing’s data analytics help your company to have a competitive edge. It helps you to better grasp not just your

The Importance of Data Analytics in Digital Marketing Read More »

How to Start a Self-Care Routine You’ll Follow

Your needs, calendar, and personal tastes will determine the ideal self-care regimen. “Self-care means really listening to your body, taking moments to check in, deliberately tuning in to the thoughts going on in your mind, and challenging your behaviors and belief systems if things feel out of alignment in your life,” says Kelsey Patel, a Los Angeles–based wellness coach and Reiki instructor, and author of Burning Bright: Rituals, Reiki, and Self-Care to Heal Burnout, Anxiety, and Stress. Although you might be ready for the task, one thing is definitely realizing you need self-care; another is actually implementing a self-care routine that will help you, especially in light of so much outside of your control happening in the world. Here’s how to accomplish this.First, define what is self-care and what is not. Most of the studies on self-care originate in nursing rather than from mental health disciplines. Long recognized as a means of maintaining general health and either preventing or controlling chronic illness is diet. Studies reveal that the idea of self-care is nebulous as so many various definitions apply.The authors describe self-care as the capacity to achieve, preserve, or advance optimal health and well-being via awareness, self-control, and self-reliance.Practically, self-care is complex. Paula Gill Lopez, PhD, an associate professor and chair of the department of psychological and educational consultation at Fairfield University in Connecticut, whose studies center on self-care, defines it as the deliberate, proactive search for integrated wellness that balances mind, body, and spirit personally and professionally. It goes beyond merely looking after your physical condition. “Just eating healthy isn’t enough now,” Patel notes. “We need room to self-care and slow down to rest from all the busyness in our lives; things are moving so fast around us.” A activity is not self-care simply because it “good for you.” “I suggest looking for something you enjoy for self-care,” says Brooklyn, New York-based licensed psychologist Stephanie Freitag, PhD, an adjunct assistant professor at Emory School of Medicine. That could be something for pure enjoyment—a massage or frequent dinners with friends—or something that improves physical health—a particular kind of exercise. The common denominator of self-care routines is that you get some satisfaction out of the activity, adds Marni Amsellem, PhD, a licensed psychologist in private practice headquartered in Fairfield County, Connecticut. Your point of view helps you decide what kinds of activities qualify as self-care. For example, suppose you recently started running and have a weekly running target of ten miles. Running itself might not be fun, so you might suffer through every minute of it as you start. Still, it could be worth it if achieving your targets makes you happy. Though in the moment it doesn’t feel like self-care, Dr. Amsellem says if that practice helps you say: Look at what I did today; I’m working toward my goal and that feels wonderful — then that counts. Dr. Freitag notes that several less-than-fun hobbies count as self-care, such maintaining a tidy house and giving annual visits top priority. Once more, these activities may not make the present joyful—not for everyone, anyway—but they greatly increase general well-being and peace of mind. Simply said, self-care is all the actions you take, in the best possible manner, to tend to your mental and physical wellbeing. “Good self-care consists in doing the activities that will enable you operate at an optimal level,” explains Shauna Pollard, PhD, a psychologist in private practice headquartered in Rockville, Maryland. She advises that the activities you include in your self-care schedule should balance the ones that deliver instant delight with the ones that offer enjoyment once they are finished. Steps for Developing (and Entering) a Self-Care Routine Use these steps to start a sustainable self-care routine. Determine what brings you back to earth. Leading self-care seminars for professional groups, colleges, and community organizations, Dr. Gill Lopez notes she introduces attendees to many forms of self-care since one size does not fit all. “I go through all different kinds of things that could appeal to people in hopes that they’ll find something they can regularly do,” Gill Lopez explains. Start by jotting down as many items as you can think of that make you happy—the color purple, back-off strokes, springtime, specific fragrances, or music. Come up with ideas on how you might include those items into your everyday routine. Gill Lopez says it might be in the background (such as devoting a certain amount of time in your daily routine for a given activity) or it could occupy a more prominent place in your daily life (such as coloring your space with the hues and smells you prefer). Try introducing just one new self-care technique at a time; starting small might help one develop the habit more easily. Plan to include daily self-care activities. Once you choose the self-care activities you want to include into your life, create plans for when and how often. Gill Lopez advises in an essay in the 2017 National Association of School Psychologists Communiqué to make your aim reasonable and quantifiable.[1] If you’re trying to be more present by unplugging from electronic gadgets, for example, start with a small period, like twenty minutes at dinner. Once you can effectively follow that for a week, you can create a more difficult target. Get help. Freitag advises depending on your support network to maintain sustainable habits in your self-care. Look for others who participate in the same kind of self-care activities so you may occasionally do them together. As you proceed, change and refine your strategy. If there are occasional hiccups, it’s normal. “We’re talking about a practice, we’re talking about trial and error. We’re also talking about our needs changing over time.” Explains Washington, DC psychologist Ellen K. Baker, PhD. “What might be self-care in one period could be less so in another period.” Reading a book to your child (or yourself) every night; going for a 10-minute walk outside; sleeping earlier; turning off your devices in the evening; cooking with more wholesome ingredients;

How to Start a Self-Care Routine You’ll Follow Read More »

Min cost path using Memoization DP:

Min cost path by means of memoizing DP: We utilize a 2D array for memorizing since the recursive solution changes two parameters.To signify that no values are computed initially, we start the 2D array as -1.First we check in the memo table in the recursion. Should we detect value as -1, we only call recursively. In this sense, we avoid recommendations of the same sub-problems. C++ Java Python JavaScript Time Complexity: O(M * N)Auxiliary Space: O(M * N)

Min cost path using Memoization DP: Read More »