Fraction Addition and Subtraction | Simple Simulation | Leetcode 592 | codestorywithMIK

preview_player
Показать описание
This is the 41st Video of our Playlist "Strings : Popular Interview Problems" by codestorywithMIK

In this video we will try to solve a very good String Problem : Fraction Addition and Subtraction | Simple Simulation | Leetcode 592 | codestorywithMIK

I will explain the intuition so easily that you will never forget and start seeing this as cakewalk EASYYY.
We will do live coding after explanation and see if we are able to pass all the test cases.
Also, please note that my Github solution link below contains both C++ as well as JAVA code.

Problem Name : Fraction Addition and Subtraction | Simple Simulation | Leetcode 592 | codestorywithMIK
Company Tags : Will update soon

╔═╦╗╔╦╗╔═╦═╦╦╦╦╗╔═╗
║╚╣║║║╚╣╚╣╔╣╔╣║╚╣═╣
╠╗║╚╝║║╠╗║╚╣║║║║║═╣
╚═╩══╩═╩═╩═╩╝╚╩═╩═╝

Summary :
The approach to solving the fraction addition problem involves parsing and processing a string containing fractions, performing arithmetic operations to accumulate the result, and simplifying the final fraction. Here's a summary:

Parsing the Input: The string expression is iterated to extract each fraction's numerator and denominator, handling both positive and negative signs.

Fraction Arithmetic: As fractions are parsed, they are converted to a common denominator to allow direct addition or subtraction. The cumulative result is maintained using two variables: one for the numerator and one for the denominator.

Simplification: Once all fractions are processed, the resulting fraction is simplified by dividing both the numerator and denominator by their greatest common divisor (GCD).

Result: The simplified fraction is returned as a string in the form "numerator/denominator".

The algorithm efficiently handles multiple fractions and simplifies the final result.

✨ Timelines✨

00:00 - Introduction

#coding #helpajobseeker #easyrecipes #leetcode #leetcodequestionandanswers #leetcodesolution #leetcodedailychallenge #leetcodequestions #leetcodechallenge #hindi #india #coding #helpajobseeker #easyrecipes #leetcode #leetcodequestionandanswers #leetcodesolution #leetcodedailychallenge#leetcodequestions #leetcodechallenge #hindi #india #hindiexplanation #hindiexplained #easyexplaination #interview#interviewtips #interviewpreparation #interview_ds_algo #hinglish #github #design #data #google #video #instagram #facebook #leetcode #computerscience #leetcodesolutions #leetcodequestionandanswers #code #learning #dsalgo #dsa #newyear2024
Рекомендации по теме
Комментарии
Автор

Thanks, MIK! I want to thank you for being my teacher over this past one year. I have been doing leetcode since 2018. I had no background in CS before that. I could clear interviews only after i started following this channel. I cannot stress enough that the explanation and story you give are EXACTLY what interviewers look for. I signed my Microsoft offer recently. If anyone asks how I prepped, I share your channel with them.

nitisharma
Автор

Got Placed with 20LPA yesterday.

Thank you so much MIK, last 3 months, it's all about starting the day with leetcode daily and seeing your videos.

You are the best ❤❤

gauravkumar
Автор

Reason for solving leetcode efficiently..and understanding ❤

mohitchoudhary
Автор

I solved it on my own. Made some mistakes, finally got accepted 😃

aws_handles
Автор

Please make video on today's question. Waiting for it

kusumjoshi
Автор

Thank you so much MIK .learning new everyday from you.

stillthinking
Автор

Hi MIK, for this problem, I took inspiration from your String LC-Hard problem and was able to easily solve this one. Thanks for your inputs!

rev_krakken
Автор

Bhaiya, could you please create a complete DSA course? I'm eagerly looking forward to it because your explanations are much better than others.

abhishekprasad
Автор

wow so fast...hats off to your dedication...

I was able to code myself lekin int main :)

I thought of this approach too, bas implement karne mai dikkat aa gayi

btw aaj ka second short tip daal do, ye number conversion waala,

aizadiqbal
Автор

Could u plz also make a video on differences between istringstream and stringstream and what r different ways to get inputs from this stream (like getline and >> operator) ? 🙏

xiaoshen
Автор

Java Solution With Own Code for GCD:

class Solution {
public int getGcd(int num, int deno){
if(num == 0)
return deno;

int seed = Math.min(num, deno);

while(seed > 0){
if(num%seed == 0 && deno%seed == 0)
return seed;
seed--;
}

return -1;
}

public String fractionAddition(String expression) {
final int N = expression.length();
int num = 0, deno = 1, i = 0;

while(i < N){
int currNum = 0;
int currDeno = 0;
boolean isNegative = (expression.charAt(i) == '-');

if(expression.charAt(i) == '+' || expression.charAt(i) == '-')
i++;

// Num
while(i<N &&
int val = expression.charAt(i) - '0';
currNum = (currNum * 10) + val;
i++;
}
if(isNegative)
currNum *= -1;

i++;

// Den
while(i<N &&
int val = expression.charAt(i) - '0';
currDeno = (currDeno * 10) + val;
i++;
}

num = (num * currDeno) + (deno * currNum);
deno = deno * currDeno;
}

int GCD = getGcd(Math.abs(num), Math.abs(deno));
num /= GCD;
deno /= GCD;

return num + "/" + deno;
}
}

nikhilhaspe
Автор

I tried to solve this question by myself. I tried for 2 days but finally I lost to this question & had to see you video.😢

manimanohar_
Автор

I did this using LCM method...

class Solution {
int gcd(int a, int b) {
while(a){
int remainder = b % a;
b = a;
a = remainder;
}
return b;
}
public:
string fractionAddition(string s) {
int n = s.length();

vector<int> numerator, denominator;
long long product = 1;
int totalGcd = 0;

int lcm = 1;

int i = 0;

while (i < n){
int temp = 1;

if (s[i] == '-'){
temp *= -1;
i++;
}
else if (s[i] == '+'){
i++;
}

//numerator
temp = (s[i] - '0') * temp;
if (i+1 < n && s[i+1] == '0'){
temp *= 10;
i++;
}

i += 2;
numerator.push_back(temp);
//denominator
temp = 1;

temp *= (s[i] - '0');
if (i+1 < n && s[i+1] == '0'){
temp *= 10;
i++;
}
denominator.push_back(temp);

product *= temp;
totalGcd = gcd(abs(temp), totalGcd);

i++;
}

//find lcm
int deno = product/totalGcd;
if (n == 3 || n == 4){
deno = totalGcd;
}

int nume = 0;
for (int i = 0; i < numerator.size(); i++){
nume += ( (deno/denominator[i])* numerator[i]);
}

//simplify;
int hcf = abs(gcd(deno, nume));
nume /= hcf;
deno /= hcf;

return to_string(nume) + '/' + to_string(deno);
}
};

theOmKumar
Автор

I did it in a diff




class Solution {
public:
int lcmArray(vector<int>& arr) {
int result = arr[0];
for(size_t i = 1; i < arr.size(); ++i) {
result = lcm(result, arr[i]);
}
return result;
}
string fractionAddition(string e) {


string s="";
int f=0, n=e.length();
vector<int>ans, ans1, ans2;
vector<char>v;
int i=0;
while(i<n){
int sum=0;
while(i<n&&isdigit(e[i])){
sum=(sum*10+(e[i]-'0'));
i++;
}
i++;
if(sum!=0)
ans.push_back(sum);
}
for(int i=1;i<ans.size();i+=2)
ans1.push_back(ans[i]);
for(int i=0;i<ans.size();i+=2)
ans2.push_back(ans[i]);
int den=lcmArray(ans1);
if(e[0]!='-')
e="+"+e;
for(auto ch:e){
if(ch=='+')
v.push_back(ch);
if(ch=='-')
v.push_back(ch);
}
int num=0;i=0;
while(i<ans2.size()){
if(v[i]=='-')
num-=(den/ans1[i])*ans2[i];
else
num+=(den/ans1[i])*ans2[i];
i++;
}
int p=den;
den=den/(__gcd(abs(num), abs(den))); num=num/(__gcd(abs(num), abs(p)));
return s;
}
};

factinsaan
Автор

1551.Minimum operations to make Array Equal
Can you make a video for this I have encountered many Question like this
But don't understand what to do
There are many other question like this but I don't understand from how to start what is the approach
Can you simply and also tell the general approach for solving this type of question please.

ayushigholase
Автор

Easy but looked horrible to code until I reached here.

abhisheksinghdangi
Автор

Bhai, wo Aaj ka leetcode question kab ayega? Find the closest palindrome .

deepakkumarsahoo
Автор

Bhaiya aap Strange Printer vale que ka solution batao na. Aapka 1 year pehle ka dekha tha but jab mein string of length 5 le rha hu to traverse nahi kar paa rha to aap ye que ek baar solve karke bata sakte ho pls

challengeAceiver
Автор

"-1/2+1"

aisa input possible nahi hai na, but agar hota toh bas, currDeno mai 1 initialize kar dete ....toh chal jaata na fir ?

aizadiqbal
Автор

my js solution

solved by self with my own approach

/**
* @param {string} expression
* @return {string}
*/
var fractionAddition = function(expression) {

if(expression[0] != "-" && expression[0] != "+") expression = "+" + expression;

let n = 0;
let d= 1;

for(let i = 0; i < expression.length; i += 4) {

let sign = expression[i];

let tn = ""
let j = i + 1;
while(!isNaN(expression[j])) {
tn += expression[j]
j++;
}
tn = Number(tn)
if(tn > 9)i++;
let td = ""
j = i + 3;

while(!isNaN(expression[j])) {
td += expression[j]
j++;
}
td = Number(td)
if(td > 9)i++;

console.log(d, td)
let lcm = LCM(d, td);

n = (lcm / d) * n;
tn = (lcm / td) * tn;
d = lcm;

if(sign == "+") n += tn;
else n -= tn;
if(n == 0) d = 1;
}

isMinus = n < 0 ? -1 : 1;

n *= isMinus;

let min = Math.min(n, d);

for(let i =2; i <= min; i++) {

if(n % i == 0 && n % i == 0) {
while(n % i == 0 && d % i == 0 ) {
n /= i;
d /= i;
}
min = Math.min(n, d);
}
}

return `${n * isMinus}/${d}`


};


function LCM(n1, n2) {

const hcf = HCF(n1, n2)

return (n2 * n1 )/hcf
}

function HCF(n1, n2) {
if (n2 === 0) return n1;
return HCF(n2, n1 % n2);
}

aman_v