question_slug
stringlengths
3
77
title
stringlengths
1
183
slug
stringlengths
12
45
summary
stringlengths
1
160
author
stringlengths
2
30
certification
stringclasses
2 values
created_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
updated_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
hit_count
int64
0
10.6M
has_video
bool
2 classes
content
stringlengths
4
576k
upvotes
int64
0
11.5k
downvotes
int64
0
358
tags
stringlengths
2
193
comments
int64
0
2.56k
customers-who-bought-all-products
Simple solution with Common Table Expressions | Beats 90.23% Runtime | Beats 100% Memory |
simple-solution-with-common-table-expres-pgzb
Intuition\nSimple solution by aggregating on the sum & count of the product ids\n\n# Approach\nUse of common table expression (CTE) to access information from t
adharshvenkat
NORMAL
2024-03-01T16:00:30.941251+00:00
2024-03-01T16:00:30.941323+00:00
616
false
# Intuition\nSimple solution by aggregating on the sum & count of the product ids\n\n# Approach\nUse of common table expression (CTE) to access information from the Product table without having the need to join, as joining would not yield any valuable results\n\n\n# Code\n```\nwith sample as \n(select sum(product_key) from Product),\n\nsample1 as\n(select count(product_key) from Product)\n\nselect customer_id from Customer\ngroup by customer_id\nhaving sum(distinct product_key) = (select * from sample) and count(distinct product_key) = (select * from sample1);\n```
2
0
[]
1
customers-who-bought-all-products
Beats 97.73% of users with MySQL
beats-9773-of-users-with-mysql-by-hojiak-0b4l
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
hojiakbarmadaminov45
NORMAL
2024-02-22T03:43:14.061424+00:00
2024-02-22T03:43:14.061484+00:00
426
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: 852 ms\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n# Write your MySQL query statement below\nselect c.customer_id from customer c\ngroup by c.customer_id\nhaving count(distinct c.product_key ) = (select count(*) from product)\n\n```
2
0
['MySQL']
0
customers-who-bought-all-products
oracle based
oracle-based-by-user0021gw-vojw
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
user0021gW
NORMAL
2024-02-20T11:29:21.812696+00:00
2024-02-20T11:29:21.812729+00:00
919
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/* Write your PL/SQL query statement below */\nSELECT customer_id FROM Customer GROUP BY customer_id\nHAVING COUNT(distinct product_key) = (SELECT COUNT(product_key) FROM Product)\n```
2
0
['Oracle']
0
customers-who-bought-all-products
100 % || INTUITIVE & Well - Defined || SQL QUERY || AGGREGATION || Beats 98.95 % || Efficient.......
100-intuitive-well-defined-sql-query-agg-dfsd
Intuition\n Describe your first thoughts on how to solve this problem. \nSELECT customer_id --> Show customer_id from Customer Table...\nFROM Customer --> Assoc
ganpatinath07
NORMAL
2024-02-08T11:58:48.104339+00:00
2024-02-08T11:58:48.104370+00:00
1,405
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSELECT customer_id --> Show customer_id from Customer Table...\nFROM Customer --> Association from Customer Table...\nGROUP BY customer_id --> Grouping w.r.t. customer_id...\nHAVING COUNT(DISTINCT product_key) = (SELECT COUNT(product_key) --> Using Aggregation function COUNT to count product_key firstly for Customer Table then finally for Product Table & Check either they are equal or not equal...? if equal then consider...(Condition given in the problem)...\n# Approach\n<!-- Describe your approach to solving the problem. -->\nUsing Fundamentals of SQL...\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nSELECT customer_id \nFROM Customer \nGROUP BY customer_id \nHAVING COUNT(DISTINCT product_key) = (SELECT COUNT(product_key) \nFROM Product);\n```
2
0
['Database', 'MySQL']
1
customers-who-bought-all-products
✔✔✔tricky but easy solution with stepwise explanation⚡MS SQL Server | MySQL | Oracle | PostgreSQL
tricky-but-easy-solution-with-stepwise-e-puh0
Code - MS SQL Server | MySQL | Oracle | PostgreSQL\n\nSELECT c.customer_id\nFROM Customer AS c\nGROUP BY c.customer_id\nHAVING COUNT(DISTINCT c.product_key) = (
anish_sule
NORMAL
2024-01-25T07:25:38.754884+00:00
2024-02-27T14:01:03.171083+00:00
210
false
# Code - MS SQL Server | MySQL | Oracle | PostgreSQL\n```\nSELECT c.customer_id\nFROM Customer AS c\nGROUP BY c.customer_id\nHAVING COUNT(DISTINCT c.product_key) = (SELECT COUNT(product_key) FROM Product)\n```\n\n# Explanation\n- step 1\n```\nGROUP BY c.customer_id\n```\nfirst, group the records based on unique customer IDs\n\n- step 2\n```\nHAVING COUNT(DISTINCT c.product_key) = (SELECT COUNT(product_key) FROM Product)\n```\nthen, include only those customer IDs where the count of distinct product keys associated with each customer is equal to the total count of product keys in the "Product" table.
2
0
['MySQL', 'Oracle', 'MS SQL Server']
0
customers-who-bought-all-products
Easy Solution using Equality Operation
easy-solution-using-equality-operation-b-vvf5
Intuition\n Describe your first thoughts on how to solve this problem. \nThe Question looks on a bit moderate side . It can be solved by step by step. \n\n---\n
20250316.vinitsingh27
NORMAL
2023-12-30T13:20:37.652780+00:00
2023-12-30T13:20:37.652809+00:00
489
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe Question looks on a bit moderate side . It can be solved by step by step. \n\n---\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nStep by Step Solution \n**Step 1 :**\nGet the distinct product keys of every user present in the customer table and equate it with the total product keys present in the product table .\nif equal then give the customer id otherwise NO\n```\nhaving count(distinct product_key) = (select count(distinct product_key)\n```\n\n---\nOnce we get the distinct product keys our problem is easily solved .\n# Code\n```\n# Write your MySQL query statement below\n#30-12-2023\nselect customer_id\nfrom customer \ngroup by customer_id \nhaving count(distinct product_key) = (select count(distinct product_key) from product)\n```
2
0
['Database', 'MySQL']
0
customers-who-bought-all-products
2 Lines Very Easy to Understand + Explained Solution MySQL
2-lines-very-easy-to-understand-explaine-g0b0
Intuition\nUse first table (Customer) and count all from (Product) second table.\n# Approach\n1. We\'re selecting the customer_id from the Customer table.\n\n2.
rivia1000moon
NORMAL
2023-08-14T17:37:46.351216+00:00
2023-08-14T17:37:46.351248+00:00
790
false
# Intuition\n**Use first table (Customer) and count all from (Product) second table.**\n# Approach\n1. We\'re selecting the customer_id from the Customer table.\n\n2. The GROUP BY c.customer_id groups the results by customer ID.\n\n3. The HAVING clause filters the results to include only those customers who have purchased all the distinct products.\n\n4. COUNT(DISTINCT c.product_key) counts the distinct products bought by each customer.\n\n5. (SELECT COUNT(*) FROM Product) gets the total count of distinct products available in the Product table.\n\n\n# Code\n```\n# Write your MySQL query statement below\n\nSELECT c.customer_id FROM Customer c GROUP BY c.customer_id\nHAVING COUNT(DISTINCT c.product_key) = (SELECT COUNT(*) FROM Product);\n```
2
0
['MySQL']
1
customers-who-bought-all-products
Group BY ||
group-by-by-shivamj11-ey70
Intuition\n Describe your first thoughts on how to solve this problem. \nGroup by\n# Approach\n Describe your approach to solving the problem. \n1. GROUP BY cus
shivamj11
NORMAL
2023-05-08T16:27:04.543969+00:00
2023-05-08T16:27:04.544015+00:00
420
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nGroup by\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. GROUP BY customer_id\n2. Set the condition in HAVING clause. If count of distinct product key in Customer table grouped with customer_id is equal to Count of product key in Product table then it will determine that if customer has all the distinct product id with it.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n# Write your MySQL query statement below\\\nSELECT customer_id\nFROM Customer \nGROUP BY customer_id\nHAVING COUNT(DISTINCT product_key) = (SELECT COUNT(*) FROM Product)\n```
2
0
['MySQL']
0
customers-who-bought-all-products
MySQL Solution | Beats 43.72% | Sub-Query
mysql-solution-beats-4372-sub-query-by-v-028z
Code\n\nSELECT \n customer_id\nFROM Customer\nGROUP BY customer_id\nHAVING SUM(DISTINCT product_key) = (\n SELECT\n
vinamrgrover
NORMAL
2023-04-12T09:13:10.555957+00:00
2023-04-12T09:13:10.555995+00:00
1,635
false
# Code\n```\nSELECT \n customer_id\nFROM Customer\nGROUP BY customer_id\nHAVING SUM(DISTINCT product_key) = (\n SELECT\n SUM(product_key)\n FROM Product\n); \n```
2
0
['MySQL']
0
customers-who-bought-all-products
MySQL Simple Solution Without Subquery and CTE
mysql-simple-solution-without-subquery-a-p6y0
select customer_id\nfrom Customer\ngroup by 1\nhaving count(distinct product_key) = (select count(*) from Product);
Michael9527
NORMAL
2022-08-29T06:41:00.037546+00:00
2022-08-29T06:41:00.037591+00:00
930
false
select customer_id\nfrom Customer\ngroup by 1\nhaving count(distinct product_key) = (select count(*) from Product);
2
0
[]
1
customers-who-bought-all-products
MYSQL : HAVING COUNT(DISTINCT) + GROUP BY. Good Luck 👍✨
mysql-having-countdistinct-group-by-good-a9jh
\n# Write your MySQL query statement below\n\n/**\nTwo Tables: Customer/Product\n\nThere is no primary key for Customer table. It may contain duplicates.\nprodu
ashlyjoseph
NORMAL
2022-08-22T23:09:11.397800+00:00
2022-08-22T23:09:11.397847+00:00
618
false
```\n# Write your MySQL query statement below\n\n/**\nTwo Tables: Customer/Product\n\nThere is no primary key for Customer table. It may contain duplicates.\nproduct_key is a foreign key to Product table.\n\nproduct_key is the primary key column for Product table.\n\nPROBLEM: report the customer ids from the Customer table that bought all the products in the Product table.\n\nSTEPS\n HAVING COUNT(DISTINCT product_key) = (SELECT COUNT(*) FROM Product)\n\n*/\n\nSELECT\n customer_id\nFROM Customer\nGROUP BY customer_id\nHAVING COUNT(DISTINCT product_key) = (SELECT COUNT(*) FROM Product)\n```
2
0
['MySQL']
0
customers-who-bought-all-products
MYSQL NOT EXISTS WHERE NOT IN CTE
mysql-not-exists-where-not-in-cte-by-ann-70ri
WITH cte as(\nSELECT distinct customer_id as customer_id\nFROM Customer)\n\nSELECT cte.customer_id\nFROM cte\nWHERE NOT EXISTS(\nSELECT product_key FROM Product
Annezy
NORMAL
2022-08-14T15:35:39.376419+00:00
2022-08-14T15:35:39.376455+00:00
990
false
WITH cte as(\nSELECT distinct customer_id as customer_id\nFROM Customer)\n\nSELECT cte.customer_id\nFROM cte\nWHERE NOT EXISTS(\nSELECT product_key FROM Product\nWHERE product_key NOT IN(\nSELECT product_key FROM Customer c\nWHERE c.customer_id = cte.customer_id)\n)
2
0
[]
1
customers-who-bought-all-products
Oracle | Easy solution
oracle-easy-solution-by-tk-x-s421
\nselect customer_id\nfrom Customer\ngroup by customer_id\nhaving count(distinct product_key) = (select count(distinct product_key) from Product)\n
TK-X
NORMAL
2022-06-05T02:22:46.087799+00:00
2022-06-05T02:22:46.087826+00:00
371
false
```\nselect customer_id\nfrom Customer\ngroup by customer_id\nhaving count(distinct product_key) = (select count(distinct product_key) from Product)\n```
2
0
['Oracle']
1
customers-who-bought-all-products
simple MySQL solution
simple-mysql-solution-by-paipaijiao-syc0
select customer_id\nfrom customer\ngroup by customer_id\nhaving count(distinct product_key) = (select count(*) from product);
paipaijiao
NORMAL
2022-05-30T16:08:21.846813+00:00
2022-05-30T16:08:21.846861+00:00
426
false
select customer_id\nfrom customer\ngroup by customer_id\nhaving count(distinct product_key) = (select count(*) from product);
2
0
[]
0
customers-who-bought-all-products
Using CTEs faster than 90%
using-ctes-faster-than-90-by-nikhilgarak-7x4h
\n# Write your MySQL query statement below\n\nwith cte1 as (\n select count(product_key) as \'total_products\' from Product\n), cte2 as (\n select custome
nikhilgarakapati29
NORMAL
2021-12-02T14:06:32.696381+00:00
2021-12-02T14:06:32.696422+00:00
345
false
```\n# Write your MySQL query statement below\n\nwith cte1 as (\n select count(product_key) as \'total_products\' from Product\n), cte2 as (\n select customer_id, count(distinct product_key) as \'total\' from Customer\n group by customer_id\n)\n\nselect customer_id from cte2\nwhere total = (select * from cte1)\n```
2
0
[]
0
customers-who-bought-all-products
Faster Than 100%
faster-than-100-by-deleted_user-f27a
\'\'\'\nSELECT customer_id\nFROM Customer\nGROUP BY customer_id\nHAVING COUNT(DISTINCT product_key) = (SELECT COUNT(*) FROM Product);\n\'\'\'
deleted_user
NORMAL
2021-10-10T08:23:07.527897+00:00
2021-10-10T08:23:07.527935+00:00
354
false
\'\'\'\nSELECT customer_id\nFROM Customer\nGROUP BY customer_id\nHAVING COUNT(DISTINCT product_key) = (SELECT COUNT(*) FROM Product);\n\'\'\'
2
0
[]
0
customers-who-bought-all-products
MS SQL RIGHT JOIN + GROUP BY
ms-sql-right-join-group-by-by-nishantlee-yxnd
\nSELECT CUSTOMER_ID\nFROM CUSTOMER C\nRIGHT JOIN PRODUCT P\nON C.PRODUCT_KEY = P.PRODUCT_KEY\nGROUP BY CUSTOMER_ID \nHAVING COUNT(DISTINCT C.PRODUCT_KEY) = (SE
nishantleet17
NORMAL
2021-08-26T03:21:59.109466+00:00
2021-08-26T03:22:22.164366+00:00
200
false
```\nSELECT CUSTOMER_ID\nFROM CUSTOMER C\nRIGHT JOIN PRODUCT P\nON C.PRODUCT_KEY = P.PRODUCT_KEY\nGROUP BY CUSTOMER_ID \nHAVING COUNT(DISTINCT C.PRODUCT_KEY) = (SELECT COUNT(DISTINCT PRODUCT_KEY) FROM PRODUCT)\n```\nHello guys! Please do comment and let me know if you have a better approach in MS SQL. Thanks!!
2
0
['MS SQL Server']
0
customers-who-bought-all-products
faster than 98%
faster-than-98-by-jiemo-ixxr
\n\nSELECT\n customer_id\nFROM\n (SELECT \n customer_id,\n COUNT(DISTINCT(product_key)) AS c\n FROM Customer\n GROUP BY customer_i
jiemo
NORMAL
2021-07-21T05:20:00.816880+00:00
2021-07-21T05:20:00.816911+00:00
227
false
```\n\nSELECT\n customer_id\nFROM\n (SELECT \n customer_id,\n COUNT(DISTINCT(product_key)) AS c\n FROM Customer\n GROUP BY customer_id) A\nWHERE c = (SELECT COUNT(*) FROM product)\n```
2
0
[]
0
customers-who-bought-all-products
My simple MySQL solution
my-simple-mysql-solution-by-amazinggrace-zbrb
\nSELECT c.customer_id\nFROM Customer c\nGROUP BY c.customer_id\nHAVING COUNT(DISTINCT product_key) = (SELECT COUNT(DISTINCT product_key) FROM Product p)\n
AmazingGraceYYYY
NORMAL
2021-05-28T23:57:55.695749+00:00
2021-05-28T23:57:55.695776+00:00
213
false
```\nSELECT c.customer_id\nFROM Customer c\nGROUP BY c.customer_id\nHAVING COUNT(DISTINCT product_key) = (SELECT COUNT(DISTINCT product_key) FROM Product p)\n```
2
0
[]
0
customers-who-bought-all-products
【MySQL】Easy Understanding Solution
mysql-easy-understanding-solution-by-qia-9h53
\nselect customer_id\nfrom Customer\ngroup by customer_id\nhaving count(distinct product_key) = (select count(distinct product_key) from Product)\n
qiaochow
NORMAL
2021-05-04T20:01:24.802874+00:00
2021-05-04T20:01:24.802921+00:00
362
false
```\nselect customer_id\nfrom Customer\ngroup by customer_id\nhaving count(distinct product_key) = (select count(distinct product_key) from Product)\n```
2
0
['MySQL']
1
customers-who-bought-all-products
No subquery simple MySQL solution (count distinct)
no-subquery-simple-mysql-solution-count-1kl99
\nselect customer_id\nfrom customer \ngroup by customer_id \nhaving count(distinct product_key) = (select count(distinct product_key) from product)\n\n\n
ericleuchu
NORMAL
2021-04-19T17:04:34.443789+00:00
2021-04-19T17:04:34.443828+00:00
166
false
```\nselect customer_id\nfrom customer \ngroup by customer_id \nhaving count(distinct product_key) = (select count(distinct product_key) from product)\n```\n\n
2
0
[]
0
customers-who-bought-all-products
mySQL GROUP_CONCAT
mysql-group_concat-by-saikannan17-3z9g
This solution handles for the edge case when the Product table has different set of product_key than in the Customer table\n\nWITH prods AS (\n SELECT custom
saikannan17
NORMAL
2021-01-04T22:07:27.920496+00:00
2021-01-04T22:07:27.920527+00:00
111
false
This solution handles for the edge case when the Product table has different set of product_key than in the Customer table\n```\nWITH prods AS (\n SELECT customer_id,\n GROUP_CONCAT(DISTINCT product_key) as prods\n FROM Customer\n GROUP BY 1)\n \nSELECT customer_id\nFROM prods\nWHERE prods = (SELECT GROUP_CONCAT(DISTINCT product_key) FROM Product)\n```
2
0
[]
0
customers-who-bought-all-products
Not a simple comparison between the two count()
not-a-simple-comparison-between-the-two-xxu37
My solution cover the situation that the product_keys in customer table are out of those in product #table\n\nselect customer_id\nfrom ( \n select p.product_
mncoding
NORMAL
2020-10-05T22:10:45.511608+00:00
2020-10-05T22:10:45.511638+00:00
208
false
#My solution cover the situation that the product_keys in customer table are out of those in product #table\n\nselect customer_id\nfrom ( \n select p.product_key, c.customer_id\n from product p\n left join customer c on c.product_key = p.product_key ) t\ngroup by customer_id\nhaving count(distinct product_key) = (select count(*) from product)
2
0
[]
0
customers-who-bought-all-products
Easiest MSSQL Solution
easiest-mssql-solution-by-codingkida-yqy3
\nselect customer_id\nfrom customer\ngroup by customer_id\nhaving count(distinct product_key)=(select count(*) from product)\n
codingkida
NORMAL
2020-10-01T23:29:37.370845+00:00
2020-10-01T23:29:37.370877+00:00
167
false
```\nselect customer_id\nfrom customer\ngroup by customer_id\nhaving count(distinct product_key)=(select count(*) from product)\n```
2
1
[]
0
customers-who-bought-all-products
MS SQL SERVER
ms-sql-server-by-nazir_cinu-e6rx
\nselect customer_id from Customer group by customer_id\nhaving count(distinct product_key)=(select count(1) from Product)\n
nazir_cinu
NORMAL
2020-09-23T05:18:14.148019+00:00
2020-09-23T05:18:14.148071+00:00
170
false
```\nselect customer_id from Customer group by customer_id\nhaving count(distinct product_key)=(select count(1) from Product)\n```
2
0
[]
0
customers-who-bought-all-products
MySQL solutions using double NOT EXISTS. Compare counts is not accurate.
mysql-solutions-using-double-not-exists-z38ia
select customer_id from Customer c1\nwhere not exists\n\t(select * from Product p\n\twhere not exists\n\t\t(select * from Customer c2\n\t\twhere c2.product_key
ivyhou97
NORMAL
2020-03-19T02:49:07.453136+00:00
2020-03-19T02:49:07.453173+00:00
67
false
select customer_id from Customer c1\nwhere not exists\n\t(select * from Product p\n\twhere not exists\n\t\t(select * from Customer c2\n\t\twhere c2.product_key = p.product_key\n\t\tand c2.customer_id = c1.customer_id))\ngroup by customer_id
2
0
[]
2
customers-who-bought-all-products
simple solution
simple-solution-by-drfluid-hpzs
\nSELECT customer_id from Customer\ngroup by customer_id\nhaving count(distinct product_key) = \n(\nselect count(distinct product_key) from Product\n)\n\n
drfluid
NORMAL
2019-05-30T17:39:06.271556+00:00
2019-05-30T17:39:06.271601+00:00
237
false
```\nSELECT customer_id from Customer\ngroup by customer_id\nhaving count(distinct product_key) = \n(\nselect count(distinct product_key) from Product\n)\n\n```
2
0
[]
1
customers-who-bought-all-products
My MYSQL + MS SQL answers
my-mysql-ms-sql-answers-by-starry0731-rafg
My MySQL solution: Firstly, you need exclude the products which are not in the product list. Secondly, you need to delete the duplicates, which means one custom
starry0731
NORMAL
2019-05-18T16:43:28.856180+00:00
2019-05-18T16:43:28.856225+00:00
553
false
My MySQL solution: Firstly, you need exclude the products which are not in the product list. Secondly, you need to delete the duplicates, which means one customer buy the same product multiple times. Then you just need to make sure the number of distinct product each customer buys is equal to the number of distinct product on the list. \n\nMySQL:\n```\nSELECT customer_id\nFROM (\nSELECT DISTINCT *\nFROM Customer\nWHERE product_key IN (SELECT DISTINCT product_key FROM Product)) AS temp\nGROUP BY customer_id\nHAVING COUNT(DISTINCT product_key) = (SELECT COUNT(DISTINCT product_key) FROM Product)\n```\n\nMS SQL:\n```\n\nSELECT DISTINCT customer_id\nFROM (\n \nSELECT *, MAX(CT) OVER(PARTITION BY customer_id) AS MX\n \nFROM ( \nSELECT *, DENSE_RANK() OVER(PARTITION BY customer_id ORDER BY product_key) AS CT\nFROM Customer\nWHERE product_key IN (SELECT DISTINCT product_key FROM Product)) AS temp1\n \n ) AS temp2\nWHERE MX = (SELECT COUNT(DISTINCT product_key) FROM Product)\n```
2
0
[]
0
customers-who-bought-all-products
My solution with explanation
my-solution-with-explanation-by-tingtntn-4d1u
\n1\t\t\tselect customer_id\n2\t\t\tfrom\n3\t\t\t(\n4\t\t\t\tselect customer_id, product_key\n5\t\t\t\tfrom customer\n6\t\t\t\tgroup by customer_id, product_key
tingtntn
NORMAL
2019-05-18T07:49:56.999038+00:00
2019-05-22T00:45:06.849963+00:00
355
false
```\n1\t\t\tselect customer_id\n2\t\t\tfrom\n3\t\t\t(\n4\t\t\t\tselect customer_id, product_key\n5\t\t\t\tfrom customer\n6\t\t\t\tgroup by customer_id, product_key\n7\t\t\t) as temp\n8\t\t\tgroup by customer_id\n9\t\t\thaving count(*) = \n10\t\t\t(\n11\t\t\t select count(*)\n12\t\t\t from product\n13\t\t\t)\n```\n\nIt is not stated in the question whether the customer_id is a primary key of customer table. Therefore, my solution is a bit longer than others, because I consider the situation where we have duplicates, which is a person can buy the same products more than 1 time (results in two or more rows that are exactly the same).\n\nIn order to get rid of the duplicates, I have line 4-6.\n\nFeel free to ask if you have any questions.\n
2
1
[]
3
fraction-addition-and-subtraction
✅94.21%🔥Easy Solution🔥With Explanation🔥
9421easy-solutionwith-explanation-by-mra-0rf0
Intuition \u2712\uFE0F\n#### When we see the problem, the goal is to add and subtract fractions represented as a string expression. Since fractions have differe
MrAke
NORMAL
2024-08-23T00:55:35.481481+00:00
2024-08-23T01:00:40.520783+00:00
33,713
false
# Intuition \u2712\uFE0F\n#### When we see the problem, the goal is to add and subtract fractions represented as a string expression. Since fractions have different denominators, we\'ll need to manage this by finding a common denominator when adding or subtracting them. We also need to simplify the result to ensure it\'s in its irreducible form.\n\n---\n# Approach \uD83D\uDE80\n#### *`Extract the Fractions`*: First, we extract all the numerators and denominators from the string using regular expressions. This helps in breaking down the problem into smaller, manageable pieces.\n#### *`Initialize the Result`*: Start with a fraction represented by a numerator of 0 and a denominator of 1, which effectively means 0/1.\n#### *`Add/Subtract Fractions`*: Iterate over the extracted numerators and denominators, adding each fraction to the result using cross multiplication to handle the different denominators. This step effectively reduces multiple fraction operations to basic arithmetic.\n#### *`Simplify the Result`*: After computing the final fraction, simplify it by dividing the numerator and denominator by their greatest common divisor (GCD).\n#### *`Return the Fraction`*: Finally, return the result in the form of "numerator/denominator".\n\n\n---\n\n\n\n- # Time complexity:\n#### The time complexity is $$O(n)$$, where $$n$$ is the length of the input string. This is because we are processing each character of the input string to extract numerators and denominators and then performing a fixed amount of work for each fraction.\n\n\n- # Space complexity:\n#### The space complexity is $$O(1)$$, excluding the input and output, since we\'re only using a fixed amount of extra space for the numerator, denominator, and a few variables for calculations. The space used by the regular expression for extracting numbers is proportional to the number of fractions but remains constant with respect to the length of the input.\n---\n\n# Code\n```python []\nclass Solution:\n def fractionAddition(self, expression: str) -> str:\n nums = list(map(int, re.findall(r\'[+-]?\\d+\', expression)))\n numerator = 0\n denominator = 1\n \n for i in range(0, len(nums), 2):\n num, den = nums[i], nums[i + 1]\n numerator = numerator * den + num * denominator\n denominator *= den\n \n common_divisor = gcd(numerator, denominator)\n return f"{numerator // common_divisor}/{denominator // common_divisor}"\n```\n```C++ []\n#include <string>\n#include <vector>\nclass Solution {\npublic:\n string fractionAddition(string expression) {\n int numerator = 0, denominator = 1;\n int i = 0, n = expression.size();\n\n while (i < n) {\n int sign = 1;\n if (expression[i] == \'+\' || expression[i] == \'-\') {\n if (expression[i] == \'-\') sign = -1;\n i++;\n }\n\n int num = 0;\n while (i < n && isdigit(expression[i])) {\n num = num * 10 + (expression[i] - \'0\');\n i++;\n }\n num *= sign;\n\n i++;\n\n int den = 0;\n while (i < n && isdigit(expression[i])) {\n den = den * 10 + (expression[i] - \'0\');\n i++;\n }\n\n numerator = numerator * den + num * denominator;\n denominator *= den;\n\n int gcdVal = gcd(abs(numerator), denominator);\n numerator /= gcdVal;\n denominator /= gcdVal;\n }\n\n return to_string(numerator) + "/" + to_string(denominator);\n }\n};\n\n```\n```javascript []\nvar fractionAddition = function(expression) {\n let numerator = 0, denominator = 1;\n\n const regex = /([+-]?\\d+)\\/(\\d+)/g;\n let match;\n\n while ((match = regex.exec(expression)) !== null) {\n let num = parseInt(match[1]);\n let den = parseInt(match[2]);\n\n numerator = numerator * den + num * denominator;\n denominator *= den;\n\n let gcdVal = gcd(Math.abs(numerator), denominator);\n numerator /= gcdVal;\n denominator /= gcdVal;\n }\n\n return numerator + "/" + denominator;\n};\n\nfunction gcd(a, b) {\n while (b !== 0) {\n let temp = b;\n b = a % b;\n a = temp;\n }\n return a;\n}\n\n```\n```java []\nclass Solution {\n public String fractionAddition(String expression) {\n int numerator = 0, denominator = 1;\n \n Pattern pattern = Pattern.compile("([+-]?\\\\d+)/(\\\\d+)");\n Matcher matcher = pattern.matcher(expression);\n \n while (matcher.find()) {\n int num = Integer.parseInt(matcher.group(1));\n int den = Integer.parseInt(matcher.group(2));\n \n numerator = numerator * den + num * denominator;\n denominator *= den;\n \n int gcdVal = gcd(Math.abs(numerator), denominator);\n numerator /= gcdVal;\n denominator /= gcdVal;\n }\n \n return numerator + "/" + denominator;\n }\n \n private int gcd(int a, int b) {\n while (b != 0) {\n int temp = b;\n b = a % b;\n a = temp;\n }\n return a;\n }\n}\n\n```\n```C# []\npublic class Solution {\n public string FractionAddition(string expression) {\n int numerator = 0, denominator = 1;\n\n Regex regex = new Regex(@"([+-]?\\d+)\\/(\\d+)");\n MatchCollection matches = regex.Matches(expression);\n\n foreach (Match match in matches) {\n int num = int.Parse(match.Groups[1].Value);\n int den = int.Parse(match.Groups[2].Value);\n\n numerator = numerator * den + num * denominator;\n denominator *= den;\n\n int gcdVal = GCD(Math.Abs(numerator), denominator);\n numerator /= gcdVal;\n denominator /= gcdVal;\n }\n\n return $"{numerator}/{denominator}";\n }\n\n private int GCD(int a, int b) {\n while (b != 0) {\n int temp = b;\n b = a % b;\n a = temp;\n }\n return a;\n }\n}\n\n```\n---\n\n![Screenshot 2023-08-20 065922.png](https://assets.leetcode.com/users/images/cabb99f0-5b1d-465b-8c32-7d427d5c2bdc_1724374731.076821.png)\n\n
166
3
['Math', 'String', 'Python', 'C++', 'Java', 'Python3', 'JavaScript', 'C#']
18
fraction-addition-and-subtraction
Small simple C++/Java/Python
small-simple-cjavapython-by-stefanpochma-eypq
Keep the overall result in A / B, read the next fraction into a / b. Their sum is (Ab + aB) / Bb (but cancel their greatest common divisor).\n\nC++:\n\n stri
stefanpochmann
NORMAL
2017-05-21T09:17:10.149000+00:00
2018-09-15T22:35:46.795173+00:00
22,381
false
Keep the overall result in `A / B`, read the next fraction into `a / b`. Their sum is `(Ab + aB) / Bb` (but cancel their greatest common divisor).\n\n**C++:**\n\n string fractionAddition(string expression) {\n istringstream in(expression);\n int A = 0, B = 1, a, b;\n char _;\n while (in >> a >> _ >> b) {\n A = A * b + a * B;\n B *= b;\n int g = abs(__gcd(A, B));\n A /= g;\n B /= g;\n }\n return to_string(A) + '/' + to_string(B);\n }\n\n**Java:**\n\n public String fractionAddition(String expression) {\n Scanner sc = new Scanner(expression).useDelimiter("/|(?=[-+])");\n int A = 0, B = 1;\n while (sc.hasNext()) {\n int a = sc.nextInt(), b = sc.nextInt();\n A = A * b + a * B;\n B *= b;\n int g = gcd(A, B);\n A /= g;\n B /= g;\n }\n return A + "/" + B;\n }\n\n private int gcd(int a, int b) {\n return a != 0 ? gcd(b % a, a) : Math.abs(b);\n }\n\n**Python 3:**\nAdded this after @lee215 reminded me about Python 3's `math.gcd` with his solution in the comments.\n\n def fractionAddition(self, expression):\n ints = map(int, re.findall('[+-]?\\d+', expression))\n A, B = 0, 1\n for a in ints:\n b = next(ints)\n A = A * b + a * B\n B *= b\n g = math.gcd(A, B)\n A //= g\n B //= g\n return '%d/%d' % (A, B)
150
5
[]
21
fraction-addition-and-subtraction
Simple Python solution, no Fraction, and for people who are not familiar with Regular Expression.
simple-python-solution-no-fraction-and-f-zmv5
If you like it, please give me an upvote.\n\n def fractionAddition(self, expression):\n def gcd(i, j):\n while j: i, j = j, i%j\n
xuan__yu
NORMAL
2018-12-16T18:55:38.943491+00:00
2018-12-16T18:55:38.943540+00:00
3,676
false
If you like it, please give me an upvote.\n```\n def fractionAddition(self, expression):\n def gcd(i, j):\n while j: i, j = j, i%j\n return i\n lst = expression.replace("+", " +").replace("-", " -").split()\n A, B = 0, 1\n for num in lst:\n a, b = num.split("/")\n a, b = int(a), int(b)\n A = A*b+B*a\n B *= b\n devisor = gcd(A, B)\n A /= devisor; B /= devisor\n return str(A) + "/" + str(B)\n```
83
0
[]
5
fraction-addition-and-subtraction
Concise Java Solution
concise-java-solution-by-compton_scatter-6jsb
\npublic String fractionAddition(String expression) {\n String[] fracs = expression.split("(?=[-+])"); // splits input string into individual fractions\n
compton_scatter
NORMAL
2017-05-21T03:02:26.964000+00:00
2018-08-31T00:29:22.665225+00:00
10,034
false
```\npublic String fractionAddition(String expression) {\n String[] fracs = expression.split("(?=[-+])"); // splits input string into individual fractions\n String res = "0/1";\n for (String frac : fracs) res = add(res, frac); // add all fractions together\n return res;\n}\n\npublic String add(String frac1, String frac2) {\n int[] f1 = Stream.of(frac1.split("/")).mapToInt(Integer::parseInt).toArray(), \n f2 = Stream.of(frac2.split("/")).mapToInt(Integer::parseInt).toArray();\n int numer = f1[0]*f2[1] + f1[1]*f2[0], denom = f1[1]*f2[1];\n String sign = "";\n if (numer < 0) {sign = "-"; numer *= -1;}\n return sign + numer/gcd(numer, denom) + "/" + denom/gcd(numer, denom); // construct reduced fraction\n}\n\n// Computes gcd using Euclidean algorithm\npublic int gcd(int x, int y) { return x == 0 || y == 0 ? x + y : gcd(y, x % y); }\n```
42
1
[]
11
fraction-addition-and-subtraction
Python easy understood 2-line solution
python-easy-understood-2-line-solution-b-1lkv
Explanation\nSplit by + and -, and sum up all fractions.\n\nAlso you need to import libraries before the class\n\nfrom fractions import Fraction as f\n\n\n\nwit
lee215
NORMAL
2017-05-23T16:48:05.900000+00:00
2019-12-20T14:08:42.337574+00:00
5,743
false
## **Explanation**\nSplit by `+` and `-`, and sum up all fractions.\n\nAlso you need to import libraries before the class\n```\nfrom fractions import Fraction as f\n```\n<br>\n\nwithout regx\n```py\n def fractionAddition(self, exp):\n res = sum(map(f, re.findall(\'[+-]?\\d+/\\d+\', exp)))\n return \'%s/%s\' % (res.numerator, res.denominator)\n```\n<br>\n\nwith regx\n```py\n def fractionAddition(self, exp):\n res = sum(map(f, exp.replace(\'+\', \' +\').replace(\'-\', \' -\').split()))\n return \'%s/%s\' % (res.numerator, res.denominator)\n```
37
4
[]
10
fraction-addition-and-subtraction
Java Solution, Fraction Addition and GCD
java-solution-fraction-addition-and-gcd-fzj6x
\npublic class Solution {\n public String fractionAddition(String expression) {\n List<String> nums = new ArrayList<>();\n int i = 0, j = 0;\n
shawngao
NORMAL
2017-05-21T03:02:40.258000+00:00
2017-05-21T03:02:40.258000+00:00
4,873
false
```\npublic class Solution {\n public String fractionAddition(String expression) {\n List<String> nums = new ArrayList<>();\n int i = 0, j = 0;\n while (j <= expression.length()) {\n if (j == expression.length() || j != i && (expression.charAt(j) == '+' || expression.charAt(j) == '-')) {\n if (expression.charAt(i) == '+') {\n nums.add(expression.substring(i + 1, j));\n }\n else {\n nums.add(expression.substring(i, j));\n }\n \n i = j;\n }\n j++;\n }\n \n String result = "0/1";\n \n for (String num : nums) {\n result = add(result, num);\n }\n \n return result;\n }\n \n private String add(String s1, String s2) {\n String[] sa1 = s1.split("/");\n String[] sa2 = s2.split("/");\n int n1 = Integer.parseInt(sa1[0]);\n int d1 = Integer.parseInt(sa1[1]);\n int n2 = Integer.parseInt(sa2[0]);\n int d2 = Integer.parseInt(sa2[1]);\n \n int n = n1 * d2 + n2 * d1;\n int d = d1 * d2;\n \n if (n == 0) return "0/1";\n \n boolean isNegative = n * d < 0;\n n = Math.abs(n);\n d = Math.abs(d);\n int gcd = getGCD(n, d);\n \n return (isNegative ? "-" : "") + (n / gcd) + "/" + (d / gcd);\n }\n \n private int getGCD(int a, int b) {\n if (a == 0 || b == 0) return a + b; // base case\n return getGCD(b, a % b);\n }\n}\n```
23
1
[]
4
fraction-addition-and-subtraction
Simple Java Code ☠️
simple-java-code-by-abhinandannaik1717-vgsf
Code\njava []\nclass Solution {\n public String fractionAddition(String expression) {\n int n = expression.length();\n int c = 0;\n for(
abhinandannaik1717
NORMAL
2024-08-23T02:38:40.661872+00:00
2024-08-23T02:38:40.661891+00:00
4,877
false
# Code\n```java []\nclass Solution {\n public String fractionAddition(String expression) {\n int n = expression.length();\n int c = 0;\n for(int i=0;i<n;i++){\n if(expression.charAt(i)==\'/\'){\n c++;\n }\n }\n int[] num = new int[c];\n int[] den = new int[c];\n int[] s = new int[c];\n int i = 0;\n if(expression.charAt(0)==\'-\'){\n s[0]=-1;\n i=1;\n }\n else{\n s[0]=1;\n }\n int j=0,k=0,l=1;\n while (i < n) {\n if (expression.charAt(i) == \'-\' || expression.charAt(i) == \'+\') {\n if (expression.charAt(i) == \'-\') {\n s[l] = -1;\n } else {\n s[l] = 1;\n }\n l++;\n i++;\n }\n int nu=0;\n while (i < n && Character.isDigit(expression.charAt(i))) {\n nu=nu*10+(expression.charAt(i)-\'0\');\n i++;\n }\n num[j++] = nu;\n i++; \n int de = 0;\n while (i < n && Character.isDigit(expression.charAt(i))) {\n de=de* 10+(expression.charAt(i)-\'0\');\n i++;\n }\n den[k++]=de;\n }\n int lcm = den[0];\n for(i=1;i<c;i++){\n lcm = lcm*(den[i]/helper(lcm,den[i]));;\n }\n for(i=0;i<c;i++){\n int a = (lcm/den[i])*s[i];\n num[i]*=a;\n }\n int sum=0;\n for(i=0;i<c;i++){\n sum+=num[i];\n }\n int x = helper(Math.abs(sum),lcm);\n sum=sum/x;\n lcm=lcm/x;\n String str = Integer.toString(sum)+"/"+Integer.toString(lcm);\n return str;\n }\n public static int helper(int a,int b) {\n if (b==0)\n return a;\n return helper(b, a % b);\n }\n}\n```\n\n\n\n\n### Logic Breakdown\n\n1. **Count Fractions**:\n - Determine the number of fractions in the input string. This is done by counting the number of \'/\' characters in the string.\n\n2. **Initialize Data Structures**:\n - Create arrays to store:\n - **Numerators** of the fractions.\n - **Denominators** of the fractions.\n - **Signs** associated with each fraction (whether it\'s positive or negative).\n\n3. **Parse the Input String**:\n - Traverse the string to extract and parse:\n - **Signs**: Determine if the fraction is positive or negative.\n - **Numerators** and **Denominators**: Extract these values based on their position in the string.\n - Handle transitions between fractions and signs appropriately to fill the arrays.\n\n4. **Compute Least Common Multiple (LCM)**:\n - Calculate the LCM of all denominators. The LCM is required to find a common denominator so that all fractions can be added or subtracted correctly.\n\n5. **Convert Fractions to Common Denominator**:\n - Adjust each fraction so that its denominator matches the computed LCM. This involves:\n - Multiplying the numerator by the factor required to convert its denominator to the LCM.\n\n6. **Sum the Numerators**:\n - Sum all the numerators after they have been adjusted to the common denominator. The resulting value is the numerator of the final result.\n\n7. **Reduce the Resulting Fraction**:\n - Simplify the resulting fraction by dividing both the numerator and the denominator by their greatest common divisor (GCD). This ensures the fraction is in its simplest form.\n\n8. **Format the Result**:\n - Convert the simplified numerator and denominator into a string format representing the final fraction. If the numerator is zero, ensure the denominator is set to 1 to follow the problem\u2019s requirements.\n\n### Detailed Steps\n\n1. **Counting Fractions**:\n - Use the \'/\' character to count how many fractions are present in the expression.\n\n2. **Array Initialization**:\n - Initialize arrays for numerators, denominators, and signs based on the number of fractions.\n\n3. **Parsing the Expression**:\n - Traverse the string and use conditions to detect signs (\'+\' or \'-\') and extract numeric values for numerators and denominators.\n\n4. **LCM Calculation**:\n - Compute the LCM of all denominators to facilitate addition/subtraction. This involves multiplying and dividing based on GCD calculations.\n\n5. **Adjusting Fractions**:\n - For each fraction, adjust the numerator according to how much the denominator needs to be scaled up to match the LCM.\n\n6. **Summing Up**:\n - After adjusting, sum all the numerators to get the final numerator of the result.\n\n7. **Simplification**:\n - Divide the final numerator and denominator by their GCD to get the fraction in its simplest form.\n\n8. **Formatting**:\n - Convert the simplified result into a string format for output.\n\n\nLet\'s walk through the logic with an example: \n\n**Expression: `"1/2+1/3-1/4"`**\n\n### Step-by-Step Explanation\n\n1. **Count Fractions**:\n - There are three fractions in the expression (`"1/2"`, `"1/3"`, `"1/4"`).\n\n2. **Initialize Data Structures**:\n - Arrays to hold:\n - **Numerators**: `[1, 1, -1]` (for `"1/2"`, `"1/3"`, and `"1/4"`)\n - **Denominators**: `[2, 3, 4]`\n - **Signs**: `[1, 1, -1]` (signs corresponding to each fraction)\n\n3. **Parse the Input String**:\n - Traverse the string to extract the numerators, denominators, and signs:\n - `"1/2"`: Numerator = 1, Denominator = 2, Sign = `+`\n - `"1/3"`: Numerator = 1, Denominator = 3, Sign = `+`\n - `"1/4"`: Numerator = 1, Denominator = 4, Sign = `-`\n\n4. **Compute Least Common Multiple (LCM)**:\n - Calculate the LCM of the denominators `[2, 3, 4]`:\n - LCM of 2 and 3 is 6.\n - LCM of 6 and 4 is 12.\n - So, the LCM of `[2, 3, 4]` is `12`.\n\n5. **Convert Fractions to Common Denominator**:\n - Convert each fraction to have a denominator of 12:\n - `"1/2"`: To get denominator 12, multiply numerator by `12 / 2 = 6`. So, it becomes `6/12`.\n - `"1/3"`: To get denominator 12, multiply numerator by `12 / 3 = 4`. So, it becomes `4/12`.\n - `"1/4"`: To get denominator 12, multiply numerator by `12 / 4 = 3`. So, it becomes `-3/12` (considering the negative sign).\n\n6. **Sum the Numerators**:\n - Sum the numerators after converting to a common denominator:\n - `6 + 4 - 3 = 7`.\n - So, the resulting fraction is `7/12`.\n\n7. **Reduce the Resulting Fraction**:\n - The greatest common divisor (GCD) of `7` and `12` is `1`, so the fraction is already in its simplest form.\n\n8. **Format the Result**:\n - The final result is `"7/12"`.\n\n\n\n\n- **Time Complexity**: \\(O(n + c log d)\\), where \\(n\\) is the length of the input string, \\(c\\) is the number of fractions, and \\(d\\) is the magnitude of the denominators.\n- **Space Complexity**: \\(O(c)\\), where \\(c\\) is the number of fractions.\n\n\n\n
19
0
['Math', 'String', 'Simulation', 'Java']
4
fraction-addition-and-subtraction
Convert to fractions then do school Math||beats 100%
convert-to-fractions-then-do-school-math-apn4
Intuition\n Describe your first thoughts on how to solve this problem. \nThis question has 2 parts that must be done.\n1. Convert the expression to a sequnece
anwendeng
NORMAL
2024-08-23T00:35:56.773027+00:00
2024-08-23T09:48:21.798525+00:00
7,013
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis question has 2 parts that must be done.\n1. Convert the expression to a sequnece of fractions; in fact pairs of ints (hard way using many branches/ easy way using stringstream)\n2. Use school math to perform the fraction add/subtract such as xp/xq+yp/yq=p/q, do not forget to find gcd to divide p & q to get the irreducible fraction.\n\nC++, Python codes are made.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n[Please turn on English subtitles if necessary]\n[https://youtu.be/Al-FZ4wPmyY?si=sDCIyhLsvFQTfbHa](https://youtu.be/Al-FZ4wPmyY?si=sDCIyhLsvFQTfbHa)\n1. The fractions are hold in the container `fraction` in an array over int pairs.\n2. Define the function `convert(expression)` to convert expression to fraction; in the implementation, one can use 1-pass transversal to deal \'+\', \'-\',\'/\' and digit characters \'0\'-\'9\'.\n3. Define the function `add(x, y)` whose task is to do the fraction addition as follows\n```\nauto [xp, xq]=x;\nauto [yp, yq]=y;\nlong long q=xq*yq;// current common denominator\nlong long p=xp*yq+xq*yp;\nlong long g=gcd(p, q);\nreturn {p/g, q/g};//Fraction reduction\n```\n4. In `fractionAddition`, 1st call `fraction=convert(expression);` then use a loop to proceed `ans=add(ans, f)` for `f` in ``fraction`, the initial value for `f` is `{0,1}` which is corresponding to `0/1`.\n5. Convert the int pair `ans` to the answering format string.\n6. The other version for `convert` is using std::stringstream which is a good class dealing string & simplies the code.\n7. Python\'s convert is done with regex.\n# Why not compute LCM as the common denominator?\nFor 2 rationals `x=xp/xq, y=yp/yq`,\nIf taking `d=lcm(xq, yq)=xq*yq/gcd(xq, yq)`.\nThe result `p/q` for `x+y` (`x-y`) using `d` may be reducible or irreducible depending whether `gcd(p,q)>1` or not.\nIf irreducible, you\'ve luck; otherwise it needs 2 more divisions; the fraction is represented by the int pair `(p/g, p/g)`.\nThis method needs 2x computations for gcd & more multiplications/divisions; it\'s more expensive than my method.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$O(sz+|add|\\times fz)$ where $sz=|expression|, fz=|fraction|$. Each `add` operation needs 3 multiplications 1 add/subtract & 1 gcd (system builtin gcd, it is supposed having several divisions due to Euclidean algorithm) & 2 divisions. \n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$O(fz)$\n# Code|| C++ 0ms beats 100%\n```C++ []\nclass Solution {\npublic:\n using int2=pair<int, int>;\n void print(auto& f){\n for(auto& [x, y]: f) cout<<"("<<x<<","<<y<<")";\n cout<<endl;\n }\n\n vector<int2> convert(string& expression){\n vector<int2> fraction;\n int sz=expression.size(), x=0, sgn=1;\n char c=expression[0];\n switch(c){\n case \'+\':break;\n case \'-\': sgn=-1; break;\n default: x=c-\'0\';\n }\n int prev=0;\n for(int i=1; i<sz; i++){\n c=expression[i];\n while(c>=\'0\'){\n x=10*x+(c-\'0\');\n if (i==sz-1) break;\n c=expression[++i];\n // cout<<x<<", ";\n }\n switch(c){\n case \'+\':\n fraction.emplace_back(prev, x);\n sgn=1; \n x=0;\n break;\n case \'-\':\n fraction.emplace_back(prev, x); \n sgn=-1; \n x=0;\n break;\n case \'/\':\n prev=x*sgn;\n x=0;\n } \n }\n // dealing with i=sz-1\n fraction.emplace_back(prev, x);\n return fraction;\n }\n int2 add(int2& x, int2& y){\n auto [xp, xq]=x;\n auto [yp, yq]=y;\n long long q=xq*yq;\n long long p=xp*yq+xq*yp;\n long long g=gcd(p, q);\n return {p/g, q/g};\n }\n \n string fractionAddition(string& expression) {\n auto fraction=convert(expression);\n // print(fraction);\n int fz=fraction.size();\n int2 ans={0, 1};\n for(auto& f: fraction){\n ans=add(ans, f);\n }\n string s=to_string(ans.first)+"/"+to_string(ans.second);\n return s;\n }\n};\n```\n```Python []\nclass Solution:\n def fractionAddition(self, expression: str) -> str:\n def convert(exp):\n fraction=[]\n x, sgn, prev=0, 1, 0\n c=exp[0]\n if c==\'-\': sgn=-1\n elif c==\'+\': pass\n else: x=ord(c)-ord(\'0\')\n\n i, sz= 1, len(exp)\n while i<sz:\n c=exp[i]\n while ord(c)>=ord(\'0\'):\n x=10*x+(ord(c)-ord(\'0\'))\n if i==sz-1: break\n i+=1\n c=exp[i]\n\n if c==\'+\':\n fraction+=[(prev, x)]\n sgn=1\n x=0\n elif c==\'-\':\n fraction+=[(prev, x)]\n sgn=-1\n x=0\n elif c==\'/\':\n prev=x*sgn\n x=0\n i+=1\n fraction+=[(prev, x)]\n return fraction\n\n def add(x, y):\n q=x[1]*y[1]\n p=x[0]*y[1]+x[1]*y[0]\n g=gcd(p, q)\n return (p//g, q//g)\n\n fraction=convert(expression)\n ans=(0, 1)\n for f in fraction:\n ans=add(ans, f)\n return str(ans[0])+\'/\'+str(ans[1])\n \n\n \n```\n# C++ convert using stringstream\n```\n vector<int2> convert(string& expression) {\n vector<int2> fraction;\n stringstream ss(expression);\n char op;\n int num, denom;\n\n while (ss>>num>>op>>denom) {\n fraction.emplace_back(num, denom);\n // cout<<num<<","<<op<<denom<<endl;\n }\n return fraction;\n }\n```\n# Python convert using regex\n```\nimport re\ndef convert(expression):\n regex=r"([+-]?\\d+)/(\\d+)"\n\n matches=re.findall(regex, expression)\n\n fraction = [(int(num), int(den)) for num, den in matches]\n return fraction\n```
16
3
['Math', 'String', 'Simulation', 'C++', 'Python3']
7
fraction-addition-and-subtraction
C++ clean code
c-clean-code-by-codermonk-ar3e
int findgcd(int a, int b) {\n if(b == 0) return a;\n return findgcd(b, a%b);\n }\n void add(int& a, int& b, int c, int d) {\n int num
codermonk
NORMAL
2017-06-23T03:04:04.221000+00:00
2018-10-08T09:54:15.080029+00:00
2,470
false
int findgcd(int a, int b) {\n if(b == 0) return a;\n return findgcd(b, a%b);\n }\n void add(int& a, int& b, int c, int d) {\n int nume = a*d + c*b, deno = b*d;\n int gcd = findgcd(abs(nume), abs(deno));\n a = nume / gcd;\n b = deno / gcd;\n }\n string fractionAddition(string expression) {\n stringstream ss(expression);\n char op;\n int a, b, c, d;\n ss >> a; \n ss >> op; \n ss >> b;\n while(ss >> c) {\n ss >> op; \n ss >> d;\n add(a, b, c, d);\n }\n return to_string(a) + "/" + to_string(b);\n }
16
0
[]
4
fraction-addition-and-subtraction
Simple implementation | best explanation | beat 100% complexity || Easy Solution
simple-implementation-best-explanation-b-fn9a
Problem Overview\nThe problem involves performing arithmetic operations on fractions given as strings. The goal is to add these fractions and simplify the resul
Have-To-Do-Every-Thing
NORMAL
2024-08-23T04:03:05.239911+00:00
2024-08-23T06:41:41.313269+00:00
10,169
false
# Problem Overview\nThe problem involves performing arithmetic operations on fractions given as strings. The goal is to add these fractions and simplify the result. The task is to parse the input string to extract the fractions, compute their sum using a common denominator, and return the simplified result.\n\n# Intuition\nThe problem revolves around handling arithmetic operations on fractions represented in a string format. To solve this, we need to:\n\n- Extract Fractions: Parse the input string to extract each fraction\'s numerator and denominator.\n- Manage Denominators: Use a common denominator to sum up all fractions.\n- Simplify the Result: Simplify the resulting fraction using the greatest common divisor (GCD).\n- My initial thought is to treat the input as a series of fraction additions, compute a common denominator to facilitate the addition, and then simplify the result.\n\n## Solution Explanation\n* Parse the Input String:\n - Handle the input string to extract individual fractions. Each fraction is in the form of numerator/denominator, and we need to handle both positive and negative values.\n\n- Calculate the Common Denominator:\n - Compute the least common multiple (LCM) of all denominators to convert each fraction to have the same denominator.\n\n- Sum the Fractions:\n - Adjust the numerators according to the common denominator and sum them up.\n \n- Simplify the Fraction:\n - Use the greatest common divisor (GCD) to simplify the resulting fraction.\n- Return the Result:\n - Format the final result as a string in the form of `numerator/denominator`.\nExplanation of Edge Cases and Complexity\n\n# Edge Cases:\n * All fractions have different denominators, which requires accurate computation of the LCM.\n* Fractions with negative values are handled by parsing and adjusting signs correctly.\n\n# Complexity\n- Time complexity: The solution runs in $O(n)$ time, where $n$ is the length of the string. Parsing the string and computing LCM/GCD are linear in relation to the number of characters.\n\n- Space complexity: The space complexity is $O(1)$ since only a few extra variables are used regardless of the input size.\n\n# Code\n```cpp []\nclass Solution {\npublic:\n string fractionAddition(string s) {\n // Vectors to store the numerators and denominators separately\n std::vector<int> num;\n std::vector<int> den;\n\n int i = 0;\n int n = s.size();\n\n // If the string does not start with a negative sign, prepend a \'+\' sign\n if (s[0] != \'-\') {\n s = "+" + s;\n }\n\n // Parse the string to extract numerators and denominators\n while (i < n) {\n if (s[i] == \'/\') {\n // Finding the numerator\n int j = i - 1;\n int power = 0;\n int res = 0;\n\n // Traverse back to find the numerator before the \'/\' character\n while (\'0\' <= s[j] && s[j] <= \'9\') {\n int num = s[j] - \'0\';\n res = num * std::pow(10, power) + res;\n j--;\n power++;\n }\n\n // If the numerator is negative, multiply by -1\n if (s[j] == \'-\') {\n res = res * (-1);\n }\n num.push_back(res);\n\n // Finding the denominator\n j = i + 1;\n bool isneg = false;\n\n // Check if the denominator is negative (which should not occur in a valid fraction)\n if (s[j] == \'-\') {\n isneg = true;\n }\n res = 0;\n\n // Traverse forward to find the denominator after the \'/\' character\n while (\'0\' <= s[j] && s[j] <= \'9\') {\n int num = s[j] - \'0\';\n res = res * 10 + num;\n j++;\n }\n\n // If the denominator was found to be negative, multiply by -1\n if (isneg) {\n res = res * -1;\n }\n den.push_back(res);\n }\n i++;\n }\n\n // Calculate the least common multiple (LCM) of all denominators\n int lcm = 1;\n for (auto itr : den) {\n lcm = itr * lcm;\n }\n\n // Calculate the resulting numerator by summing up all numerators after adjusting them to the common denominator\n int numRes = 0;\n for (int i = 0; i < num.size(); i++) {\n numRes = numRes + (lcm / den[i]) * (num[i]);\n }\n\n // Find the greatest common divisor (GCD) of the resulting numerator and the LCM (which is now the denominator)\n int gcdVal = gcd(abs(numRes), lcm);\n \n // Simplify the fraction by dividing both the numerator and denominator by their GCD\n numRes /= gcdVal;\n lcm /= gcdVal;\n\n // Return the resulting fraction as a string in the form "numerator/denominator"\n return std::to_string(numRes) + "/" + std::to_string(lcm);\n }\n\nprivate:\n // Function to calculate the greatest common divisor (GCD) using the Euclidean algorithm\n int gcd(int a, int b) {\n while (b != 0) {\n int temp = b;\n b = a % b;\n a = temp;\n }\n return a;\n }\n};\n```\n```python []\nfrom fractions import Fraction\n\nclass Solution(object):\n def fractionAddition(self, expression):\n """\n :type expression: str\n :rtype: str\n """\n result = Fraction(0, 1)\n i = 0\n n = len(expression)\n \n while i < n:\n # Determine the sign of the current fraction\n sign = 1\n if expression[i] == \'-\':\n sign = -1\n i += 1\n elif expression[i] == \'+\':\n i += 1\n \n # Extract the numerator\n j = i\n while j < n and expression[j].isdigit():\n j += 1\n numerator = sign * int(expression[i:j])\n \n # Move past the \'/\' character\n i = j + 1\n \n # Extract the denominator\n j = i\n while j < n and expression[j].isdigit():\n j += 1\n denominator = int(expression[i:j])\n \n # Update the result using the current fraction\n result += Fraction(numerator, denominator)\n \n # Move to the next part of the expression\n i = j\n \n # Return the result as a string in the form of "numerator/denominator"\n return str(result.numerator) + "/" + str(result.denominator)\n\n\n```\n``` Java []\nimport java.math.BigInteger;\n\nclass Solution {\n public String fractionAddition(String expression) {\n BigInteger num = BigInteger.ZERO;\n BigInteger den = BigInteger.ONE;\n int i = 0;\n int n = expression.length();\n \n while (i < n) {\n int sign = 1;\n \n // Determine the sign of the current fraction\n if (expression.charAt(i) == \'-\') {\n sign = -1;\n i++;\n } else if (expression.charAt(i) == \'+\') {\n i++;\n }\n \n // Extract the numerator\n int j = i;\n while (j < n && Character.isDigit(expression.charAt(j))) {\n j++;\n }\n BigInteger numerator = new BigInteger(expression.substring(i, j)).multiply(BigInteger.valueOf(sign));\n \n // Move past the \'/\' character\n i = j + 1;\n \n // Extract the denominator\n j = i;\n while (j < n && Character.isDigit(expression.charAt(j))) {\n j++;\n }\n BigInteger denominator = new BigInteger(expression.substring(i, j));\n \n // Calculate the new denominator (LCM of current and new denominator)\n BigInteger commonDen = den.multiply(denominator).divide(den.gcd(denominator));\n \n // Adjust the numerators to the new common denominator and add them\n num = num.multiply(commonDen.divide(den)).add(numerator.multiply(commonDen.divide(denominator)));\n den = commonDen;\n \n // Move to the next part of the expression\n i = j;\n }\n \n // Simplify the fraction\n BigInteger gcd = num.gcd(den);\n num = num.divide(gcd);\n den = den.divide(gcd);\n \n return num.toString() + "/" + den.toString();\n }\n}\n\n\n```\n\n``` JavaScript []\n/**\n * @param {string} expression\n * @return {string}\n */\nvar fractionAddition = function(expression) {\n let num = 0;\n let den = 1;\n let i = 0;\n const n = expression.length;\n \n while (i < n) {\n let sign = 1;\n \n // Determine the sign of the current fraction\n if (expression[i] === \'-\') {\n sign = -1;\n i++;\n } else if (expression[i] === \'+\') {\n i++;\n }\n \n // Extract the numerator\n let j = i;\n while (j < n && isDigit(expression[j])) {\n j++;\n }\n let numerator = sign * parseInt(expression.substring(i, j));\n \n // Move past the \'/\' character\n i = j + 1;\n \n // Extract the denominator\n j = i;\n while (j < n && isDigit(expression[j])) {\n j++;\n }\n let denominator = parseInt(expression.substring(i, j));\n \n // Calculate the new denominator (LCM of current and new denominator)\n let commonDen = lcm(den, denominator);\n \n // Adjust the numerators to the new common denominator and add them\n num = num * (commonDen / den) + numerator * (commonDen / denominator);\n den = commonDen;\n \n // Move to the next part of the expression\n i = j;\n }\n \n // Simplify the fraction\n let gcdValue = gcd(Math.abs(num), den);\n num /= gcdValue;\n den /= gcdValue;\n \n return `${num}/${den}`;\n};\n\n// Helper function to check if a character is a digit\nfunction isDigit(char) {\n return char >= \'0\' && char <= \'9\';\n}\n\n// Helper function to compute the greatest common divisor (GCD)\nfunction gcd(a, b) {\n while (b !== 0) {\n let temp = b;\n b = a % b;\n a = temp;\n }\n return a;\n}\n\n// Helper function to compute the least common multiple (LCM)\nfunction lcm(a, b) {\n return (a * b) / gcd(a, b);\n}\n```
15
0
['Array', 'Math', 'String', 'Simulation', 'Python', 'C++', 'Java', 'JavaScript']
9
fraction-addition-and-subtraction
Easy C++ Solution with Video Explanation ✅
easy-c-solution-with-video-explanation-b-aiuh
Video Explanation\nhttps://youtu.be/yaiGPCQh5cY\n# Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem requires performing arit
prajaktakap00r
NORMAL
2024-08-23T02:32:11.752355+00:00
2024-08-23T02:32:11.752394+00:00
3,217
false
# Video Explanation\nhttps://youtu.be/yaiGPCQh5cY\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem requires performing arithmetic on fractions in a string format. To add or subtract fractions, they must be brought to a common denominator. Once this is achieved, the fractions can be added or subtracted by simply manipulating the numerators.\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. **Initialization:**\n\n- Start with a numerator of 0 and a denominator of 1. This represents the initial fraction as 0/1.\n- Use an index i to traverse the string expression.\n2. **Processing the String:**\n\n- Traverse the string character by character.\n- Handle the signs + and -. If a - is encountered, set sign to -1; otherwise, it remains 1.\n- Extract the numerator and denominator for each fraction in the string.\n- Use the formula to add or subtract fractions:\n\n- After each addition, simplify the resulting fraction by dividing both the numerator and denominator by their greatest common divisor (GCD).\n3.** Return the Result:**\n\n- Convert the final numerator and denominator into a string formatted as "numerator/denominator".\n# Complexity\n- Time complexity:$$O(n log K)$$\nwhere \uD835\uDC3E is the maximum value of the numerator or denominator encountered.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n string fractionAddition(string expression) {\n int numerator=0,denominator=1;\n int i=0;\n int n=expression.size();\n\n while(i<n){\n int sign=1;\n if(expression[i]==\'+\' || expression[i]==\'-\'){\n if(expression[i]==\'-\') sign=-1;\n i++;\n }\n\n int num=0;\n while(i<n && isdigit(expression[i])){\n num=num*10+(expression[i]-\'0\');\n i++;\n }\n num*=sign;\n i++;\n int den=0;\n while(i<n && isdigit(expression[i])){\n den=den*10+(expression[i]-\'0\');\n i++;\n }\n numerator=numerator*den+num*denominator;\n denominator*=den;\n\n int gcdVal=gcd(abs(numerator),denominator);\n numerator/=gcdVal;\n denominator/=gcdVal;\n\n }\n return to_string(numerator)+\'/\'+to_string(denominator);\n\n }\n};\n```
11
0
['C++']
5
fraction-addition-and-subtraction
[Python] Simple Parsing - with example
python-simple-parsing-with-example-by-ro-be8t
html5\n<b>Time Complexity: O(n + log(N&middot;D))</b> where n = expression.length and (N, D) are the unreduced numerator and common denominator &becaus; while-l
rowe1227
NORMAL
2021-03-26T19:10:05.263462+00:00
2021-03-26T19:48:27.877185+00:00
2,161
false
```html5\n<b>Time Complexity: O(n + log(N&middot;D))</b> where n = expression.length and (N, D) are the unreduced numerator and common denominator &becaus; while-loop and gcd\n<b>Space Complexity: O(n)</b> &becaus; num and den both scale with n and &becaus; when the first fraction is positive: expression = \'+\' + expression\n```\n\nWe will use the example `"-3/1+2/3-3/2+4/7+5/5"` while walking through the approach.\nSteps are also annotated within the code.\n\n**Approach:**\n\nFirst use a while-loop iterate over `expression` once.\nEach loop, we will extract one fraction from the expression:\n1. `expression[i]` will tell us if the numerator is positve or negative\n2. The following characters that are digits will make up the numerator.\n3. Skip the next character, it will always be `\'/\'`.\n4. The following characters that are digits will make up the denominator.\n\nAfter which the cycle either ends because we reached the end of `expression`\nor the cycle repeats starting with a new `+` or `-` denoting the sign of the next fraction.\n\nStore all of the numerators in a list `num` and all of the denominators in a separate list `den`.\nAn easy way to find a common divisor is to just multiply all of the denominators together.\nI.e: `den = [1, 3, 2, 7, 5] -> denominator = 1*3*2*7*5 = 210`\n\nThen multiply each numerator and denominator by `210 / den` so that it can be represented as `new_numerator / 210`.\n```html5\nnum = [-3, 2, -3, 4, 5] -> num = [-3/1, 2/3, -3/2, 4/7, 5/5] * 210 -> num = [-630, 140, -315, 120, 210]\nden = [ 1, 3, 2, 7, 5] -> den = [ 1/1, 3/3, 2/2, 7/7, 5/5] * 210 -> den = [ 210, 210, 210, 210, 210]\n```\n\nNow our numerators and denominators look like this:\n```html5\nnum = [-630, 140, -315, 120, 210]\nden = [ 210, 210, 210, 210, 210]\n```\n\nSince all of the fraction share the same denominator, we can combine them through addition:\n`numerator = -475`\n`denominator = 210`\n\nFinally, all that is left to do is to reduce the fraction.\nThis can be done by dividing the numerator and denominator by their greatest common divisor.\n`gcd(-475, 210) = 5 -> numerator = -475 / 5 = -95 -> denominator = 210 / 5 = 42`\n`gcd(-95, 42) = 1`\n\nHence, the final answer is `"numerator / denominator" = "-95/42"`.\n\n```python\nclass Solution:\n def fractionAddition(self, exp: str) -> str:\n \n if not exp:\n return "0/1"\n \n if exp[0] != \'-\':\n exp = \'+\' + exp\n \n # Parse the expression to get the numerator and denominator of each fraction\n num = []\n den = []\n pos = True\n i = 0\n while i < len(exp):\n # Check sign\n pos = True if exp[i] == \'+\' else False\n \n # Get numerator\n i += 1\n n = 0\n while exp[i].isdigit():\n n = n*10 + int(exp[i])\n i += 1\n num.append(n if pos else -n)\n \n # Get denominator\n i += 1\n d = 0\n while i < len(exp) and exp[i].isdigit():\n d = d*10 + int(exp[i])\n i += 1\n den.append(d)\n \n # Multiply the numerator of all fractions so that they have the same denominator\n denominator = functools.reduce(lambda x, y: x*y, den)\n for i,(n,d) in enumerate(zip(num, den)):\n num[i] = n * denominator // d\n \n # Sum up all of the numerator values\n numerator = sum(num)\n \n # Divide numerator and denominator by the greatest common divisor (gcd)\n g = math.gcd(numerator, denominator)\n numerator = numerator // g\n denominator = denominator // g\n \n return f"{numerator}/{denominator}"\n```
10
0
['Python', 'Python3']
1
fraction-addition-and-subtraction
Python | Greedy
python-greedy-by-khosiyat-uduz
see the Successfully Accepted Submission\n\n# Code\npython3 []\nimport re\nfrom math import gcd\n\nclass Solution:\n def fractionAddition(self, expression: s
Khosiyat
NORMAL
2024-08-23T06:45:54.975626+00:00
2024-08-23T06:45:54.975668+00:00
1,185
false
[see the Successfully Accepted Submission](https://leetcode.com/problems/fraction-addition-and-subtraction/submissions/1365428117/?envType=daily-question&envId=2024-08-23)\n\n# Code\n```python3 []\nimport re\nfrom math import gcd\n\nclass Solution:\n def fractionAddition(self, expression: str) -> str:\n # Find all the fractions in the expression, including signs\n fractions = re.findall(\'[+-]?\\\\d+/\\\\d+\', expression)\n \n # Initialize numerator and denominator of the result\n numerator = 0\n denominator = 1\n \n # Process each fraction\n for fraction in fractions:\n # Extract numerator and denominator\n num, denom = map(int, fraction.split(\'/\'))\n \n # Calculate the new numerator and denominator for the result\n numerator = numerator * denom + num * denominator\n denominator *= denom\n \n # Calculate GCD to simplify the fraction\n common_divisor = gcd(abs(numerator), denominator)\n \n # Simplify the fraction\n numerator //= common_divisor\n denominator //= common_divisor\n \n # Return the result as a string\n return f"{numerator}/{denominator}"\n\n\n```\n\n# Steps to Solve the Problem\n\n1. **Parse the Input String**: Extract all the fractions from the expression string.\n2. **Calculate the Least Common Denominator (LCD)**: For all the denominators in the expression, calculate the LCD so that we can easily add or subtract the fractions.\n3. **Convert Fractions to Have the Same Denominator**: Use the LCD to convert all fractions to have the same denominator.\n4. **Sum the Numerators**: Add or subtract the numerators of these fractions.\n5. **Simplify the Result**: Reduce the resulting fraction to its simplest form using the greatest common divisor (GCD).\n6. **Return the Result**: Ensure the result is in the correct format.\n\n# Explanation\n\n## Parsing Fractions\n\n- We use the regex pattern `\'[+-]?\\\\d+/\\\\d+\'` to match fractions including their signs.\n\n## Addition/Subtraction of Fractions\n\n- For each fraction, we update the overall numerator using the formula:\n \n \\[\n \\text{{new\\_numerator}} = \\text{{current\\_numerator}} \\times \\text{{denom}} + \\text{{num}} \\times \\text{{current\\_denominator}}\n \\]\n\n- The denominator is multiplied directly since we are summing fractions.\n\n## Simplifying the Result\n\n- We calculate the greatest common divisor (GCD) of the numerator and denominator to reduce the fraction.\n\n## Handling Edge Cases\n\n- The result automatically handles edge cases, such as resulting in a fraction of `0` (e.g., `"0/1"`).\n\n\n![image](https://assets.leetcode.com/users/images/b1e4af48-4da1-486c-bc97-b11ae02febd0_1696186577.992237.jpeg)
9
0
['Python3']
3
fraction-addition-and-subtraction
C++ 12 lines (GCD)
c-12-lines-gcd-by-votrubac-dko6
The initial fraction is 0/1 (n/d). We just need to read next fraction (nn/dd), normalize denominators between n/d and nn/dd (using GCD), and add/subtract the nu
votrubac
NORMAL
2017-05-21T03:39:16.726000+00:00
2017-05-21T03:39:16.726000+00:00
3,003
false
The initial fraction is 0/1 (n/d). We just need to read next fraction (nn/dd), normalize denominators between n/d and nn/dd (using GCD), and add/subtract the numerator (n +/- nn). In the end, we also need to use GCD to make the resulting fraction irreducible. \n```\nint GCD(int a, int b ){ return (b == 0) ? a : GCD(b, a % b); }\nstring fractionAddition(string s) {\n int n = 0, d = 1, p = 0, p1 = 0, p2 = 0;\n if (s[0] != '-') s = "+" + s;\n while (p < s.size()) {\n for (p1 = p + 1; s[p1] != '/'; ++p1);\n for (p2 = p1 + 1; p2 < s.size() && s[p2] != '+' && s[p2] != '-'; ++p2);\n auto nn = stoi(s.substr(p + 1, p1 - p - 1)), dd = stoi(s.substr(p1 + 1, p2 - p1 - 1));\n auto gcd = GCD(d, dd);\n n = n * dd / gcd + (s[p] == '-' ? -1 : 1) * nn * d / gcd;\n d *= dd / gcd;\n p = p2;\n } \n auto gcd = GCD(abs(n), d);\n return to_string(n / gcd) + "/" + to_string(d / gcd);\n}\n```
9
0
[]
3
fraction-addition-and-subtraction
Beats 79.94%!! Shortest code🔥!!BEST Python code🔥!!Token!🔥
beats-7994-shortest-codebest-python-code-fxlo
Intuition\nI couldn\'t belive this works.\n\n# Approach\nTo use findall from re and then sum the result and boom, shortest code.\n\n# Complexity\n### Time Compl
aijcoder
NORMAL
2024-08-23T09:15:27.824545+00:00
2024-08-23T09:15:27.824577+00:00
221
false
# Intuition\nI couldn\'t belive this works.\n\n# Approach\nTo use findall from re and then sum the result and boom, shortest code.\n\n# Complexity\n### Time Complexity\n\n1. **Regular Expression Matching**:\n - `re.findall(r\'[+-]?\\d+/\\d+\', expression)`: Scans through the entire string `expression` to find all matching substrings.\n - Time complexity: \\( O(n) \\), where \\( n \\) is the length of the input string.\n\n2. **Fraction Parsing**:\n - `Fraction(token)` for each match: Parsing each fraction takes constant time.\n - Time complexity: \\( O(m) \\), where \\( m \\) is the number of fractions found.\n\n3. **Summing Fractions**:\n - `sum(Fraction(token) for token in ...)`: Summing all fractions involves iterating through them.\n - Time complexity: \\( O(m) \\).\n\n Since \\( m \\) (number of fractions) is generally proportional to \\( n \\) (length of the input string), the overall time complexity is \\( O(n) \\).\n\n### Space Complexity\n\n1. **Space for Matches**:\n - Storing all matches from `re.findall` requires \\( O(m) \\) space.\n\n2. **Space for Fractions**:\n - Storing all `Fraction` objects requires \\( O(m) \\) space.\n\n3. **Space for Result**:\n - The final formatted string takes \\( O(1) \\) additional space.\n\n The overall space complexity is \\( O(m) \\), which simplifies to \\( O(n) \\) if the number of fractions \\( m \\) is proportional to the length of the input string \\( n \\).\n\n### Summary\n\n- **Time Complexity**: \\( O(n) \\)\n- **Space Complexity**: \\( O(n) \\)\n\n# Code\n```python3 []\nfrom fractions import Fraction\nimport re\nclass Solution:\n def fractionAddition(self, expression: str) -> str:\n fractions = [Fraction(token) for token in re.findall(r\'[+-]?\\d+/\\d+\', expression)]\n return f"{sum(fractions).numerator}/{sum(fractions).denominator}"\n\n\n```\nCould have been shorter
8
0
['Math', 'Shortest Path', 'Python3']
2
fraction-addition-and-subtraction
Extremely Simple C++ solution with explanation
extremely-simple-c-solution-with-explana-ex84
Stringstream is the easiest solution when signs and different numbers are to be extracted from a string. The advantage is that it automatically includes the \'+
shaunblaze21
NORMAL
2020-07-25T14:55:52.440256+00:00
2020-07-25T14:55:52.440298+00:00
920
false
Stringstream is the easiest solution when signs and different numbers are to be extracted from a string. The advantage is that it automatically includes the \'+\' or \'-\' sign. \nWe maintain \'a\' as our numerator and \'b\' as our denominator throughout the process. So a/b + c/d can be written as (a*d+b*c)/(bd) . Divide that by gcd to reduce it into smallest fraction. \nRest of the explanation is in code. Comment for doubt.\n```\nclass Solution {\npublic:\n string fractionAddition(string expression) {\n stringstream ss(expression);\n char op;\n int a,b,c,d;\n int num,den;\n ss>>a;ss>>op;ss>>b; //extracting the 1st 2 numbers\n while(ss>>c) //til we have the number\n {\n ss>>op; // op is the operator. which is \'/\' in our case\n ss>>d;\n num= a*d + b*c;\n den= b*d;\n a= num/__gcd(abs(num),abs(den));\n b= den/__gcd(abs(num),abs(den));\n }\n c=__gcd(abs(a),abs(b));\n a=a/c;\n b=b/c;\n return to_string(a)+\'/\'+to_string(b);\n }\n};\n```
8
0
['Math', 'C']
1
fraction-addition-and-subtraction
Python, Straightforward with Explanation
python-straightforward-with-explanation-wsdja
Evidently, we have 2 parts to our problem:\n Break our string into separate tokens which represent one fraction each\n Add the fractions together, keeping it in
awice
NORMAL
2017-05-21T03:10:07.900000+00:00
2017-05-21T03:10:07.900000+00:00
1,370
false
Evidently, we have 2 parts to our problem:\n* Break our string into separate tokens which represent one fraction each\n* Add the fractions together, keeping it in reduced form\n\nLet's decide how we want to break our string into tokens. Immediately after we see the second digit region, we know the first fraction must end there. To know whether we ended a digit region, we can look for a digit followed by a non-digit (or we are at the end of the string). Thus, every 2 digit regions, we'll report the token we've found. That token is something like "-10/3", which we'll convert into the integer tuple (-10, 3) representing fraction (-10 / 3).\n\n```\ndef fractionAddition(self, S):\n def iter_tokens(S):\n left = 0\n count = 0 \n for right, symbol in enumerate(S):\n if (right == len(S)-1 or \n symbol.isdigit() and not S[right + 1].isdigit()):\n count += 1\n if count % 2 == 0:\n yield map(int, S[left: right+1].split('/'))\n left = right + 1\n```\n\nTo add two fractions (a, b) and (c, d) together, we convert to a common denominator bd, so the fraction is (ad + bc, bd). To keep fraction (x, y) reduced, we should divide both the numerator and denominator by their greatest common divisor. We can finish as follows:\n\n```\n def gcd(a, b):\n if a == 0: return b\n return gcd(b%a, a)\n\n def add((an, ad), (bn, bd)):\n n = an * bd + bn * ad\n d = ad * bd\n g = gcd(n, d)\n return n/g, d/g\n\n return "{}/{}".format(*reduce(add, iter_tokens(S)))\n```\n\nWe could have also leveraged the fractions library to simplify our calculation.\n```\ndef fractionAddition(self, S):\n from fractions import Fraction\n ans = Fraction(0, 1)\n left = count = 0\n for right, symbol in enumerate(S):\n if (right == len(S) - 1 or \n symbol.isdigit() and not S[right + 1].isdigit()):\n count ^= 1\n if not count:\n ans += Fraction(*map(int, S[left: right+1].split('/')))\n left = right + 1\n \n return "{}/{}".format(ans.numerator, ans.denominator)\n```
7
0
[]
0
fraction-addition-and-subtraction
C++ Beats 100%!!! Pointwise explanation!
c-beats-100-pointwise-explanation-by-var-ubea
\n\n1. gcd Function:\nCalculates the greatest common divisor (GCD) of two numbers using the Euclidean algorithm.\n2. lcm Function:\nComputes the least common mu
Varun_Haralalka
NORMAL
2024-08-23T04:09:36.955796+00:00
2024-08-23T04:10:24.989409+00:00
499
false
![image.png](https://assets.leetcode.com/users/images/be4430a7-7467-4422-bb3a-8536b6f857f8_1724385933.063961.png)\n\n1. **gcd Function:**\nCalculates the greatest common divisor (GCD) of two numbers using the Euclidean algorithm.\n2. **lcm Function:**\nComputes the least common multiple (LCM) of two numbers using the formula: LCM(a, b) = (a / GCD(a, b)) * b.\n\n3. **reduce Function:**\nSimplifies a fraction by dividing both the numerator and the denominator by their GCD.\n\n4. **parseNumber Function:**\nExtracts a potentially multi-digit number from the string and handles its sign (positive or negative).\n\n5. **fractionAddition Function:**\nInitialization: Starts with an initial fraction of 0/1.\nParsing: Iterates through the input string, parsing each fraction one by one.\nLCM Calculation: Finds the LCM of the current and next denominators to bring them to a common base.\nNumerator Update: Updates the cumulative numerator based on the current operation (+ or -).\nDenominator Update: Sets the denominator to the LCM.\nSimplification: After processing all fractions, simplifies the final result.\nReturn: Outputs the result as a string in the form "numerator/denominator".\n\n\n# Please Upvote!\n# Code\n```cpp []\nclass Solution {\n int gcd(int a, int b) {\n if (b == 0) return a;\n return gcd(b, a % b);\n }\n \n int lcm(int a, int b) {\n return (a / gcd(a, b)) * b;\n }\n \n void reduce(int &a, int &b) {\n int gcd_ab = gcd(abs(a), b);\n a /= gcd_ab;\n b /= gcd_ab;\n }\n int parseNumber(const string &expression, int &i) {\n int sign = 1;\n if (expression[i] == \'-\') {\n sign = -1;\n i++;\n } \n else if (expression[i] == \'+\')\n i++;\n int num = 0;\n while (i < expression.length() && isdigit(expression[i])) {\n num = num * 10 + (expression[i] - \'0\');\n i++;\n }\n return sign * num;\n }\n \npublic:\n string fractionAddition(string expression) {\n int numerator = 0, denominator = 1;\n for (int i = 0; i < expression.length();) {\n int num = parseNumber(expression, i);\n i++; // Skip the \'/\'\n int den = parseNumber(expression, i);\n int LCM = lcm(denominator, den);\n numerator = numerator * (LCM / denominator) + num * (LCM / den);\n denominator = LCM;\n }\n if (numerator == 0) return "0/1";\n reduce(numerator, denominator);\n return to_string(numerator) + "/" + to_string(denominator);\n }\n};\n```
6
0
['C++']
1
fraction-addition-and-subtraction
Overcomplicated, unreadable, manually implemented solution - No explanation provided
overcomplicated-unreadable-manually-impl-0hjo
\xAF\\\(\u30C4)/\xAF\n\n\nclass Solution:\n def fractionAddition(self, expression: str) -> str:\n denominator = 1\n numerator = 0\n for
v1dhn
NORMAL
2024-02-11T19:04:15.832087+00:00
2024-02-11T19:04:15.832132+00:00
674
false
# \xAF\\\\\\_(\u30C4)_/\xAF\n\n```\nclass Solution:\n def fractionAddition(self, expression: str) -> str:\n denominator = 1\n numerator = 0\n for i in range(1,len(expression)):\n if expression[i-1]==\'/\':\n temp = int(expression[i])\n if i+1<len(expression):\n if temp == 1 and expression[i+1]==\'0\':\n temp = 10\n denominator*=temp\n for j in range(len(expression)-1):\n if expression[j+1]==\'/\':\n temp1 = int(expression[j])\n temp2 = int(expression[j+2])\n sign = 1\n if j>0:\n sign = -1 if expression[j-1]==\'-\' else 1\n if temp1==0 and expression[j-1]==\'1\':\n temp1 = 10\n if temp1==10 and j-2>=0:\n if expression[j-2]==\'-\':\n sign = -1\n if j+3<len(expression):\n if temp2 == 1 and expression[j+3]==\'0\':\n temp2 = 10\n numerator +=\\\n (sign*temp1*(denominator//temp2))\n a,b = numerator,denominator\n while b:\n a, b = b, a % b\n hcf = a\n ans = str(numerator//hcf)+\'/\'+str(denominator//hcf)\n return ans\n```
6
0
['Python3']
2
fraction-addition-and-subtraction
✅Cpp || Faster than 100% || LCM and HCF
cpp-faster-than-100-lcm-and-hcf-by-feroc-rq13
\nclass Solution {\npublic:\n int gcd(int a,int b){\n if(a%b==0) return b;\n return gcd(b,a%b);\n }\n int getNum(int &i,string exp){ //
ferociouscentaur
NORMAL
2022-08-15T01:36:08.087946+00:00
2022-08-15T01:36:08.087971+00:00
1,045
false
```\nclass Solution {\npublic:\n int gcd(int a,int b){\n if(a%b==0) return b;\n return gcd(b,a%b);\n }\n int getNum(int &i,string exp){ // returns numerator\n string temp = "";\n while(exp[i]!=\'/\'){\n temp+=exp[i];\n i++;\n }\n return stoi(temp);\n \n }\n int getDen(int &i,string exp){ // returns denominator\n string temp = "";\n while(i<exp.size() and (exp[i]!=\'+\' and exp[i]!=\'-\')){\n temp+=exp[i];\n i++;\n }\n int num = stoi(temp);\n return num;\n \n }\n string fractionAddition(string exp) {\n int s1 = 1;\n int i =0 ;\n if(exp[0]==\'-\'){\n s1 = -1;\n i++;\n }\n int num1 = getNum(i,exp);\n i++;\n int den1 = getDen(i,exp);\n while(i<exp.size()){\n int s2 = exp[i]==\'-\'?-1:1;\n i++;\n int num2 = getNum(i,exp);\n i++;\n int den2 = getDen(i,exp);\n int lcm = (den2*den1)/gcd(den1,den2);\n num1 = (s1*num1*(lcm/den1) + s2*num2*(lcm/den2));\n den1 = lcm;\n if(num1<0){\n s1 = -1;\n num1 *=-1;\n }\n else{\n s1 = 1;\n }\n }\n int gc = gcd(num1,den1);\n if(gc>1){\n num1 = num1/gc;\n den1 = den1/gc;\n }\n string ans = "";\n ans += s1==-1?"-":"";\n ans += to_string(num1);\n ans += "/";\n ans += to_string(den1);\n return ans;\n \n }\n};\n```
6
0
['C++']
0
fraction-addition-and-subtraction
Simple and Easy CPP Code!💯✅☮️
simple-and-easy-cpp-code-by-siddharth_si-8mg3
Code\ncpp []\nclass Solution {\npublic:\n string fractionAddition(string exp) {\n int num=0;\n int deno=1;\n int i=0;\n int n=exp
siddharth_sid_k
NORMAL
2024-09-01T14:19:55.553277+00:00
2024-09-01T14:19:55.553308+00:00
62
false
# Code\n```cpp []\nclass Solution {\npublic:\n string fractionAddition(string exp) {\n int num=0;\n int deno=1;\n int i=0;\n int n=exp.size();\n while(i<n)\n {\n int curnum=0;\n int curdeno=0;\n bool isneg=(exp[i]==\'-\');\n if(exp[i]==\'+\' or exp[i]==\'-\')\n {\n i++;\n }\n while(i<n and isdigit(exp[i]))\n {\n int val=exp[i]-\'0\';\n curnum=(curnum*10)+val;\n i++;\n }\n i++;\n if(isneg==true)\n {\n curnum*=-1;\n }\n while(i<n and isdigit(exp[i]))\n {\n int val=exp[i]-\'0\';\n curdeno=(curdeno*10)+val;\n i++;\n }\n num=(num*curdeno)+(curnum*deno);\n deno=deno*curdeno;\n }\n int gcd=abs(__gcd(num,deno));\n num/=gcd;\n deno/=gcd;\n return to_string(num)+"/"+to_string(deno);\n }\n};\n```\n\n# Intuition\nThe goal is to parse the string representation of the expression, add or subtract fractions accordingly, and return the result in its simplest form. \n\n# Approach\n\n1. **Initialization:** The code`initializes` `num to 0` and `den to 1`, which will hold the numerator and denominator of the cumulative fraction, respectively.\n2. **Iteration:** The loop iterates through the string exp to parse each fraction:\n- It first checks if the current character is a sign (\'+\' or \'-\'). `If` it\'s a `\'-\'`, it sets a `flag to true` to indicate that the numerator should be negative.\n- It then `parses the numerator` (curnum) by iterating through the digits.\n- The loop continues to `parse the denominator` (curdeno) after encountering the \'/\' character.\n3. **Fraction Arithmetic:** The code updates the cumulative numerator (num) and denominator (den) by using the `formula` for adding fraction\n$$`newNum=num\xD7curdeno+curnum\xD7den`$$ \n$$`newDen=den\xD7curdeno`$$\n4. **Simplification:** After processing all fractions, the code calculates the greatest common divisor (GCD) of the numerator and denominator using the` __gcd function`, and then divides both by the GCD to simplify the fraction.\n5. **Return:** Finally, the code converts the simplified numerator and denominator to strings and concatenates them in the form `"numerator/denominator"` to return as the result.\n\n# Example Walkthrough\n\n### Input: `"-1/2+1/2"`\n\n### Step-by-Step Execution:\n\n1. **Initialization**:\n - `num = 0`, `den = 1`, `i = 0`, `n = 7` (length of the string).\n\n2. **First Fraction Parsing** (`"-1/2"`):\n - **Check for Sign**:\n - The character at `exp[0]` is `\'-\'`, so `flag` is set to `true`.\n - `i` is incremented to 1 to move to the next character.\n - **Numerator Parsing**:\n - The character at `exp[1]` is `\'1\'`, which is a digit.\n - `curnum` is updated to 1 (as `curnum = 0 * 10 + 1`).\n - Since `flag` is `true`, `curnum` is multiplied by `-1`, making `curnum = -1`.\n - `i` is incremented to 2, and the character at `exp[2]` is `\'/\'`, so the loop for the numerator ends.\n - **Denominator Parsing**:\n - `i` is incremented to 3, and the character at `exp[3]` is `\'2\'`, which is a digit.\n - `curdeno` is updated to 2 (as `curdeno = 0 * 10 + 2`).\n - `i` is incremented to 4, and the loop for the denominator ends.\n - **Fraction Arithmetic**:\n - Now, `num = 0 * 2 + (-1) * 1 = -1`.\n - `den = 1 * 2 = 2`.\n\n3. **Second Fraction Parsing** (`"+1/2"`):\n - **Check for Sign**:\n - The character at `exp[4]` is `\'+\'`, so `flag` is set to `false`.\n - `i` is incremented to 5 to move to the next character.\n - **Numerator Parsing**:\n - The character at `exp[5]` is `\'1\'`, which is a digit.\n - `curnum` is updated to 1 (as `curnum = 0 * 10 + 1`).\n - Since `flag` is `false`, `curnum` remains positive.\n - `i` is incremented to 6, and the character at `exp[6]` is `\'/\'`, so the loop for the numerator ends.\n - **Denominator Parsing**:\n - `i` is incremented to 7, and the character at `exp[7]` is `\'2\'`, which is a digit.\n - `curdeno` is updated to 2 (as `curdeno = 0 * 10 + 2`).\n - `i` is incremented to 8, and the loop for the denominator ends.\n - **Fraction Arithmetic**:\n - Now, `num = -1 * 2 + 1 * 2 = 0`.\n - `den = 2 * 2 = 4`.\n\n4. **Simplification**:\n - The GCD of `num` (0) and `den` (4) is calculated using `__gcd(0, 4)`, which is 4.\n - Simplified `num` and `den` are `0 / 4 = 0` and `4 / 4 = 1`.\n\n5. **Result**:\n - The final result is `"0/1"`.\n\n### Output:\nThe code correctly simplifies `"-1/2 + 1/2"` to `"0/1"`.\n\n# Complexity\n- Time complexity:`O(n)`,where n is the length of the input string exp. This is because the code iterates through the string once to parse the numerators and denominators.\n\n- Space complexity:`O(1)`, as the algorithm only uses a constant amount of extra space for variables like num, den, curnum, and curdeno.\n\n
5
0
['C++']
0
fraction-addition-and-subtraction
Java Solution for Fraction Addition and Subtraction Problem
java-solution-for-fraction-addition-and-d8jhe
Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem involves adding and subtracting fractions, which requires finding a common
Aman_Raj_Sinha
NORMAL
2024-08-23T03:33:19.497554+00:00
2024-08-23T03:33:19.497574+00:00
1,605
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem involves adding and subtracting fractions, which requires finding a common denominator and combining the numerators accordingly. The key steps involve parsing the input expression, extracting the numerators and denominators, and then performing the arithmetic operations. The result must be returned as an irreducible fraction.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1.\tInitialization:\n\t\u2022\tStart with an initial fraction of 0/1.\n2.\tParsing:\n\t\u2022\tIterate through the expression, extracting each fraction by identifying the numerator and denominator. Handle signs (+ or -) appropriately to ensure the correct operation (addition or subtraction).\n3.\tCombining Fractions:\n\t\u2022\tFor each fraction extracted, update the overall result by:\n\t \u2022\tFinding a common denominator between the current fraction and the result.\n\t \u2022\tAdjusting the numerators accordingly and summing them up.\n\t\u2022\tSimplify the fraction after each operation by dividing the numerator and denominator by their greatest common divisor (GCD).\n4.\tReturning the Result:\n\t\u2022\tOnce all fractions have been processed, return the final result as a string in the format numerator/denominator.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\u2022\tO(n): The time complexity is linear relative to the length of the input string. Each character is processed exactly once.\n\u2022\tO(1): The GCD computation for each fraction addition takes constant time since the numerator and denominator values are bounded by small integers.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\u2022\tO(1): The space complexity is constant because the solution uses a fixed amount of extra space for variables (numerator, denominator, and gcd). No additional space scales with the input size.\n\n# Code\n```java []\nclass Solution {\n public String fractionAddition(String expression) {\n int numerator = 0, denominator = 1;\n int i = 0, n = expression.length();\n\n while (i < n) {\n int sign = 1;\n if (expression.charAt(i) == \'+\' || expression.charAt(i) == \'-\') {\n sign = expression.charAt(i) == \'-\' ? -1 : 1;\n i++;\n }\n\n int num = 0;\n while (i < n && Character.isDigit(expression.charAt(i))) {\n num = num * 10 + (expression.charAt(i) - \'0\');\n i++;\n }\n\n num *= sign;\n\n i++; // Skip the \'/\'\n \n int denom = 0;\n while (i < n && Character.isDigit(expression.charAt(i))) {\n denom = denom * 10 + (expression.charAt(i) - \'0\');\n i++;\n }\n\n numerator = numerator * denom + num * denominator;\n denominator *= denom;\n\n int gcd = gcd(Math.abs(numerator), denominator);\n numerator /= gcd;\n denominator /= gcd;\n }\n\n return numerator + "/" + denominator;\n }\n\n private int gcd(int a, int b) {\n return b == 0 ? a : gcd(b, a % b);\n }\n\n}\n```
5
0
['Java']
4
fraction-addition-and-subtraction
592: Space 98%, Solution with step by step explanation
592-space-98-solution-with-step-by-step-u2qoz
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n1. Split the expression string into individual fractions using the re.fin
Marlen09
NORMAL
2023-03-16T03:47:11.155371+00:00
2023-03-16T03:47:11.155415+00:00
1,020
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Split the expression string into individual fractions using the re.findall function and regular expression pattern [+-]?\\d+/\\d+. This will match any fraction in the expression, including negative fractions and fractions with whole numbers.\n2. Convert the list of fraction strings to a list of tuples (numerator, denominator) by splitting each fraction string at the \'/\' character and converting the resulting strings to integers using map.\n3. Find the least common multiple (LCM) of the denominators of all the fractions. To do this, initialize lcm to 1 and loop through each fraction, multiplying lcm by the fraction\'s denominator divided by the greatest common divisor of lcm and the fraction\'s denominator.\n4. Add the numerators of all the fractions, after multiplying each numerator by a factor so that the fractions all have a common denominator equal to the lcm found in step 3.\n5. Simplify the resulting fraction by dividing the numerator and denominator by their greatest common divisor using the math.gcd function.\n6. Return the simplified fraction as a string in the format numerator/denominator.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def fractionAddition(self, expression: str) -> str:\n # Split the expression into individual fractions\n fractions = re.findall(\'[+-]?\\d+/\\d+\', expression)\n \n # Convert the fractions to a list of tuples (numerator, denominator)\n fractions = [tuple(map(int, fraction.split(\'/\'))) for fraction in fractions]\n \n # Find the LCM of the denominators\n lcm = 1\n for fraction in fractions:\n lcm = lcm * fraction[1] // math.gcd(lcm, fraction[1])\n \n # Add the numerators after multiplying by the appropriate factor\n numerator_sum = sum([fraction[0] * (lcm // fraction[1]) for fraction in fractions])\n \n # Simplify the fraction\n gcd = math.gcd(numerator_sum, lcm)\n numerator = numerator_sum // gcd\n denominator = lcm // gcd\n \n # Return the simplified fraction as a string\n return str(numerator) + \'/\' + str(denominator)\n\n```
5
0
['Math', 'String', 'Simulation', 'Python', 'Python3']
1
fraction-addition-and-subtraction
two python solutions
two-python-solutions-by-fhqplzj-pfve
method 1:\n\n def fractionAddition(self, expression):\n """\n :type expression: str\n :rtype: str\n """\n import re\n\n
fhqplzj
NORMAL
2017-11-06T15:06:55.143000+00:00
2018-09-02T16:54:39.511183+00:00
1,253
false
method 1:\n```\n def fractionAddition(self, expression):\n """\n :type expression: str\n :rtype: str\n """\n import re\n\n def gcd(x, y):\n while y:\n x, y = y, x % y\n return x\n\n nums = map(int, re.findall('[+-]?\\d+', expression))\n A, B = 0, 1\n for a, b in zip(nums[::2], nums[1::2]):\n A = A * b + B * a\n B *= b\n g = gcd(A, B)\n A /= g\n B /= g\n return '{0}/{1}'.format(A, B)\n```\nmethod 2:\n```\n def fractionAddition1(self, expression):\n """\n :type expression: str\n :rtype: str\n """\n from fractions import Fraction\n result = sum(map(Fraction, expression.replace('+', ' +').replace('-', ' -').split()))\n return '{0}/{1}'.format(result.numerator, result.denominator)
5
0
[]
0
fraction-addition-and-subtraction
✅ Regex Builder Approach
regex-builder-approach-by-eleev-lekq
Solution\nswift []\nimport RegexBuilder\n\nstruct Solution {\n @_optimize(speed)\n func fractionAddition(_ expression: String) -> String { \n
eleev
NORMAL
2024-08-23T08:07:17.405592+00:00
2024-08-24T13:42:11.772824+00:00
77
false
# Solution\n```swift []\nimport RegexBuilder\n\nstruct Solution {\n @_optimize(speed)\n func fractionAddition(_ expression: String) -> String { \n let regex = Regex {\n Capture {\n Optionally("-")\n OneOrMore(.digit)\n }\n "/"\n Capture {\n OneOrMore(.digit)\n }\n }\n\n let fractions = expression\n .matches(of: regex)\n .compactMap { (Int($0.1) ?? 1, Int($0.2) ?? 1) }\n var (num, denom) = (0, 1)\n\n func gcd(_ x: Int, _ y: Int) -> Int {\n x == 0 ? y : gcd(y % x, x)\n }\n\n for fraction in fractions {\n let (cnum, cdenom) = fraction\n num = num * cdenom + cnum * denom\n denom *= cdenom\n let common = abs(gcd(num, denom))\n num /= common\n denom /= common\n }\n return "\\(num)/\\(denom)"\n }\n}\n\n```
4
0
['Math', 'String', 'Swift']
1
fraction-addition-and-subtraction
String Fractions Simplified: Using LCM and GCD | Java & C++ | [Video Solution]
string-fractions-simplified-using-lcm-an-szz3
Intuition, approach, and complexity discussed in video solution in detail.\nhttps://youtu.be/jUq3a7Nkbo0\n\n# Code\njava []\nclass Solution {\n public String
Lazy_Potato_
NORMAL
2024-08-23T06:59:13.216222+00:00
2024-08-23T06:59:13.216250+00:00
934
false
# Intuition, approach, and complexity discussed in video solution in detail.\nhttps://youtu.be/jUq3a7Nkbo0\n\n# Code\n```java []\nclass Solution {\n public String fractionAddition(String expression) {\n Map<Integer, List<int[]>> denoToSignNumMp = new HashMap<>();\n int size = expression.length();\n char expChrs[] = expression.toCharArray();\n int indx = 0;\n int sign = 1;\n\n while (indx < size) {\n char currChar = expChrs[indx];\n if (currChar == \'-\') {\n sign = -1;\n indx++;\n } else if (currChar == \'+\') {\n sign = 1;\n indx++;\n }\n\n int num = 0, deno = 0;\n boolean slashFound = false;\n\n while (indx < size && expChrs[indx] != \'+\' && expChrs[indx] != \'-\') {\n if (expChrs[indx] == \'/\') {\n slashFound = true;\n indx++;\n continue;\n }\n\n if (!slashFound) {\n num = num * 10 + (expChrs[indx] - \'0\');\n } else {\n deno = deno * 10 + (expChrs[indx] - \'0\');\n }\n\n indx++;\n }\n\n if (deno == 0) deno = 1;\n denoToSignNumMp.putIfAbsent(deno, new ArrayList<>());\n denoToSignNumMp.get(deno).add(new int[]{num, sign});\n }\n\n int lcm = 1;\n for (var deno : denoToSignNumMp.keySet()) {\n lcm = getLcm(lcm, deno);\n }\n\n int totalNum = 0;\n for (var entry : denoToSignNumMp.entrySet()) {\n var deno = entry.getKey();\n for (var numEntry : entry.getValue()) {\n int num = numEntry[0], numSign = numEntry[1];\n totalNum += (numSign * num * (lcm / deno));\n }\n }\n int gcd = gcd(Math.abs(totalNum), lcm);\n totalNum /= gcd;\n lcm /= gcd;\n\n if (lcm == 1) return totalNum + "/1";\n return totalNum + "/" + lcm;\n }\n\n private int getLcm(int a, int b) {\n return (a * b) / gcd(a, b);\n }\n\n private int gcd(int a, int b) {\n while (b != 0) {\n int temp = b;\n b = a % b;\n a = temp;\n }\n return a;\n }\n}\n\n```\n```cpp []\nclass Solution {\npublic:\n string fractionAddition(string expression) {\n unordered_map<int, vector<pair<int, int>>> denoToSignNumMp;\n int size = expression.length();\n vector<char> expChrs(expression.begin(), expression.end());\n int indx = 0;\n int sign = 1;\n\n while (indx < size) {\n char currChar = expChrs[indx];\n if (currChar == \'-\') {\n sign = -1;\n indx++;\n } else if (currChar == \'+\') {\n sign = 1;\n indx++;\n }\n\n int num = 0, deno = 0;\n bool slashFound = false;\n\n while (indx < size && expChrs[indx] != \'+\' && expChrs[indx] != \'-\') {\n if (expChrs[indx] == \'/\') {\n slashFound = true;\n indx++;\n continue;\n }\n\n if (!slashFound) {\n num = num * 10 + (expChrs[indx] - \'0\');\n } else {\n deno = deno * 10 + (expChrs[indx] - \'0\');\n }\n\n indx++;\n }\n\n if (deno == 0) deno = 1;\n denoToSignNumMp[deno].emplace_back(num, sign);\n }\n\n int lcm = 1;\n for (const auto& denoEntry : denoToSignNumMp) {\n lcm = getLcm(lcm, denoEntry.first);\n }\n\n int totalNum = 0;\n for (const auto& entry : denoToSignNumMp) {\n int deno = entry.first;\n for (const auto& numEntry : entry.second) {\n int num = numEntry.first, numSign = numEntry.second;\n totalNum += (numSign * num * (lcm / deno));\n }\n }\n int gcdValue = gcd(abs(totalNum), lcm);\n totalNum /= gcdValue;\n lcm /= gcdValue;\n\n if (lcm == 1) return to_string(totalNum) + "/1";\n return to_string(totalNum) + "/" + to_string(lcm);\n }\n\nprivate:\n int getLcm(int a, int b) {\n return (a * b) / gcd(a, b);\n }\n\n int gcd(int a, int b) {\n while (b != 0) {\n int temp = b;\n b = a % b;\n a = temp;\n }\n return a;\n }\n};\n```
4
0
['Math', 'String', 'Simulation', 'C++', 'Java']
2
fraction-addition-and-subtraction
🎯 Accurate Fraction Addition with GCD Optimization💯
accurate-fraction-addition-with-gcd-opti-tohi
Intuition\nWhen adding fractions, the key challenge is finding a common denominator and then summing the numerators. Simplifying the resulting fraction by divid
mugeshking33
NORMAL
2024-08-23T05:52:24.388291+00:00
2024-08-23T05:52:24.388325+00:00
366
false
# Intuition\nWhen adding fractions, the key challenge is finding a common denominator and then summing the numerators. Simplifying the resulting fraction by dividing both the numerator and denominator by their greatest common divisor (GCD) ensures the answer is in its simplest form.\n\n# Approach\n1. Parsing the Input: Iterate through the input string to extract each fraction. Identify the numerator and denominator, accounting for possible signs (+ or -).\n2. Common Denominator: As fractions are parsed, calculate a common denominator and adjust numerators accordingly to sum them up.\n3. Simplify the Fraction: After summing the fractions, use the GCD to simplify the result.\n4. Return the Result: Format the simplified fraction as a string.\n\n# Complexity\n- Time complexity:\n The time complexity is O(n), where n is the length of the input string, since we need to parse through the string and perform arithmetic operations.\n\n- Space complexity:\nThe space complexity is O(1), since the space used is independent of the input size.\n# Code\n```java []\nclass Solution {\n private static int gcd(int a, int b) {\n if (b == 0) return a;\n return gcd(b, a % b);\n }\n public String fractionAddition(String e) {\n int ne = 0, de = 1,n = e.length(), i = 0;\n while (i < n) {\n int sign = e.charAt(i) == \'-\' ? -1 : 1;\n int num = 0, den = 0;\n i=(e.charAt(i) == \'-\' || e.charAt(i) == \'+\')?i+1:i;\n while (i < n && e.charAt(i) >= \'0\' && e.charAt(i) <= \'9\') \n num = num * 10 + (e.charAt(i++) - \'0\');\n num *= sign;\n i++;\n while (i < n && e.charAt(i) >= \'0\' && e.charAt(i) <= \'9\') \n den = den * 10 + (e.charAt(i++) - \'0\');\n ne = ne * den + num * de;\n de *= den;\n int gcd = gcd(Math.abs(ne), de);\n ne /= gcd;\n de /= gcd;\n }\n return ne == 0 ? "0/1" : ne + "/" + de;\n }\n}\n```\n```python []\nclass Solution:\n def fractionAddition(self, expression: str) -> str:\n def gcd(a: int, b: int) -> int:\n while b:\n a, b = b, a % b\n return a \n ne = 0 # Numerator\n de = 1 # Denominator\n i = 0\n n = len(expression)\n while i < n:\n sign = -1 if expression[i] == \'-\' else 1\n i += (expression[i] == \'-\' or expression[i] == \'+\')\n num = 0\n while i < n and expression[i].isdigit():\n num = num * 10 + int(expression[i])\n i += 1\n num *= sign\n i += 1 \n den = 0\n while i < n and expression[i].isdigit():\n den = den * 10 + int(expression[i])\n i += 1\n ne = ne * den + num * de\n de *= den\n g = gcd(abs(ne), de)\n ne //= g\n de //= g\n return "0/1" if ne == 0 else f"{ne}/{de}"\n```\n```C []\nint gcd(int a, int b) {\n while (b != 0) {\n int temp = b;\n b = a % b;\n a = temp;\n }\n return a;\n}\nchar* fractionAddition(const char *expression) {\n static char result[100]; // Allocate a buffer to hold the result\n int ne = 0; // Numerator of the result\n int de = 1; // Denominator of the result\n int i = 0, num = 0, den = 0, sign;\n while (expression[i] != \'\\0\') {\n sign = (expression[i] == \'-\') ? -1 : 1;\n if (expression[i] == \'-\' || expression[i] == \'+\') i++;\n num = 0;\n while (expression[i] >= \'0\' && expression[i] <= \'9\') \n num = num * 10 + (expression[i++] - \'0\');\n num *= sign;\n i++; // Skip the \'/\' character\n den = 0;\n while (expression[i] >= \'0\' && expression[i] <= \'9\') \n den = den * 10 + (expression[i++] - \'0\');\n ne = ne * den + num * de;\n de *= den;\n int g = gcd(abs(ne), de);\n ne /= g;\n de /= g;\n }\n if (ne == 0) {\n sprintf(result, "0/1");\n } else {\n sprintf(result, "%d/%d", ne, de);\n }\n return result;\n}\n\n\n```\n
4
0
['Math', 'String', 'C', 'Rejection Sampling', 'Simulation', 'Python', 'Java', 'JavaScript']
2
fraction-addition-and-subtraction
C# Solution for Fraction Addition and Subtraction Problem
c-solution-for-fraction-addition-and-sub-6s3i
Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem involves adding and subtracting fractions, which can be simplified by first
Aman_Raj_Sinha
NORMAL
2024-08-23T03:37:24.682149+00:00
2024-08-23T03:37:24.682183+00:00
199
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem involves adding and subtracting fractions, which can be simplified by first finding a common denominator for all the fractions and then summing the numerators accordingly. This approach allows us to handle all the fractions simultaneously rather than incrementally updating the result.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1.\tParse the Expression:\n\t\u2022\tIterate through the string to identify and extract the numerators and denominators of each fraction. Store these values separately in two lists: numerators and denominators.\n2.\tFind the Least Common Multiple (LCM):\n\t\u2022\tTo sum fractions with different denominators, first find the LCM of all the denominators. This LCM will serve as a common denominator for the final addition.\n3.\tAdjust Numerators to the Common Denominator:\n\t\u2022\tFor each fraction, adjust its numerator so that its denominator matches the common denominator. This is done by multiplying the numerator by the necessary factor (i.e., LCM divided by the fraction\u2019s denominator).\n4.\tSum the Numerators:\n\t\u2022\tSum up all the adjusted numerators, which gives the total numerator for the final fraction with the common denominator.\n5.\tSimplify the Result:\n\t\u2022\tSimplify the final fraction by dividing both the numerator and the denominator by their Greatest Common Divisor (GCD).\n6.\tReturn the Result:\n\t\u2022\tReturn the result as a string in the format numerator/denominator.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\u2022\tO(n): The time complexity is linear relative to the length of the input string n. Parsing the expression, finding the LCM, adjusting numerators, and summing them are all done in a single pass through the input.\n\u2022\tO(m \\cdot log(D)): The complexity for finding the GCD and LCM involves logarithmic operations relative to the denominators. Here, m is the number of fractions, and D represents the magnitude of the denominators.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\u2022\tO(m): The space complexity is linear relative to the number of fractions m. The space is primarily used to store the lists of numerators and denominators.\n\u2022\tO(1) for other auxiliary variables, as the LCM and GCD calculations do not require additional space proportional to the input size.\n\n# Code\n```csharp []\npublic class Solution {\n public string FractionAddition(string expression) {\n List<int> numerators = new List<int>();\n List<int> denominators = new List<int>();\n\n int i = 0;\n while (i < expression.Length) {\n int sign = 1;\n if (expression[i] == \'-\' || expression[i] == \'+\') {\n sign = expression[i] == \'-\' ? -1 : 1;\n i++;\n }\n\n int num = 0;\n while (i < expression.Length && char.IsDigit(expression[i])) {\n num = num * 10 + (expression[i] - \'0\');\n i++;\n }\n\n i++; // skip the \'/\'\n\n int denom = 0;\n while (i < expression.Length && char.IsDigit(expression[i])) {\n denom = denom * 10 + (expression[i] - \'0\');\n i++;\n }\n\n numerators.Add(sign * num);\n denominators.Add(denom);\n }\n\n int commonDenominator = 1;\n foreach (int denom in denominators) {\n commonDenominator = lcm(commonDenominator, denom);\n }\n\n int totalNumerator = 0;\n for (int j = 0; j < numerators.Count; j++) {\n totalNumerator += numerators[j] * (commonDenominator / denominators[j]);\n }\n\n int gcdValue = gcd(Math.Abs(totalNumerator), commonDenominator);\n return (totalNumerator / gcdValue) + "/" + (commonDenominator / gcdValue);\n }\n\n private int gcd(int a, int b) {\n return b == 0 ? a : gcd(b, a % b);\n }\n\n private int lcm(int a, int b) {\n return a / gcd(a, b) * b;\n }\n}\n```
4
0
['C#']
0
fraction-addition-and-subtraction
Fraction Addition and Subtraction - Easy Explanation with the Gcd - Super Understandable Solution
fraction-addition-and-subtraction-easy-e-h93w
Intuition\n Describe your first thoughts on how to solve this problem. \nTo split the string first based on the operator and then in that string,split it based
RAJESWARI_P
NORMAL
2024-08-23T02:34:52.174860+00:00
2024-08-23T02:34:52.174894+00:00
267
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo split the string first based on the operator and then in that string,split it based on "/" as numerator and denominator.\n\nnumerator value is initially set to 0 and the denominator value is initially set to 1.\n\nAnd then iteratively perform operation by adding "0/1" with the incoming numbers.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1) Split the string based on the operators.\n2) Initialize the numerator to 0 and the denominator to 1.\n3) Iterate through the loop for each of the string.\n4) In the iteration,split the string based on "/" as current numerator and for current denominator(In our case: num and denom).\n5) Then perform addition or subtraction operation by adding with "0/1" with incoming numbers by numerator as numerator*denom + num*denominator as denominator as denominator*=denom.\n6) Find the gcd of absolute value of numerator and the denominator by using gcd() function.\n7) Then divide the numerator by gcd and denominator by gcd.\n8) Iterate the loop until all the number strings.\n9) Then return the answer as numberator+"/"+denominator.\n\n**gcd function**: \n This function get two values : numerator and denominator as a and b.\n This function repeats the iteration till b is not equal to 0.\n At each iteration,change the value of a to b and then b to a%b.\n Then a is the gcd when b becomes 0.\n\n# Complexity\nTime complexity:**O(n)**. \n\n n -> length of the input string.\n- The time complexity for splitting the expression is **O(n)**.\n- The loop through the fraction contributes **O(mlogC)** due to GCD Calculations.\n- m is constant and small,the denominator factor is the length of the String so overall complexity is **O(n+logC)**.\n- But in the constraints,maximum value of m is given as 10,the time complexity is essentially **O(n)**.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\nSpace complexity:**O(1)**.\n\n- Since extra space is used for storing the number as string but m is given as small and constant.Hence the overall space complexity is \n**O(1)** -> constant time complexity.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n private int gcd(int a,int b)\n {\n while(b!=0)\n {\n int temp=b;\n b=a%b;\n a=temp;\n }\n return a;\n }\n public String fractionAddition(String expression) {\n String[] fractions=expression.split("(?=[+-])");\n int numerator=0,denominator=1;\n for(String frac:fractions)\n {\n String[] parts=frac.split("/");\n int num=Integer.parseInt(parts[0]);\n int denom=Integer.parseInt(parts[1]);\n numerator=numerator*denom+num*denominator;\n denominator*=denom;\n\n int gcd=gcd(Math.abs(numerator),denominator);\n\n numerator/=gcd;\n denominator/=gcd;\n }\n return numerator+"/"+denominator;\n }\n}\n```
4
0
['Math', 'String', 'Simulation', 'Java']
0
fraction-addition-and-subtraction
Python Elegant & Short | RegEx | Two lines
python-elegant-short-regex-two-lines-by-t9pl2
\timport re\n\tfrom fractions import Fraction\n\n\n\tclass Solution:\n\t\t"""\n\t\tTime: O(n)\n\t\tMemory: O(n)\n\t\t"""\n\n\t\tFRACTION_PATTERN = r\'([+-]?[^
Kyrylo-Ktl
NORMAL
2022-09-01T19:46:42.005438+00:00
2022-09-01T20:01:24.858220+00:00
1,084
false
\timport re\n\tfrom fractions import Fraction\n\n\n\tclass Solution:\n\t\t"""\n\t\tTime: O(n)\n\t\tMemory: O(n)\n\t\t"""\n\n\t\tFRACTION_PATTERN = r\'([+-]?[^+-]+)\'\n\t\t\n\t\t# First solution\n\t\tdef fractionAddition(self, expression: str) -> str:\n\t\t\tresult_fraction = Fraction(0)\n\n\t\t\tfor exp in re.findall(self.FRACTION_PATTERN, expression):\n\t\t\t\tn, d = map(int, exp.split(\'/\'))\n\t\t\t\tresult_fraction += Fraction(n, d)\n\n\t\t\treturn f\'{result_fraction.numerator}/{result_fraction.denominator}\'\n\n\t\t# Second solution\n\t\tdef fractionAddition(self, expression: str) -> str:\n\t\t\tresult_fraction = sum(\n\t\t\t\t(Fraction(*map(int, exp.split(\'/\'))) for exp in re.findall(self.FRACTION_PATTERN, expression)),\n\t\t\t\tFraction(0)\n\t\t\t)\n\t\t\treturn f\'{result_fraction.numerator}/{result_fraction.denominator}\'\n
4
0
['Python', 'Python3']
0
fraction-addition-and-subtraction
C# short solution (Regex, Linq and GCD)
c-short-solution-regex-linq-and-gcd-by-e-qbby
Felt like having fun with LINQ.\n\n\nusing System.Text.RegularExpressions;\n\npublic class Solution\n{\n public string FractionAddition(string expression)\n
evilkos
NORMAL
2017-05-21T18:49:40.207000+00:00
2017-05-21T18:49:40.207000+00:00
407
false
Felt like having fun with LINQ.\n\n```\nusing System.Text.RegularExpressions;\n\npublic class Solution\n{\n public string FractionAddition(string expression)\n {\n return string.Join("/", \n Regex.Matches(expression, @"(-?\\d+)\\/(\\d+)").OfType<Match>()\n .Select(m => new[] { int.Parse(m.Groups[1].Value), int.Parse(m.Groups[2].Value) })\n .Aggregate(new[] { 0, 1 }, (p, c) => Normalize(p[0] * c[1] + p[1] * c[0], p[1] * c[1])));\n }\n\n private int Gcd(int a, int b) => a == 0 ? Math.Abs(b) : Gcd(b % a, a);\n\n private int[] Normalize(int n, int d) => new[] { n / Gcd(n, d), d / Gcd(n, d) };\n}\n```\n\n1. First we convert the string expression to an enumerable of fractions. Each fraction is an int[2] array. Regular expression expects fractions like "n/d" where n could be negative. Plus signs are disregarded completely, we don't need them:\n```\nRegex.Matches(expression, @"(-?\\d+)\\/(\\d+)").OfType<Match>()\n .Select(m => new[] { int.Parse(m.Groups[1].Value), int.Parse(m.Groups[2].Value) })\n```\n2. Next we aggregate the results (this Linq function's analogue in javascript is called `reduce`, for example). We always start from value 0/1 and then sum it with the first number using the fraction rules from school: `a/b + c/d = (a*d + b*c) / b * d`. After that we use the `Normalize` helper function, which finds the greatest common denominator for numerator and denominator and uses it to normalize our current fraction.\n```\n.Aggregate(new[] { 0, 1 }, (p, c) => Normalize(p[0] * c[1] + p[1] * c[0], p[1] * c[1])));\n```\n3. After the last number was added, the resulting nominator and denominator are joined with "/" in between them with: ```string.Join```
4
0
[]
1
fraction-addition-and-subtraction
EASY PYTHON SOLN FOR BEGINNERS
easy-python-soln-for-beginners-by-rahulm-2o11
Class Definition and Method Setup:\n\nA class Solution is defined with a method fractionAddition that takes a string e representing a fraction expression.\nHand
RAHULMOST
NORMAL
2024-10-15T03:31:29.436844+00:00
2024-10-15T03:31:29.436867+00:00
44
false
Class Definition and Method Setup:\n\nA class Solution is defined with a method fractionAddition that takes a string e representing a fraction expression.\nHandling Negative Signs and Splitting:\n\nAll - signs are replaced with +- to manage negative fractions, and the string is split by + to form a list of fractions.\nSumming the Fractions:\n\nEach valid fraction is converted to a Fraction object, and the sum is calculated using sum().\nChecking for Zero Sum:\n\nIf the total sum is zero, "0/1" is returned as the output.\nReturning the Result:\n\nThe result is formatted and returned as a string using f"{result.numerator}/{result.denominator}".\n\n# Code\n```python3 []\nfrom fractions import Fraction\n\nclass Solution:\n def fractionAddition(self, e: str) -> str:\n c= e.replace("-","+-").split("+")\n result = sum(Fraction(C) for C in c if C)\n if result == 0:\n return "0/1"\n else:\n return f"{result.numerator}/{result.denominator}"\n\n \n\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n \n \n #c = e.replace("-", "+-").split("+")\n # result = sum(Fraction(comp) for comp in components if comp)\n\n```
3
0
['Python3']
1
fraction-addition-and-subtraction
Easy and Simple C++ Code ☠️💯✅
easy-and-simple-c-code-by-shodhan_ak-urky
Code\ncpp []\nclass Solution {\npublic:\n string fractionAddition(string s) {\n int num = 0;\n int den = 1;\n int n = s.size();\n
Shodhan_ak
NORMAL
2024-09-01T08:55:51.061828+00:00
2024-09-01T08:55:51.061848+00:00
30
false
# Code\n```cpp []\nclass Solution {\npublic:\n string fractionAddition(string s) {\n int num = 0;\n int den = 1;\n int n = s.size();\n int i = 0;\n while (i < n) {\n int cn = 0;\n int cd = 0;\n bool neg = false;\n char ch = s[i];\n if (ch == \'+\' || ch == \'-\') {\n if (ch == \'-\') {\n neg = true;\n }\n i++;\n }\n int st = i;\n while (i < n && isdigit(s[i])) {\n i++;\n }\n cn = stoi(s.substr(st, i - st));\n if (neg) {\n cn *= -1;\n }\n i++;\n st = i;\n while (i < n && isdigit(s[i])) {\n i++;\n }\n cd = stoi(s.substr(st, i - st));\n num = num * cd + cn * den;\n den = den * cd;\n int g = gcd(abs(num), den);\n num /= g;\n den /= g;\n }\n return to_string(num) + "/" + to_string(den);\n }\n};\n\n```\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n**Initialization:**\n\nTwo variables, num (numerator) and den (denominator), are initialized to represent the result of the accumulated fraction. Initially,` num = 0` and `den = 1`, representing the fraction `0/1`.\n- n is the size of the input string s.\n- i is used as a pointer to traverse through the input string.\n\n**Iterate Over the String:**\n\nThe code enters a while loop that continues as long as i < n, meaning it processes each fraction in the string.\nInside the loop, the local variables cn (current numerator), cd (current denominator), and neg (a boolean flag to check if the fraction is negative) are initialized.\n\n**Handling Signs:**\n\nThe character ch = s[i] is checked to see if it\'s a + or -. If it\'s -, neg is set to true to handle the negative sign. i is then incremented to move to the next character.\n\n**Extracting Numerator:**\n\n`st = i` marks the starting index of the numerator. The code then moves the pointer i forward while the characters are digits, effectively parsing the numerator part of the fraction.\n`cn = stoi(s.substr(st, i - st))` converts the extracted substring to an integer representing the current numerator.\nIf neg is true, cn is multiplied by -1 to account for the negative sign.\n\n**Extracting Denominator:**\n\nAfter parsing the numerator, **i++ skips the / character**.\nSimilar to the numerator extraction, st = i marks the start of the denominator, and the loop increments i until all digit characters are processed.\n`cd = stoi(s.substr(st, i - st)) `converts the extracted substring to an integer representing the current denominator.\n\n**Updating the Result:**\n\nThe result is updated using the formula for adding fractions: num = num * cd + cn * den, and den = den * cd. This adjusts the result to account for the common denominator of the fractions.\nTo ensure the fraction remains in its simplest form, the greatest common divisor (GCD) of the numerator (num) and the denominator (den) is computed using gcd(abs(num), den).\nBoth num and den are divided by their GCD to simplify the fraction.\n\n**End of Loop:**\n\nThe loop continues until all characters of the string have been processed.\n\n**Returning the Result:**\n\nThe final result is converted to a string in the form "num/den" and returned.\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n
3
0
['C++']
0
fraction-addition-and-subtraction
C++ || Faster than 100% || Easy Video Solution
c-faster-than-100-easy-video-solution-by-onsd
The video solution for the below code is\nhttps://youtu.be/2Qbzv0qbebg\n\n# Code\ncpp []\nclass Solution {\npublic:\n string fractionAddition(string s) {\n
__SAI__NIVAS__
NORMAL
2024-08-23T15:32:09.994155+00:00
2024-08-23T15:32:09.994189+00:00
331
false
The video solution for the below code is\nhttps://youtu.be/2Qbzv0qbebg\n\n# Code\n```cpp []\nclass Solution {\npublic:\n string fractionAddition(string s) {\n vector<int> nums;\n vector<int> dens;\n int sz = s.size();\n int i = 0;\n bool isPositive = true;\n while(i < sz){\n if(s[i] == \'+\' or s[i] == \'-\'){\n if(s[i] == \'-\') isPositive = false;\n i++;\n }\n int num = 0;\n while(s[i] >= \'0\' and s[i] <= \'9\'){\n num = num*10 + (s[i] - \'0\');\n i++;\n }\n i++;\n int den = 0;\n while(s[i] >= \'0\' and s[i] <= \'9\'){\n den = den*10 + (s[i] - \'0\');\n i++;\n }\n if(isPositive == false) num *= -1;\n nums.push_back(num);\n dens.push_back(den);\n isPositive = true;\n }\n int szFractions = dens.size();\n int lcm = 1;\n for(int i = 0 ; i < szFractions ; i++){\n lcm = (lcm * dens[i]) / __gcd(lcm, dens[i]);\n }\n int numerator = 0;\n for(int i = 0 ; i < szFractions ; i++){\n numerator += ((lcm / dens[i]) * nums[i]);\n }\n if(numerator == 0) return "0/1";\n int GCD = __gcd(numerator, lcm);\n if(GCD < 0) GCD *= -1;\n return to_string(numerator / GCD) + "/" + to_string(lcm / GCD);\n }\n};\n```
3
0
['C++']
0
fraction-addition-and-subtraction
Fraction Arithmetic with Simplification: Parsing, Common Denominators, and GCD Reduction
fraction-arithmetic-with-simplification-fhwxm
Intuition\n Describe your first thoughts on how to solve this problem. \nWhen dealing with fraction addition and subtraction, we need to carefully manage the ar
KrishnaD098
NORMAL
2024-08-23T13:46:46.908050+00:00
2024-08-23T13:46:46.908075+00:00
12
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWhen dealing with fraction addition and subtraction, we need to carefully manage the arithmetic operations between fractions, which involve finding a common denominator and simplifying the result. The key challenge is to parse the expression correctly, handle the signs, and ensure that the final fraction is reduced to its simplest form. By iterating through the expression, we can sequentially process each fraction, accumulating the result while maintaining the correct sign and simplifying as we go.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1.Parsing the Expression: Iterate through the input string to extract each fraction. Identify the sign (+ or -) and then extract the numerator and denominator of the fraction.\n\n2.Common Denominator: To add or subtract fractions, convert them to a common denominator. This is done by adjusting the numerator of each fraction accordingly.\n\n3.Updating the Result: Maintain a running total of the result as a fraction by adding or subtracting the adjusted numerators. The denominator remains the common one.\n\n4.Simplification: After each operation, simplify the fraction by finding the greatest common divisor (GCD) of the numerator and denominator, and divide both by this GCD.\n\n5.Final Output: Return the result in the format numerator/denominator, ensuring that even if the result is an integer, it is expressed as a fraction (e.g., 2 becomes 2/1).\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public String fractionAddition(String expression) {\n int numerator = 0, denominator = 1;\n int i = 0, n = expression.length();\n\n while (i < n) {\n // Read the numerator\n int sign = 1;\n if (expression.charAt(i) == \'-\' || expression.charAt(i)==\'+\'){\n sign = expression.charAt(i) == \'-\' ? -1 : 1;\n i++;\n }\n\n int num = 0;\n while (i < n && Character.isDigit(expression.charAt(i))) {\n num = num * 10 + (expression.charAt(i) - \'0\');\n i++;\n }\n num *= sign;\n i++;\n\n // Read the denominator\n int den = 0;\n while (i < n && Character.isDigit(expression.charAt(i))) {\n den = den * 10 + (expression.charAt(i) - \'0\');\n i++;\n }\n\n // Add the fraction to the result\n numerator = numerator * den + num * denominator;\n denominator *= den;\n\n // Simplify the fraction\n int gcd = gcd(Math.abs(numerator), denominator);\n numerator /= gcd;\n denominator /= gcd;\n }\n return numerator + "/" + denominator;\n }\n // Helper function to compute the GCD (Greatest Common Divisor)\n private static int gcd(int a, int b) {\n while (b != 0) {\n int temp = b;\n b = a % b;\n a = temp;\n }\n return a;\n }\n}\n```
3
0
['Java']
0
fraction-addition-and-subtraction
Simple Implementation like school maths || C++
simple-implementation-like-school-maths-p20q7
Intuition\nThe problem requires us to evaluate an expression containing fractions, which might involve both addition and subtraction. The result must be returne
Satvik_Agrawal
NORMAL
2024-08-23T09:12:34.383691+00:00
2024-08-23T09:12:34.383732+00:00
24
false
# Intuition\nThe problem requires us to evaluate an expression containing fractions, which might involve both addition and subtraction. The result must be returned as an irreducible fraction. If the fraction is an integer, it should be returned with a denominator of 1, e.g., 2 should be returned as 2/1.\n\nTo solve this, we need to:\n1. Parse the input string and extract each fraction along with its sign.\n2. Compute the sum of these fractions by finding a common denominator.\n3. Simplify the result by finding the greatest common divisor (GCD) of the numerator and denominator.\n\n# Approach\n\n1. Parse the Expression:\n - Traverse the string expression to identify fractions and their corresponding signs.\n - For each fraction, extract the numerator and denominator.\n2. Compute Fraction Addition:\n - Maintain a cumulative numerator and a common denominator.\n - For each fraction in the expression, compute the least common multiple (LCM) of the current denominator and the new fraction\u2019s denominator.\n - Adjust the numerators according to the LCM and add/subtract them.\n3. Simplify the Result:\n - After processing all fractions, simplify the result by dividing both the numerator and denominator by their GCD.\n - Return the simplified fraction as a string.\n\n# Complexity\n- Time complexity:\nParsing the expression and performing GCD/LCM operations on each fraction takes $$O(n)$$, where $$n$$ is the length of the expression string.\n\n- Space complexity:\nThe space complexity is $$O(1)$$ because we only use a few extra variables for computation.\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int gcd(int a, int b) {\n if (b == 0)\n return a;\n return gcd(b, a % b);\n }\n\n int lcm(int a, int b) {\n return a * (b / gcd(a, b));\n }\n\n string fractionAddition(string expression) {\n int numerator = 0, denominator = 1;\n int i = 0, n = expression.size();\n\n while (i < n) {\n int sign = 1;\n if (expression[i] == \'+\' || expression[i] == \'-\') {\n if (expression[i] == \'-\') sign = -1;\n i++;\n }\n\n int currentNum = 0;\n while (i < n && isdigit(expression[i])) {\n currentNum = currentNum * 10 + (expression[i++] - \'0\');\n }\n currentNum *= sign;\n\n i++;\n\n int currentDen = 0;\n while (i < n && isdigit(expression[i])) {\n currentDen = currentDen * 10 + (expression[i++] - \'0\');\n }\n\n int commonDen = lcm(denominator, currentDen);\n numerator = numerator * (commonDen / denominator) + currentNum * (commonDen / currentDen);\n denominator = commonDen;\n }\n\n if (numerator == 0) return "0/1";\n\n int GCD = gcd(abs(numerator), denominator);\n return to_string(numerator / GCD) + "/" + to_string(denominator / GCD);\n }\n};\n\n```
3
0
['C++']
0
fraction-addition-and-subtraction
Java Solution Using Regex Expression
java-solution-using-regex-expression-by-xftf1
Complexity\n- Time complexity:O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity:O(1)\n Add your space complexity here, e.g. O(n) \n\n# Code
Shree_Govind_Jee
NORMAL
2024-08-23T06:02:27.429474+00:00
2024-08-23T06:02:27.429506+00:00
205
false
# Complexity\n- Time complexity:$$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n private int GCD(int a, int b) {\n return a == 0 ? Math.abs(b) : GCD(b % a, a);\n }\n\n public String fractionAddition(String expression) {\n Scanner sc = new Scanner(expression).useDelimiter("/|(?=[-+])");\n int A = 0, B = 1;\n while (sc.hasNext()) {\n int a = sc.nextInt(), b = sc.nextInt();\n A = A * b + B * a;\n B = B * b;\n\n int gcd = GCD(A, B);\n A /= gcd;\n B /= gcd;\n }\n return A + "/" + B;\n }\n}\n```
3
0
['Math', 'String', 'Simulation', 'Java']
0
fraction-addition-and-subtraction
🔥100%% Explanations No One Will Give You🎓🧠Very Detailed Approach🎯🔥
100-explanations-no-one-will-give-youver-3vt3
# Code\ncpp []\nclass Solution {\npublic:\n string fractionAddition(string expression) {\n int num = 0;\n int den = 1;\n int i = 0;\n
ShivanshGoel1611
NORMAL
2024-08-23T05:17:09.689694+00:00
2024-08-23T05:17:09.689722+00:00
986
false
# ***# Code***\n```cpp []\nclass Solution {\npublic:\n string fractionAddition(string expression) {\n int num = 0;\n int den = 1;\n int i = 0;\n int n = expression.size();\n while (i < n) {\n int currentnum = 0;\n int currentden = 0;\n bool negative = (expression[i] == \'-\');\n while (i < n && (expression[i] == \'-\' || expression[i] == \'+\')) {\n i++;\n }\n while (i < n && isdigit(expression[i])) {\n int a = expression[i] - \'0\';\n currentnum = (currentnum * 10) + a;\n i++;\n }\n i++;\n while (i < n && isdigit(expression[i])) {\n int a = expression[i] - \'0\';\n currentden = (currentden * 10) + a;\n i++;\n }\n if (negative == true) {\n currentnum *= -1;\n }\n num = num * currentden + den * currentnum;\n den = den * currentden;\n }\n int Gcd = abs(__gcd(num, den));\n num /= Gcd;\n den /= Gcd;\n return to_string(num) + "/" + to_string(den);\n }\n};\n```
3
0
['Math', 'String', 'PHP', 'Simulation', 'Python', 'C++', 'Java', 'JavaScript']
3
fraction-addition-and-subtraction
Simple Math & GCD
simple-math-gcd-by-up41guy-g7yc
Breakdown of the Regular Expression: (/[+-]?\d+\/\d+/g)\n[+-]?:\n\n[+-]: This is a character class that matches either a + or a - sign.\n?: This quantifier mean
Cx1z0
NORMAL
2024-08-23T03:41:44.403060+00:00
2024-08-23T03:51:59.242308+00:00
226
false
**Breakdown of the Regular Expression:** (/[+-]?\\d+\\/\\d+/g)\n[+-]?:\n\n[+-]: This is a character class that matches either a + or a - sign.\n?: This quantifier means "zero or one occurrence." It allows the sign to be optional, so it will match fractions with or without a sign.\n\\d+:\n\n\\d: This matches any digit from 0 to 9.\n+: This quantifier means "one or more occurrences." It ensures that the regular expression matches one or more digits, which forms the numerator of the fraction.\n\\/:\n\n\\/: This escapes the / character, which is used as the division symbol in fractions. The backslash (\\) is necessary because / has special meaning in regular expressions (it is typically used to delimit the regex pattern).\n\\d+:\n\nThis is the same as the previous \\d+ and matches one or more digits, which forms the denominator of the fraction.\ng:\n\nThe g flag stands for "global." It means that the regular expression will search for all matches in the string, not just the first one. Without this flag, the regular expression would stop after finding the first match.\nExample Matches:\nGiven the string "-1/2+1/2+1/3", here\'s how the regular expression would match:\n\n-1/2:\n[+-]?: Matches the -.\n\\d+: Matches 1.\n\\/: Matches the /.\n\\d+: Matches 2.\n\n+1/2:\n[+-]?: Matches the +.\n\\d+: Matches 1.\n\\/: Matches the /.\n\\d+: Matches 2.\n\n+1/3:\n[+-]?: Matches the +.\n\\d+: Matches 1.\n\\/: Matches the /.\n\\d+: Matches 3.\n\nSummary:\n[+-]?: Matches an optional sign.\n\\d+: Matches the numerator (one or more digits).\n\\/: Matches the division symbol /.\n\\d+: Matches the denominator (one or more digits).\ng: Ensures all fractions in the string are matched, not just the first one.\n\n\n# Code\n```javascript []\n/**\n * @param {string} expression\n * @return {string}\n */\nvar fractionAddition = function (expression) {\n const fractions = expression.match(/[+-]?\\d+\\/\\d+/g); //[ \'-1/2\', \'+1/2\', \'-3/4\' ]\n\n let numerator = 0\n let denominator = 1\n\n const gcd = (a, b) => b === 0 ? a : gcd(b, a % b)\n\n for (const fract of fractions) {\n const [num, denom] = fract.split(\'/\')// \'-3/4\' -> [ \'-3\', \'4\' ]\n\n numerator = numerator * denom + num * denominator\n denominator *= denom\n\n\n //simplify the fraction\n\n const gcdval = gcd(Math.abs(numerator), Math.abs(denominator))\n numerator /= gcdval\n denominator /= gcdval\n\n }\n return `${numerator}/${denominator}`\n};\n```
3
0
['Math', 'Simulation', 'JavaScript']
0
fraction-addition-and-subtraction
🌟 | C++ | Java | Python3 | 0ms Beats 100.00% | O(n) | Fraction Addition and Subtraction |
c-java-python3-0ms-beats-10000-on-fracti-flyk
\n---\n\n# Intuition\nThe problem requires adding and subtracting fractions within a given string expression. The key is to process each fraction one by one, ma
user4612MW
NORMAL
2024-08-23T02:45:57.169645+00:00
2024-08-23T02:45:57.169670+00:00
42
false
#\n---\n\n# **Intuition**\nThe problem requires adding and subtracting fractions within a given string expression. The key is to process each fraction one by one, maintaining a running total as you move through the string.\n\n# **Approach**\nTo solve this problem, initialize the numerator as 0 and the denominator as 1. As you parse through each fraction in the expression, update the running total by computing the sum of the current fraction and the total so far. Normalize the result by dividing both the numerator and the denominator by their greatest common divisor (GCD) to simplify the fraction. Continue this process until all fractions are processed. The final result is the simplified fraction of the total sum.\n\n# **Complexity**\n- **Time Complexity** $$O(n)$$, where $$n$$ is the length of the expression, as each character in the expression is processed once.\n- **Space Complexity** $$O(1)$$, only a few additional variables are used.\n\n# **Code**\n\n```cpp []\nclass Solution {\npublic:\n string fractionAddition(string expr) {\n int num{0}, den{1}, n, d;\n char slash;\n for (istringstream in(expr); in >> n >> slash >> d; ) {\n num = num * d + n * den;\n den *= d;\n int gcd = std::gcd(abs(num), den);\n num /= gcd;\n den /= gcd;\n }\n return to_string(num) + "/" + to_string(den);\n }\n};\n```\n\n```java []\nclass Solution {\n public String fractionAddition(String expr) {\n int num = 0, den = 1;\n for (String s : expr.split("(?=[+-])")) {\n int gcd = gcd(Math.abs(num * Integer.parseInt(s.split("/")[1]) + Integer.parseInt(s.split("/")[0]) * den), den * Integer.parseInt(s.split("/")[1]));\n num = (num * Integer.parseInt(s.split("/")[1]) + Integer.parseInt(s.split("/")[0]) * den) / gcd;\n den = (den * Integer.parseInt(s.split("/")[1])) / gcd;\n }\n return num + "/" + den;\n }\n \n private int gcd(int a, int b) {\n while (b != 0) {\n int temp = b;\n b = a % b;\n a = temp;\n }\n return a;\n }\n}\n```\n\n```python3 []\nclass Solution:\n def fractionAddition(self, expr: str) -> str:\n from math import gcd\n num, den = 0, 1\n import re\n for n, d in re.findall(r\'([+-]?\\d+)/(\\d+)\', expr):\n n, d = int(n), int(d)\n num = num * d + n * den\n den *= d\n g = gcd(abs(num), den)\n num //= g\n den //= g\n return f\'{num}/{den}\'\n```\n\n---\n\n## **If you found this solution helpful, please upvote! \uD83D\uDE0A**\n\n---
3
0
['C++', 'Java', 'Python3']
0
fraction-addition-and-subtraction
Clean Code | Python, Java, C++ | Easily understandable and optimized codes.✅
clean-code-python-java-c-easily-understa-qxri
Intuition and Approach\n Describe your first thoughts on how to solve this problem. \nThe problem is about evaluating a string expression containing fractions,
92kareeem
NORMAL
2024-08-23T01:04:51.681304+00:00
2024-08-23T01:04:51.681326+00:00
1,011
false
# Intuition and Approach\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem is about evaluating a string expression containing fractions, where each fraction is either added or subtracted. The key challenge is to correctly handle the addition and subtraction of fractions with different denominators and ensure the result is in its simplest form.\n\nIdentify Fractions: Parse the string to extract numerators and denominators of all fractions.\n\nFind a Common Denominator: To add or subtract fractions, convert them to have a common denominator.\n\nPerform the Operation: Add or subtract the numerators while keeping the common denominator.\n\nSimplify the Result: Reduce the resulting fraction to its simplest form by dividing both numerator and denominator by their greatest common divisor (GCD).\n\nReturn in Required Format: Ensure that the result is returned in the required format, even if it is a whole number.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n), where n is the length of the input string. Parsing and processing each fraction takes constant time.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1), as the space used is constant and does not grow with the input size.\n\n# Code\n```java []\nclass Solution {\n public String fractionAddition(String expression) {\n\n expression = expression.replace("-", "+-");\n String[] fractions = expression.split("\\\\+");\n \n int numerator = 0, denominator = 1;\n \n for (String fraction : fractions) {\n if (!fraction.isEmpty()) {\n String[] parts = fraction.split("/");\n int num = Integer.parseInt(parts[0]);\n int den = Integer.parseInt(parts[1]);\n \n numerator = numerator * den + num * denominator;\n denominator *= den;\n \n int gcd = gcd(Math.abs(numerator), Math.abs(denominator));\n numerator /= gcd;\n denominator /= gcd;\n }\n }\n \n return numerator + "/" + denominator;\n }\n \n private static int gcd(int a, int b) {\n while (b != 0) {\n int temp = b;\n b = a % b;\n a = temp;\n }\n return a;\n }\n}\n```\n# Code\n```Python []\nimport math\nfrom fractions import Fraction\n\ndef fractionAddition(expression: str) -> str:\n # Replace \'-\' with \'+-\' to split easily\n expression = expression.replace(\'-\', \'+-\')\n fractions = expression.split(\'+\')\n\n # Initialize result as 0/1\n result = Fraction(0, 1)\n\n for fraction in fractions:\n if fraction:\n result += Fraction(fraction)\n \n # Convert the result to a string in numerator/denominator format\n return f"{result.numerator}/{result.denominator}"\n```\n# Code\n```C++ []\n#include <iostream>\n#include <string>\n#include <sstream>\n#include <numeric>\n\nusing namespace std;\n\nclass Solution {\npublic:\n string fractionAddition(string expression) {\n expression = replace(expression, "-", "+-");\n stringstream ss(expression);\n string fraction;\n int numerator = 0, denominator = 1;\n \n while (getline(ss, fraction, \'+\')) {\n if (!fraction.empty()) {\n int num, den;\n sscanf(fraction.c_str(), "%d/%d", &num, &den);\n \n numerator = numerator * den + num * denominator;\n denominator *= den;\n \n int gcd_val = gcd(abs(numerator), abs(denominator));\n numerator /= gcd_val;\n denominator /= gcd_val;\n }\n }\n \n return to_string(numerator) + "/" + to_string(denominator);\n }\n \nprivate:\n string replace(string str, string from, string to) {\n size_t pos = 0;\n while ((pos = str.find(from, pos)) != string::npos) {\n str.replace(pos, from.length(), to);\n pos += to.length();\n }\n return str;\n }\n\n int gcd(int a, int b) {\n return b == 0 ? a : gcd(b, a % b);\n }\n};\n```\n\n\n
3
0
['Java']
2
fraction-addition-and-subtraction
100% WORKING || EASY PYTHON3 SOLUTION || USING THE SIMPLEST MATHEMATICAL APPROACH
100-working-easy-python3-solution-using-kxdit
Approach\nIn this approach, what we are doing is listed below step by step:\n1. Firstly we need to import the required libraries\n2. After that, we need to extr
khakse_0003
NORMAL
2023-11-20T15:59:11.082504+00:00
2023-11-20T15:59:11.082527+00:00
462
false
# Approach\nIn this approach, what we are doing is listed below step by step:\n1. Firstly we need to import the required libraries\n2. After that, we need to extract the denominator of each term involved in the expression. Using regex, we retrieved and stored it in a list. You can also pass that list directly to the lcm function.\n3. After that, we find the least common multiple (LCM) of all the denominators obtained earlier. This LCM serves as the limit_denominator in the rational-to-fractional conversion.\n4. Finally, we simplified our rational solution (obtained using the evaluate function) into the form of a fractional solution and returned it in the numerator/denominator format.\n\n\n# Code\n```\nfrom fractions import Fraction\nfrom re import findall\nfrom math import lcm\n\nclass Solution:\n def fractionAddition(self, expression: str) -> str:\n ln = list(map(int, re.findall(r"\\/(\\w+)+",expression)))\n lm = lcm(*ln)\n m = Fraction(str(eval(expression))).limit_denominator(lm)\n return f"{m.numerator}/{m.denominator}"\n\n\n```
3
0
['Python3']
3
fraction-addition-and-subtraction
By using Stack and GCD|| in O(n)
by-using-stack-and-gcd-in-on-by-flamexus-rc1b
Intuition\nThe Question is easy and Simple Like we Only need to find LCM,\nthe main problem is of taking care of 10 in numerator or dinomerator in the stack \n\
FlameXuser
NORMAL
2023-05-24T04:05:20.985645+00:00
2023-05-24T04:06:58.233109+00:00
1,574
false
## Intuition\nThe Question is easy and Simple Like we Only need to find LCM,\nthe main problem is of taking care of 10 in numerator or dinomerator in the stack \n\n# Approach\nTaking example -1/2+1/2;\nTake 2 integer a & b; \n a=-1 b=2;\nNow in the stack take again 2 integer c & d;\n c=1 d=2;\n\nNow next thing is to find LCM & gcd\n a=a*d+c*b;\n b=b*d;\n int gcd=__gcd(abs(a),b);\n a=a/gcd;\n b=b/gcd;\nAnd the final result we will store in a & b and continuing the same..... \n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution {\npublic:\n string fractionAddition(string exp) {\n int x=0;\n string s1="";\n if(exp[0]==\'-\')\n x=1;\n int y=0;\n int a=0;\n if(x==0)\n a=exp[x]-\'0\';\n else\n a=-(exp[x]-\'0\');\n if(exp[x+1]>=\'0\' && exp[x+1]<=\'9\') //to check if a is 10 or -10 in the first numerator \n {\n if(x==0)\n a=10;\n else\n a=-10;\n y++;\n }\n int b=exp[x+2+y]-\'0\';\n if(exp[x+3+y]>=\'0\' && exp[x+3+y]<=\'9\') ////to check if a is 10 or -10 in the first dinomerator\n {\n b=10;\n y++;\n } \n stack<string>st;\n string s=exp.substr(x+3+y,exp.size()); // pushing into stack like taking example -1/10+1/2; for we r pushing from +1/2\n reverse(s.begin(),s.end());\n for(int i=0;i<s.size();i++)\n {\n string str="";\n str+=s[i];\n st.push(str);\n }\n int c=0;\n int d=0;\n int i=0;\n int nume=0,dino=0; //for checking if not 10\n bool flag=false; //to store "+" or "-"\n bool check=false; //helps in calculating d if c has already been calculated \n while(!st.empty())\n {\n if(st.top()=="-")\n flag=true;\n \n if(st.top()>="0" && st.top()<="9" && check==false)\n {\n if(flag)\n c=-(stoi(st.top()));\n else\n c=stoi(st.top());\n if(nume==1)\n {\n if(flag)\n c=-10;\n else\n c=10;\n }\n nume++;\n }\n if(st.top()>="0" && st.top()<="9" && check==true)\n {\n d=stoi(st.top());\n if(dino==1)\n {\n d=10;\n }\n dino++;\n }\n if(st.top()=="/")\n check=true;\n st.pop();\n if((st.size()==0 || st.top()=="+" ||st.top()=="-") && check)\n {\n cout<<a<<"/"<<b<<endl;\n cout<<c<<"/"<<d<<endl;\n a=a*d+c*b;\n b=b*d;\n int gcd=__gcd(abs(a),b);\n a=a/gcd;\n b=b/gcd;\n i=0;\n flag=false;\n check=false;\n c=0;\n d=0;\n nume=0;\n dino=0;\n }\n \n \n }\n return to_string(a)+"/"+to_string(b);\n }\n};\n```
3
0
['Stack', 'C++']
2
fraction-addition-and-subtraction
Easy O(n) solution using Fraction
easy-on-solution-using-fraction-by-naman-5q4v
\nfrom fractions import Fraction\n\nclass Solution:\n def fractionAddition(self, expression: str) -> str:\n res = sum(map(Fraction, expression.replace
namanxk
NORMAL
2022-09-27T18:09:55.620521+00:00
2022-09-27T18:09:55.620568+00:00
862
false
```\nfrom fractions import Fraction\n\nclass Solution:\n def fractionAddition(self, expression: str) -> str:\n res = sum(map(Fraction, expression.replace(\'+\', \' +\').replace(\'-\', \' -\').split()))\n return str(res.numerator) + \'/\' + str(res.denominator)\n```
3
0
['Python']
0
fraction-addition-and-subtraction
100% fast Fraction Addition and Subtraction
100-fast-fraction-addition-and-subtracti-8ht7
if code is understable well ,please upvote\nclass Rational{ \n public :\n\n int numerator=1;\n int denominator=1; \n Rational(int numerator, int
Govind360
NORMAL
2022-09-03T11:22:41.192486+00:00
2023-03-09T10:47:28.634388+00:00
418
false
if code is understable well ,please upvote\nclass Rational{ \n public :\n\n int numerator=1;\n int denominator=1; \n Rational(int numerator, int denominator) {\n this -> numerator = numerator;\n this -> denominator = denominator;\n } \n\n void add(Rational const &f2) {\n int lcm = denominator * f2.denominator;\n int x = lcm / denominator;\n int y = lcm / f2.denominator;\n\n int num = x * numerator + (y * f2.numerator);\n int g=__gcd(abs(num),abs(lcm));\n\t\t// simplify the fraction\n numerator = num/g;\n denominator = lcm/g;\n\n } \n};\n\nclass Solution {\npublic:\n \n string fractionAddition(string str) {\n int n=str.size();\n int s1=1,s2=1;\n int i=0;\n if(str[i]==\'-\')s1=0,i++;\n int nume=0,deno=1;\n if(isdigit(str[i])){\n nume=str[i++]-\'0\';\n\t\t\t// if numerator of fraction have two digit\n if(isdigit(str[i])){\n nume=nume*10+(str[i++]-\'0\');\n }\n if(s1==0)nume=-1*nume;\n if(i<n && str[i]==\'/\'){\n i++;\n deno=str[i++]-\'0\';\n\t\t\t\t// if numerator of fraction have two digit\n if(isdigit(str[i])){\n deno=deno*10+(str[i++]-\'0\');\n }\n }\n }\n cout<<nume<<"/"<<deno<<endl;\n for(;i<n;){\n int nume2=0,deno2=1;\n if(isdigit(str[i])){\n nume2=str[i++]-\'0\';\n\t\t\t\t// if numerator of fraction have two digit\n if(isdigit(str[i])){\n nume2=nume2*10+(str[i++]-\'0\');\n }\n if(i<n && str[i]==\'/\'){\n i++;\n deno2=str[i++]-\'0\';\n\t\t\t\t\t// if numerator of fraction have two digit\n if(isdigit(str[i])){\n deno2=deno2*10+(str[i++]-\'0\');\n }\n }\n }\n else{\n if(str[i]==\'-\')s2=0;\n \n i++;\n continue;\n }\n \n if(s2==0)nume2=-1*nume2; \n Rational f1(nume, deno);\n\t Rational f2(nume2, deno2);\n f1.add(f2); // add fractional values\n\t\t\t//update these fractions \n nume=f1.numerator;\n deno=f1.denominator \n s2=1;\n }\n \n string res="";\n res+=to_string(nume);\n res+="/";\n if(nume==0){\n res+=to_string(1);\n }\n else res+=to_string(deno);\n return res;\n }\n};
3
0
['C++']
0
fraction-addition-and-subtraction
Python 3 | Math, Simulation, GCD | Explanation
python-3-math-simulation-gcd-explanation-h6qd
Explanation\n- Intuition: Simulation seems like a fine solution, with basic Math, it should be straight forward.\n- Simulation the following process:\n\t- Find
idontknoooo
NORMAL
2021-07-06T00:50:48.165514+00:00
2021-07-06T00:50:48.165551+00:00
708
false
### Explanation\n- Intuition: Simulation seems like a fine solution, with basic Math, it should be straight forward.\n- Simulation the following process:\n\t- Find each (numerator, divisor) in `expression`, calculate the product of all divisors and store at `multiple`\n\t- Calculate new numerator which is the sum of `numerator * multiple // divisor` named as `s`, and new divisor is now becomes to `multiple`\n\t- Find `greatest common divisor (GCD)`, which is `divisor`, between new numerator (`s`) and new divisor (`multiple`)\n\t- Divide both `s` and `multiple` by `divisor` and return the final faction\n### Implementation\n```\nclass Solution:\n def fractionAddition(self, expression: str) -> str:\n pairs, cur, sign, multiple = [], \'\', 0, 1\n for c in expression+\'+\':\n if not sign:\n if c == \'-\': sign = -1\n else: sign, cur = 1, cur + c\n elif c in \'-+\':\n left, right = cur.split(\'/\')\n pairs.append((abs(int(left)) * sign, abs(int(right))))\n multiple *= pairs[-1][1]\n sign, cur = -1 if c == \'-\' else 1, \'\'\n else: cur += c\n s = sum([n * multiple // d for n, d in pairs])\n def gcd(a, b):\n while b: a, b = b, a % b\n return abs(a) \n divisor = gcd(s, multiple)\n return f\'{s//divisor}/{multiple//divisor}\'\n```
3
0
['Math', 'String', 'Simulation', 'Python', 'Python3']
0
fraction-addition-and-subtraction
Java one loop, no need to split, 5ms, beats 100%
java-one-loop-no-need-to-split-5ms-beats-c1sl
\nclass Solution {\n public String fractionAddition(String expression) {\n // initial numerator and denominator 0 = 0 / 1\n int a = 0;\n
leonwang
NORMAL
2018-10-14T16:09:21.288670+00:00
2018-10-14T16:09:21.288711+00:00
898
false
```\nclass Solution {\n public String fractionAddition(String expression) {\n // initial numerator and denominator 0 = 0 / 1\n int a = 0;\n int b = 1;\n // current numerator and denominator c / d\n int c = 0;\n int d = 0;\n // initialize \n int sign = 1;\n boolean isNumerator = true;\n int len = expression.length();\n\n for (int i = 0; i < len; i++) {\n char ch = expression.charAt(i);\n if (ch == \'+\') {\n sign = 1;\n c = 0;\n } else if (ch == \'-\') {\n sign = -1;\n c = 0;\n } else if (ch == \'/\') {\n isNumerator = false;\n d = 0;\n } else {\n if (isNumerator) {\n c = 10 * c + (ch - \'0\');\n } else {\n d = 10 * d + (ch - \'0\');\n \n if (i == len - 1 || expression.charAt(i+1) == \'+\' || expression.charAt(i+1) == \'-\') {\n int e = 0;\n int f = 1;\n if (b == d) {\n e = a + sign * c;\n f = b;\n } else {\n e = a * d + sign * b * c;\n f = b * d;\n }\n\n // common divisor of e / f\n int j = gcd(e, f);\n a = e / j;\n b = f / j;\n // we want -1/2 rather than 1/-2\n if (b < 0) {\n a = -a;\n b = -b;\n }\n\n // next number should be numerator\n isNumerator = true;\n }\n }\n }\n }\n \n return a + "/" + b;\n }\n \n public static int gcd(int a, int b) {\n while (b != 0) {\n int t = b;\n b = a % b;\n a = t;\n }\n return a;\n }\n}\n```
3
0
[]
1
fraction-addition-and-subtraction
Easy Solution Without using Regular Expression
easy-solution-without-using-regular-expr-s4c6
Intuition\nCreate 2 arrays numerator and denomenator to store all numerators and denomenators.\n\n\n# Approach\nFind lcm by multiplying all unique denomenators,
unblemished08
NORMAL
2024-08-24T06:36:26.622027+00:00
2024-08-24T06:36:26.622057+00:00
26
false
# Intuition\nCreate 2 arrays numerator and denomenator to store all numerators and denomenators.\n\n\n# Approach\nFind lcm by multiplying all unique denomenators, we can use hashSet for that.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```java []\nclass Solution {\n public String fractionAddition(String expression) {\n ArrayList<Integer> num=new ArrayList<>();\n ArrayList<Integer> den=new ArrayList<>();\n HashSet<Integer> denSet=new HashSet<>();\n boolean n=true;\n int neg=1;\n\n for(int i=0;i<expression.length();i++)\n {\n char ch=expression.charAt(i);\n if(ch==\'-\')\n neg=-1;\n else if(ch==\'+\')\n neg=1;\n else if(ch==\'/\')\n n=false;\n else\n {\n int x=ch-\'0\';\n if(x==1 && i<expression.length()-1 && expression.charAt(i+1)==\'0\')\n {\n x=10;\n i++;\n }\n\n if(n)\n {\n num.add(x*neg);\n }\n else\n {\n den.add(x);\n denSet.add(x);\n n=true;\n }\n }\n }\n\n long lcm=1;\n for(int x:denSet)\n {\n lcm*=x;\n }\n\n long ans=0;\n for(int i=0;i<num.size();i++)\n {\n ans+=lcm/den.get(i)*num.get(i);\n }\n\n long gcdVal=gcd(Math.abs(ans),lcm);\n\n return ans/gcdVal+"/"+lcm/gcdVal;\n }\n\n public long gcd(long a, long b) {\n while (b != 0) {\n long temp = b;\n b = a % b;\n a = temp;\n }\n return a;\n }\n}\n```
2
0
['Math', 'String', 'Simulation', 'Java']
0
fraction-addition-and-subtraction
O(N) time complexity and O(1) Space complexity
on-time-complexity-and-o1-space-complexi-asp2
Code\npython3 []\nfrom fractions import Fraction\nclass Solution:\n def fractionAddition(self, e: str) -> str:\n total = Fraction(0)\n i = 0\n
NurzhanSultanov
NORMAL
2024-08-23T18:17:02.137544+00:00
2024-08-23T18:17:02.137578+00:00
9
false
Code\n```python3 []\nfrom fractions import Fraction\nclass Solution:\n def fractionAddition(self, e: str) -> str:\n total = Fraction(0)\n i = 0\n n = len(e)\n while i < len(e):\n if e[i] == \'-\':\n sign = -1\n i += 1\n else:\n sign = 1\n if e[i] == \'+\':\n i += 1\n j = i\n while i < len(e) and e[i] != \'/\':\n i += 1\n up = int(e[j:i])\n i += 1\n k = i\n while i < len(e) and (e[i].isdigit()):\n i += 1\n down = int(e[k:i])\n total = total + Fraction(sign * up, down)\n return f"{total.numerator}/{total.denominator}"\n```
2
0
['Python3']
0
fraction-addition-and-subtraction
Python solution using re module (Runtime: 89.15% beats | Memory:89.53% beats)
python-solution-using-re-module-runtime-h0h3b
Intuition\nWhen dealing with string expressions that require data extraction based on specific conditions, I instinctively turn to Python\'s re module. It\u2019
pranaymaheshwaram
NORMAL
2024-08-23T16:50:12.761636+00:00
2024-08-23T16:50:12.761674+00:00
37
false
# Intuition\nWhen dealing with string expressions that require data extraction based on specific conditions, I instinctively turn to Python\'s re module. It\u2019s a powerful tool for such tasks, especially for someone whose primary programming language is Python. After extracting the fractions, simplifying them is straightforward arithmetic. The process began with the operate function, and from there, the code evolved organically\u2014it\u2019s fascinating how ideas can flow so rapidly!\n\n# Approach\nI have used python \'re\' module to get hold of the fraction numbers.\nAfter getting all the fraction numbers I added them using a for loop. I will be getting an equivalent fraction at the end as an answer, which I will be simplifying further using math module\'s gcd function. Hence, getting a simplified fraction answer.\n\n- Time Complexity\n The regular expression split takes O(n).\n Each operation inside the loop takes O(1).\n The loop runs O(k) times, where k is the number of fractions.\n **So the overall time complexity is O(n + k), that can be considered as O(n)**\n\n- Space complexity:\nO(n)\n\n# Code\n```python3 []\nimport re\nfrom math import gcd\nclass Solution:\n def fractionAddition(self, expression: str) -> str:\n def operate(x, y):\n n1 = [int(i) for i in x.split(\'/\')]\n n2 = [int(i) for i in y.split(\'/\')]\n nume = (n1[0]*n2[1])+(n2[0]*n1[1])\n den = (n1[1]*n2[1])\n return f"{nume}/{den}"\n\n def simplify_fraction(fraction):\n num, denom = map(int, fraction.split(\'/\'))\n common_divisor = gcd(abs(num), abs(denom))\n num //= common_divisor\n denom //= common_divisor\n if denom < 0:\n num = -num\n denom = -denom\n return f"{num}/{denom}"\n\n\n fractions = re.findall(r\'[+-]?\\d+/\\d+\', expression)\n result = fractions[0]\n for i in range(1, len(fractions)):\n result = operate(result, fractions[i])\n\n return simplify_fraction(result)\n```
2
0
['Python3']
0
fraction-addition-and-subtraction
Using Python
using-python-by-deepakramgiri-djec
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
DeepakRamgiri
NORMAL
2024-08-23T15:48:57.008148+00:00
2024-08-23T15:48:57.008191+00:00
58
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python []\nfrom fractions import Fraction\n\nclass Solution(object):\n def fractionAddition(self, expression):\n # Split the expression into individual fractions\n fractions = expression.replace(\'-\', \'+-\').split(\'+\')\n \n # Sum up all the fractions\n result = sum(Fraction(f) for f in fractions if f)\n \n # Return the result as a string in the format "numerator/denominator"\n return "{}/{}".format(result.numerator, result.denominator)\n\n```
2
0
['Python']
1
fraction-addition-and-subtraction
BEATS 75% in java
beats-75-in-java-by-saiswaroop1234-mrvj
Bold# Intuition\nArrange all denominators with their final numerator using hashmap.\n\n# Approach\nJust solve using the simple lcm for all denominators. Find th
SaiSwaroop1234
NORMAL
2024-08-23T14:44:25.537314+00:00
2024-08-23T14:44:25.537344+00:00
11
false
**Bold**# Intuition\nArrange all denominators with their final numerator using hashmap.\n\n# Approach\nJust solve using the simple lcm for all denominators. Find the hcf for numerator and denominator and divide both with the hcf.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public String fractionAddition(String e) {\n int n=0;int s=1;boolean n1=true;int d=0;\n HashMap<Integer,Integer> de=new HashMap<>();\n for(int i=0;i<e.length();i++)\n {\n if(e.charAt(i)==\'-\')\n {\n s=-1;\n if(d!=0)\n {\n de.put(d,de.getOrDefault(d,0)+n);\n }\n d=0;\n n=0;\n n1=true;\n continue;\n }\n if(e.charAt(i)==\'+\')\n {\n s=1;\n if(d!=0)\n {\n de.put(d,de.getOrDefault(d,0)+n);\n }\n d=0;\n n1=true;\n n=0;\n continue;\n }\n if(n1)\n {\n if(e.charAt(i)==\'/\')\n {\n n=n*s;\n n1=false;\n continue;\n }\n if((int)e.charAt(i)<=57 && (int)e.charAt(i)>=48)\n {\n n=n*10;\n n+=((int)e.charAt(i)-48);\n continue;\n }\n }\n else\n {\n if((int)e.charAt(i)<=57 && (int)e.charAt(i)>=48)\n {\n d=d*10;\n d+=((int)e.charAt(i)-48);\n continue;\n }\n }\n }\n de.put(d,de.getOrDefault(d,0)+n);\n n=0;d=1;\n n1=true;\n for(int i:de.keySet())\n {\n n=((n*i)+(de.get(i)*d));\n d*=i;\n }\n if(n==0)\n {\n return "0/1";\n }\n if(n<0)\n {\n n=n*(-1);\n n1=false;\n }\n s=hcf(n,d);\n if(n1)\n {\n return n/s+"/"+d/s+"";\n }\n return "-"+n/s+"/"+d/s+"";\n }\n public static int hcf(int a, int b) {\n while (b != 0) {\n int temp = b;\n b = a % b;\n a = temp;\n }\n return a;\n }\n}\n```
2
0
['Java']
0
fraction-addition-and-subtraction
Easy to understand C++ code 🔥🔥
easy-to-understand-c-code-by-ashrut_shar-hmy3
\n\n\n# Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(1)\n Add your space complexity here, e.g. O(n)
Ashrut_Sharma
NORMAL
2024-08-23T14:27:44.815733+00:00
2024-08-23T14:27:44.815764+00:00
234
false
\n\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n string fractionAddition(string s) {\n string res;\n int lcm1=1;\n vector<int> denom;\n for(int i=0;i<s.length()-1;i++){\n if(s[i]==\'/\'){\n if(s[i+1]==\'1\' && s[i+2]==\'0\'){\n lcm1= lcm(10,lcm1);\n i+=2;\n }else{\n lcm1 = lcm(lcm1,int(s[i+1])-48);\n i++;\n }\n }\n }\n\n int sum = 0;\n int curr = 0;\n\n for(int i = 0; i<s.size()-1; i++)\n {\n int mul = 1;\n if(s[i] == \'/\'){\n if(i-2 >= 0 && s[i-1] == \'0\' && s[i-2] == \'1\'){\n s[i+1] == \'1\' && s[i+2] == \'0\' ? mul = (lcm1/10) : mul = (lcm1/(int(s[i+1])-48)); \n curr = 10*mul;\n }\n else{\n s[i+1] == \'1\' && s[i+2] == \'0\' ? mul = (lcm1/10) : mul = (lcm1/(int(s[i+1])-48)); \n curr = ( (int(s[i-1]) )-48)*mul;\n }\n \n i-2>= 0 && s[i-2] == \'-\' || i-3>=0 && s[i-3] == \'-\' ? sum -= curr : sum += curr;\n \n }\n }\n \n int k = 2;\n\n while(k<10){\n if (sum%k == 0 && lcm1%k == 0){\n sum /= k;\n lcm1 /= k;\n }\n else {\n k++;\n }\n }\n \n\n string result = to_string(sum)+"/"+to_string(lcm1);\n return result;\n }\n};\n```
2
0
['Math', 'String', 'C++']
1
fraction-addition-and-subtraction
Easy to Understand and Use Simple Logic beat 100% Complexity
easy-to-understand-and-use-simple-logic-lnodc
Intuition\n Describe your first thoughts on how to solve this problem. \nGetting Data From the String into a Vector array of Structure and Then Calculate Result
Muneebrajpot14
NORMAL
2024-08-23T13:31:38.839418+00:00
2024-08-23T13:31:38.839447+00:00
394
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nGetting Data From the String into a Vector array of Structure and Then Calculate Results and Convert again into the string. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSimple Math and String Manupulation.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\u201CO(n+flog(m))\u201D\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(f)\n\n# Code\n```cpp []\n\nclass Solution {\npublic:\n struct Fract {\n int sign;\n int Nom;\n int Denom;\n };\n\n void getdata(vector<Fract>& arr, const string& data) {\n size_t i = 0;\n while (i < data.size()) {\n Fract Temp;\n // Handle sign\n if (data[i] == \'-\') {\n Temp.sign = -1;\n i++;\n } else {\n Temp.sign = 1;\n if (data[i] == \'+\') {\n i++;\n }\n }\n\n // Extract numerator\n size_t start = i;\n while (i < data.size() && data[i] != \'/\') {\n if (!isdigit(data[i])) {\n throw invalid_argument("Invalid character in numerator");\n }\n i++;\n }\n Temp.Nom = stoi(data.substr(start, i - start));\n i++; // Skip \'/\'\n\n // Extract denominator\n start = i;\n while (i < data.size() && isdigit(data[i])) {\n i++;\n }\n if (i > start) {\n Temp.Denom = stoi(data.substr(start, i - start));\n } else {\n throw invalid_argument("Invalid character in denominator");\n }\n\n arr.push_back(Temp);\n }\n }\n\n Fract helper(const Fract& num1, const Fract& num2) {\n Fract ans;\n int LCM = num1.Denom * num2.Denom / findGCD(num1.Denom, num2.Denom);\n ans.Denom = LCM;\n ans.Nom = num1.sign * num1.Nom * (LCM / num1.Denom) + num2.sign * num2.Nom * (LCM / num2.Denom);\n ans.sign = (ans.Nom < 0) ? -1 : 1;\n ans.Nom = abs(ans.Nom);\n \n int gcd = findGCD(ans.Nom, ans.Denom);\n ans.Nom /= gcd;\n ans.Denom /= gcd;\n\n return ans;\n }\n\n Fract ComputeFinal(vector<Fract>& array) {\n Fract result = array[0];\n for (size_t i = 1; i < array.size(); ++i) {\n result = helper(result, array[i]);\n }\n return result;\n }\n\n int findGCD(int a, int b) {\n while (b != 0) {\n int temp = b;\n b = a % b;\n a = temp;\n }\n return a;\n }\n\n string fractionAddition(const string& expression) {\n vector<Fract> Data;\n try {\n getdata(Data, expression);\n } catch (const invalid_argument& e) {\n cerr << "Error: " << e.what() << endl;\n return "";\n }\n \n Fract Final_ans = ComputeFinal(Data);\n \n ostringstream oss;\n if (Final_ans.sign == -1) {\n oss << \'-\';\n }\n oss << Final_ans.Nom << \'/\' << Final_ans.Denom;\n return oss.str();\n }\n};\n```
2
0
['Math', 'String', 'Simulation', 'C++', 'Java', 'Python3']
0
fraction-addition-and-subtraction
Solution in c++ by calculating numerator and denominator
solution-in-c-by-calculating-numerator-a-tdnx
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
rohit_1610
NORMAL
2024-08-23T12:43:56.400675+00:00
2024-08-23T12:43:56.400694+00:00
70
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n string fractionAddition(string expression) {\n int n = expression.size();\n int i = 0;\n vector<int> num, denom;\n\n while (i < n) {\n int pro = 1;\n if (expression[i] == \'-\' || expression[i] == \'+\') {\n pro = (expression[i] == \'-\') ? -1 : 1;\n i++;\n }\n\n int x = 0;\n while (i < n && isdigit(expression[i])) {\n x = x * 10 + (expression[i] - \'0\');\n i++;\n }\n num.push_back(pro * x);\n\n i++;\n \n x = 0;\n while (i < n && isdigit(expression[i])) {\n x = x * 10 + (expression[i] - \'0\');\n i++;\n }\n denom.push_back(x);\n }\n\n int dm = denom[0];\n for (auto it : denom) {\n dm = (dm * it) / __gcd(dm, it);\n }\n\n int sum = 0;\n for (int i = 0; i < num.size(); i++) {\n sum += num[i] * (dm / denom[i]);\n }\n\n int f = __gcd(abs(sum), dm);\n sum /= f;\n dm /= f;\n\n if (sum == 0) {\n return "0/1";\n }\n\n string ans = (sum < 0 ? "-" : "") + to_string(abs(sum)) + "/" + to_string(dm);\n return ans;\n }\n};\n\n```
2
0
['C++']
0
fraction-addition-and-subtraction
In Detail JAVASCRIPT Solution
in-detail-javascript-solution-by-sajjan_-wq1z
Intuition\n Describe your first thoughts on how to solve this problem. \nTo solve this problem, you\'ll need to parse the input string, perform the addition or
sajjan_shivani
NORMAL
2024-08-23T11:59:59.958939+00:00
2024-08-23T11:59:59.958971+00:00
33
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo solve this problem, you\'ll need to parse the input string, perform the addition or subtraction on the fractions, and then return the result in its simplest form.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. GCD Calculation:\n\n- The gcd function is used to simplify fractions by finding the greatest common divisor of the numerator and denominator.\n2. Adding Fractions:\n\n- The addFractions function adds two fractions by using the common denominator formula:\n\n new\xA0numerator= n1\xD7d2+n2\xD7d1/d1xd2\n\n- It then simplifies the resulting fraction using the GCD.\n3. Extracting Fractions:\n\n- The regular expression /[+-]?\\d+\\/\\d+/g extracts all fractions from the expression, including their signs.\n4. Processing Fractions:\n\n- Each fraction is processed by splitting it into its numerator and denominator, then adding it to the cumulative result.\n5. Result Formatting:\n\n- If the denominator is negative, both the numerator and denominator are negated to keep the fraction properly formatted.\n6. Edge Cases:\n\n- The function handles cases where the result is an integer by returning it in the form of numerator/1.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nTime Complexity: O(L), where L is the length of the input string expression.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1), constant space usage.\n\n# Code\n```javascript []\n/**\n * @param {string} expression\n * @return {string}\n */\nvar fractionAddition = function(expression) {\n // Helper function to calculate the Greatest Common Divisor (GCD)\n function gcd(a, b) {\n return b === 0 ? a : gcd(b, a % b);\n }\n\n // Helper function to add two fractions\n function addFractions(n1, d1, n2, d2) {\n // Calculate the new numerator and denominator\n let numerator = n1 * d2 + n2 * d1;\n let denominator = d1 * d2;\n\n // Simplify the fraction by dividing both by their GCD\n let commonDivisor = gcd(Math.abs(numerator), Math.abs(denominator));\n return [numerator / commonDivisor, denominator / commonDivisor];\n }\n\n // Regular expression to extract fractions from the expression\n let regex = /[+-]?\\d+\\/\\d+/g;\n let fractions = expression.match(regex);\n\n // Initialize the result as 0/1\n let resultNumerator = 0;\n let resultDenominator = 1;\n\n // Process each fraction in the expression\n for (let fraction of fractions) {\n let [numerator, denominator] = fraction.split(\'/\').map(Number);\n\n // Add the current fraction to the result\n [resultNumerator, resultDenominator] = addFractions(resultNumerator, resultDenominator, numerator, denominator);\n }\n\n // Ensure the result is in the correct format\n if (resultDenominator < 0) {\n resultNumerator = -resultNumerator;\n resultDenominator = -resultDenominator;\n }\n\n return resultNumerator + \'/\' + resultDenominator;\n};\n```
2
0
['JavaScript']
1
fraction-addition-and-subtraction
Efficient Fraction Addition and Subtraction Using Python's Fraction Class
efficient-fraction-addition-and-subtract-xozd
Intuition\nAdding and subtracting fractions involves two main steps: figuring out the individual fractions (and their signs) from the input string, and then doi
rithvikreddy14
NORMAL
2024-08-23T11:07:00.329609+00:00
2024-08-23T11:07:00.329631+00:00
6
false
# Intuition\nAdding and subtracting fractions involves two main steps: figuring out the individual fractions (and their signs) from the input string, and then doing the math to add or subtract these fractions.\n\nThe tricky part comes when you\'re working with fractions that have different bottom numbers. You can\'t just add or subtract fractions with different bottom numbers without first making them have the same bottom number. This is the heart of the problem: you need to follow the rules for doing math with fractions.\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1.Parsing the Input String\n2.Using the Fraction Class\n3.Simplifying the Result\n4.Returning the Result\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nfrom fractions import Fraction\nclass Solution:\n def fractionAddition(self, e: str) -> str:\n e=e.replace(\'-\',\'+-\')\n a=e.split(\'+\')\n a=[i for i in a if i]\n result = Fraction(0, 1)\n for i in a:\n result += Fraction(i)\n return f"{result.numerator}/{result.denominator}" \n```
2
0
['Math', 'Python3']
0
fraction-addition-and-subtraction
100beats | ✅✅| Easy | CPP | String Simulation |
100beats-easy-cpp-string-simulation-by-k-fdku
Intuition\nSolve simillar to that we used to solve in our maths class.\n\n# Approach\n- Find the denominators of all the fraction and take lcm of all that to fi
karthikeya48
NORMAL
2024-08-23T10:52:49.194160+00:00
2024-08-23T10:52:49.194207+00:00
6
false
# Intuition\nSolve simillar to that we used to solve in our maths class.\n\n# Approach\n- Find the denominators of all the fraction and take lcm of all that to find the final denominator\n- Update the numerator according to the lcm.\n- Simplify the last numerator and the denominator.\n\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N)\n\n# Code\n```cpp []\nclass Solution {\npublic:\n string fractionAddition(string exp) {\n \n multiset<pair<int, int>> hash;\n vector<int> deno; \n\n if(isdigit(exp[0])) exp = \'+\' + exp;\n\n int n = exp.size();\n\n for(int i = 0; i + 3 < n; i++) { \n if(exp[i] == \'-\') {\n int x = -1 * ((exp[i + 1]) - \'0\');\n int f = 0;\n if(i + 2 < n and exp[i + 2] == \'0\') {\n x *= 10;\n f = 1;\n }\n int y = exp[i + 3 + f] - \'0\';\n if(i + 4 < n and exp[i + 4] == \'0\') {\n y *= 10;\n }\n hash.insert({x, y});\n deno.push_back(y);\n } \n\n if(exp[i] == \'+\') {\n int x = 1 * ((exp[i + 1]) - \'0\');\n int f = 0;\n if(i + 2 < n and exp[i + 2] == \'0\') {\n x *= 10;\n f = 1;\n }\n int y = exp[i + 3 + f] - \'0\';\n if(i + 4 < n and exp[i + 4] == \'0\') {\n y *= 10;\n } \n hash.insert({x, y});\n deno.push_back(y);\n }\n }\n\n int lc = 1;\n\n for(auto it : deno) lc = (lc * it) / __gcd(lc, it);\n\n string ans = "";\n\n vector<int> numer;\n\n for(auto it : hash) {\n if(it.second == lc) {\n numer.push_back(it.first);\n } else {\n numer.push_back(it.first * (lc / it.second));\n }\n }\n\n int a = 0;\n\n for(auto it : numer) a += it;\n\n if(a == 0) {\n return "0/1";\n }\n\n if(a < 0) {\n ans += \'-\';\n }\n a = abs(a);\n for(int i = 2; i <= max(a, lc); i++) {\n while(lc % i == 0 and a % i == 0) {\n lc /= i;\n a /= i;\n } \n\n }\n if(a >= 10) {\n ans += to_string(a);\n } else {\n ans += (a + \'0\');\n }\n ans += \'/\';\n if(lc >= 10) {\n ans += to_string(lc);\n } else {\n ans += (lc + \'0\');\n }\n\n return ans;\n }\n};\n```
2
0
['String', 'Simulation', 'C++']
0
fraction-addition-and-subtraction
Simple Approach beats 100% in Runtime
simple-approach-beats-100-in-runtime-by-fytac
\n\n# Intuition\nWhen faced with the problem of adding or subtracting fractions, my first thought is to align all the fractions to a common denominator. This si
secondwarbringer
NORMAL
2024-08-23T09:58:55.801406+00:00
2024-08-23T10:37:17.122270+00:00
30
false
![image.png](https://assets.leetcode.com/users/images/958b4435-a830-4782-9b2c-f9ceb37c9bbf_1724407115.038779.png)\n\n# Intuition\nWhen faced with the problem of adding or subtracting fractions, my first thought is to align all the fractions to a common denominator. This simplifies the problem since fractions with the same denominator can be directly added or subtracted by operating on their numerators. The key challenge lies in determining this common denominator and then correctly adjusting each fraction accordingly.\n\n# Approach\nParse the Input: First, we need to parse the string to extract the numerators and denominators. This involves carefully handling signs and ensuring that we correctly parse multi-digit numbers.\n\nFind the Least Common Denominator (LCD): Once all fractions are parsed, the next step is to determine the least common denominator (LCD) of all the fractions. The LCD is the smallest common multiple of all denominators, which allows us to bring all fractions to a common base.\n\nAdjust Numerators: After finding the LCD, adjust each fraction\u2019s numerator so that all fractions have the same denominator (LCD). This is done by multiplying each numerator by the appropriate factor, derived from the ratio between the LCD and the original denominator.\n\nSum the Numerators: With all fractions aligned to the same denominator, their numerators can be directly summed up or subtracted based on their signs.\n\nSimplify the Result: Finally, simplify the resulting fraction by dividing both the numerator and denominator by their greatest common divisor (GCD). This step ensures that the fraction is in its simplest form.\n\nEdge Case: Handle special cases, such as when the result is zero, by returning "0/1".\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\n int GCDFinder(int a, int b){\n if(b == 0){\n return abs(a);\n }\n return GCDFinder(b, a%b);\n }\n\n int LCMFinder(int a, int b){\n int gcd = GCDFinder(a, b);\n \n return abs(a*b)/gcd;\n }\n\n\npublic:\n string fractionAddition(string expression) {\n vector<int> nus, des;\n int i = 0;\n int n = expression.size();\n\n while (i < n) {\n int sign = 1;\n if (expression[i] == \'+\' || expression[i] == \'-\') {\n if (expression[i] == \'-\') sign = -1;\n i++;\n }\n\n int numerator = 0;\n while (i < n && isdigit(expression[i])) {\n numerator = numerator * 10 + (expression[i] - \'0\');\n i++;\n }\n numerator *= sign;\n\n i++; // skip the \'/\'\n\n int denominator = 0;\n while (i < n && isdigit(expression[i])) {\n denominator = denominator * 10 + (expression[i] - \'0\');\n i++;\n }\n\n nus.push_back(numerator);\n des.push_back(denominator);\n }\n\n int deno = des[0];\n for(int i = 1; i < des.size(); i++){\n // cout<<nus[i]<<" "<<dis[i]<<endl;\n deno = LCMFinder(deno, des[i]);\n }\n\n for(int i = 0; i < des.size(); i++){\n nus[i] = nus[i]*(deno/des[i]);\n }\n\n int numo = accumulate(nus.begin(), nus.end(), 0);\n // cout<<numo<<"/"<<dino<<endl;\n\n if(numo == 0){\n return "0/1";\n }\n int gcd = GCDFinder(numo, deno);\n numo = numo/gcd;\n deno = deno/gcd;\n\n return to_string(numo)+"/"+to_string(deno);\n }\n};\n```
2
0
['C++']
0
fraction-addition-and-subtraction
Simple Easy Intuition : Step-by-Step Guide in JAVA
simple-easy-intuition-step-by-step-guide-jtvi
Intuition\n Describe your first thoughts on how to solve this problem. \nHere\'s the intuition in simple words:\n\n### Simple Intuition for Adding Fractions:\n\
Saumo_05
NORMAL
2024-08-23T09:50:29.245012+00:00
2024-08-23T09:50:29.245034+00:00
69
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nHere\'s the intuition in simple words:\n\n### Simple Intuition for Adding Fractions:\n\n1. **Same Denominator**: \n - To add fractions, they need to have the same bottom number (denominator). If they don\'t, you can\'t add them directly.\n\n2. **Make Denominators the Same**: \n - You adjust the fractions so they have the same denominator by multiplying the bottom numbers together. This way, both fractions are "speaking the same language."\n\n3. **Adjust the Numerators**:\n - Once the denominators match, you adjust the top numbers (numerators) accordingly. This ensures each fraction is still the same value, just expressed differently.\n\n4. **Add the Numerators**:\n - Now that the denominators are the same, you simply add the numerators together to get the result.\n\n5. **Simplify**:\n - Finally, you simplify the fraction if possible, to make it as simple as possible.\n\nBy following these steps, you can correctly add fractions even if they start with different denominators.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nHere\u2019s the approach in simple words:\n\n1. **Start with a Common Denominator**:\n - When adding fractions, first make sure all the fractions have the same bottom number (denominator). You do this by multiplying the denominators together.\n\n2. **Adjust the Numerators**:\n - For each fraction, adjust the top number (numerator) so it matches the new common denominator. This keeps the value of the fraction the same.\n\n3. **Add the Numerators**:\n - Once all fractions have the same denominator, you add up the numerators (the top numbers) to get a new numerator.\n\n4. **Combine and Simplify**:\n - The final fraction will have the new numerator you calculated and the common denominator. If possible, simplify this fraction by dividing both the top and bottom by the greatest common divisor (GCD).\n\nThis approach lets you add fractions step by step, even if they have different denominators to begin with.\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public String fractionAddition(String expression) {\n // If the expression doesn\'t start with a minus, prepend a plus for easier parsing\n if (expression.charAt(0) != \'-\') {\n expression = \'+\' + expression;\n }\n\n int numeratorSum = 0;\n int denominatorProduct = 1;\n\n int i = 0;\n while (i < expression.length()) {\n // Parse the sign\n char sign = expression.charAt(i);\n i++;\n\n // Parse the numerator\n int numerator = 0;\n while (i < expression.length() && Character.isDigit(expression.charAt(i))) {\n numerator = numerator * 10 + (expression.charAt(i) - \'0\');\n i++;\n }\n if (sign == \'-\') {\n numerator = -numerator;\n }\n\n // Skip the \'/\' character\n i++;\n\n // Parse the denominator\n int denominator = 0;\n while (i < expression.length() && Character.isDigit(expression.charAt(i))) {\n denominator = denominator * 10 + (expression.charAt(i) - \'0\');\n i++;\n }\n\n // Compute the sum of numerators with a common denominator\n // a/b+c/d=(a*d+c*b)/(b*d);\n numeratorSum = numeratorSum * denominator + numerator * denominatorProduct;\n denominatorProduct *= denominator;\n \n // Simplify the fraction by dividing by the GCD\n int gcd = gcd(Math.abs(numeratorSum), denominatorProduct);\n numeratorSum /= gcd;\n denominatorProduct /= gcd;\n }\n\n return numeratorSum + "/" + denominatorProduct;\n }\n\n // Helper function to compute the Greatest Common Divisor (GCD)\n private int gcd(int a, int b) {\n if (b == 0) return a;\n return gcd(b, a % b);\n }\n}\n\n```
2
0
['Java']
0
fraction-addition-and-subtraction
🎯🔥Fraction Addition and Subtraction Simplified 🎯🔥
fraction-addition-and-subtraction-simpli-7jkl
# Intuition \n\n\n# Approach\n\nA. Initial Setup:\n\n1. num is the cumulative numerator, initialized to 0.\n2. den is the cumulative denominator, initialized
_kartikbanga_
NORMAL
2024-08-23T06:16:55.734121+00:00
2024-08-23T06:18:43.542027+00:00
19
false
<!-- # Intuition -->\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nA. Initial Setup:\n\n1. num is the cumulative numerator, initialized to 0.\n2. den is the cumulative denominator, initialized to 1.\n\nB. Iterating through the String:\n\n1. The loop runs through the string s character by character.\n2. It detects signs (+ or -) to determine whether the current fraction is positive or negative.\n3. It then extracts the numerator (curnum) and denominator (curden) of the current fraction.\n\nC. Combining Fractions:\n\n1. The fractions are combined using the formula:\nnew_num = num \xD7 curden + curnum \xD7 den\nnew_num = num \xD7 curden + curnum \xD7 den\n\n new_den = den \xD7 curden\n new_den = den \xD7 curden\n\n2. This formula handles addition and subtraction by incorporating the sign into curnum.\n\nC. Simplification:\n\n1. The greatest common divisor (GCD) of the resulting numerator and denominator is calculated using __gcd.\n2. Both num and den are divided by their GCD to simplify the fraction.\n\nD. Final Output:\n\n1. The function returns the simplified fraction as a string in the form "num/den".\n2. This approach ensures that all fractions in the input string are accurately combined and returned in their simplest form.\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(log(min(a,b))) which is taken by then recursive call stack by the __gcd function. It is nearly equal to O(1).\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n string fractionAddition(string s) {\n int n=s.length();\n int num=0,den=1;\n int i=0;\n while(i<n){\n bool isNegative=false;\n int curnum=0,curden=0;\n if(s[i]==\'-\' || s[i]==\'+\'){\n if(s[i]==\'-\')\n isNegative=true;\n i++;\n }\n while(s[i]>=48 && s[i]<=57){\n int number=s[i]-\'0\';\n curnum=curnum*10+number;\n i++;\n }\n if(isNegative)\n curnum*=-1;\n i++; //skip the "/" operator\n while(i<n && s[i]>=48 && s[i]<=57){\n int number=s[i]-\'0\';\n curden=curden*10+number;\n i++;\n }\n num=num*curden+curnum*den;\n den=den*curden;\n }\n int gcd=abs(__gcd(num,den));\n num/=gcd;\n den/=gcd;\n return to_string(num)+"/"+to_string(den);\n }\n};\n```
2
0
['Math', 'String', 'Simulation', 'C++']
0
fraction-addition-and-subtraction
100% beats || 0ms runtime Easy solution with Explaination ...
100-beats-0ms-runtime-easy-solution-with-1hqx
Intuition\nso,the thought is just to take numerator and denominator of two fraction and calculate their answer...\n\n# Approach\n- so,we first took numerator an
Alok_ayanokoji
NORMAL
2024-08-23T05:54:05.878392+00:00
2024-08-23T05:58:53.017567+00:00
222
false
# Intuition\nso,the thought is just to take numerator and denominator of two fraction and calculate their answer...\n\n# Approach\n- so,we first took numerator an denominator using for loop and conditions,and update our operation **op** which **needs to be operated**..\n\n- then we are using while loop an dgoing thorugh every single fraction and calculating their answer and updating our **nu & de** variable\n\n- we are doing this by taking **lcm** of denominators and then finally **hcf** for **minimizing** our **nu & de** varibales\n\n# Complexity\n- Time complexity:\n# - n=size of expression string\n**kind of constant for gcd calculation,max(32 operation)**\n- then stoi fxn -- **O(n)**\n- nearly around -- O(2*n);\n\n- Space complexity: **O(n)**\n- **max size of string s-> n**\n\n# Code\n```cpp []\nclass Solution {\n typedef long long ll;\n\npublic:\n string fractionAddition(string exp) {\n if (exp == "")\n return "0/1";\n ll nu, de;\n string s = "";\n char op = \'+\';\n int i = 0;\n for (; i < exp.size(); i++) {\n if (i != 0 && (exp[i] == \'+\' || exp[i] == \'-\')) {\n op = exp[i];\n de = stoi(s);\n s = "";\n i++;\n break;\n } else if (i == exp.size() - 1) {\n\n de = stoi(s + exp[i]);\n s = "";\n } else if (exp[i] == \'/\') {\n\n nu = stoi(s);\n\n s = "";\n } else {\n s += exp[i];\n }\n }\n ll tn, td;\n while (i < exp.size()) {\n if (exp[i] == \'+\' || exp[i] == \'-\') {\n td = stoi(s);\n s = "";\n\n ll lcm = (de * td) / (__gcd(de, td));\n ll upnu = nu * (lcm / de);\n ll tnu = tn * (lcm / td);\n\n if (op == \'+\') {\n nu = upnu + tnu;\n } else {\n nu = upnu - tnu;\n }\n de = lcm;\n\n ll hcf = abs(__gcd(nu, de));\n nu /= hcf;\n de /= hcf;\n\n op = exp[i];\n } else if (i == exp.size() - 1) {\n\n td = stoi(s + exp[i]);\n s = "";\n\n ll lcm = (de * 1ll * td) / (__gcd(de, td));\n ll upnu = nu * (lcm / de);\n ll tnu = tn * (lcm / td);\n\n if (op == \'+\') {\n nu = upnu + tnu;\n } else {\n nu = upnu - tnu;\n }\n de = lcm;\n\n ll hcf = abs(__gcd(nu, de));\n\n nu /= hcf;\n de /= hcf;\n\n } else if (exp[i] == \'/\') {\n tn = stoi(s);\n s = "";\n } else {\n s += exp[i];\n }\n\n i++;\n }\n s = "";\n s += to_string(nu);\n s += \'/\';\n s += to_string(de);\n return s;\n }\n};\n```\n\n---\n\n\n\n> please ***Upvote,thank you*** guys\n\n---\n\n\n# I hope it helped you :)
2
0
['C++']
0
fraction-addition-and-subtraction
Easy Solution | beats 100%
easy-solution-beats-100-by-sachinonly-wvni
Code\npython []\nfrom fractions import Fraction\n\nclass Solution(object):\n def fractionAddition(self, expression):\n def parse_expression(expression
Sachinonly__
NORMAL
2024-08-23T02:18:53.701506+00:00
2024-08-23T02:18:53.701538+00:00
777
false
# Code\n```python []\nfrom fractions import Fraction\n\nclass Solution(object):\n def fractionAddition(self, expression):\n def parse_expression(expression):\n # List to store parsed fractions\n fractions = []\n i = 0\n while i < len(expression):\n # Determine the sign of the fraction\n if expression[i] == \'+\' or expression[i] == \'-\':\n sign = expression[i]\n i += 1\n else:\n sign = \'+\'\n \n # Find the end of the fraction (numerator/denominator)\n num_start = i\n while i < len(expression) and expression[i] != \'+\' and expression[i] != \'-\':\n i += 1\n num_end = i\n \n # Extract numerator and denominator\n numerator, denominator = map(int, expression[num_start:num_end].split(\'/\'))\n \n # Apply the sign to the numerator if needed\n if sign == \'-\':\n numerator = -numerator\n \n # Add the fraction to the list\n fractions.append(Fraction(numerator, denominator))\n \n return fractions\n\n def calculate(fractions):\n # Sum all fractions and format the result\n result = sum(fractions)\n return "{}/{}".format(result.numerator, result.denominator)\n\n # Parse the expression and calculate the result\n fractions = parse_expression(expression)\n return calculate(fractions)\n```\n![unnamed.jpg](https://assets.leetcode.com/users/images/6dc0774f-093e-410e-b0f7-5b91d55685ad_1724379505.9005702.jpeg)\n
2
0
['Math', 'String', 'Simulation', 'Python', 'Python3']
0
fraction-addition-and-subtraction
Functional JavaScript | Common denominator + GCD
functional-javascript-common-denominator-lx92
\nfractionAddition=(\n e,\n // D divides all numbers in [1,...,10]\n D=2520,\n // GCD(a,b)\n $=(a,b)=>b?$(b,a%b):a\n)=>(\n e=e\n // spl
Serhii_Hrynko
NORMAL
2024-08-23T01:04:40.940098+00:00
2024-08-23T21:32:26.676881+00:00
123
false
```\nfractionAddition=(\n e,\n // D divides all numbers in [1,...,10]\n D=2520,\n // GCD(a,b)\n $=(a,b)=>b?$(b,a%b):a\n)=>(\n e=e\n // split into individual fractions keeping sign\n .split(/(?=[-+])/)\n // further split each fraction into numerator/denominator pair\n .map(x=>x.split`/`)\n // bring all fractions to common denominator D\n // find sum of numerators\n .reduce((s,[x,y])=>s+D*x/y,0),\n // find GCD of numerator and denominator\n $=$(D,e<0?-e:e),\n // divide both numerator and denominator by GCD\n // and return simplified fraction\n e/$+\'/\'+D/$\n)\n```
2
0
['JavaScript']
0
fraction-addition-and-subtraction
C++ | gcd + lcm | beats 100%
c-gcd-lcm-beats-100-by-zhanghx04-cs46
Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(n)\n Add your space complexity here, e.g. O(n) \n\n# Co
zhanghx04
NORMAL
2024-08-23T00:52:45.695762+00:00
2024-08-23T00:55:32.505719+00:00
589
false
# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\n struct frac_t {\n int above;\n int below;\n };\n\n void getFracs(vector<frac_t> &fracs, string &expr) {\n int N = expr.length();\n int idx = 0;\n int sign = 1;\n\n frac_t frac;\n int digit = 0;\n while (idx < N) {\n if (isdigit(expr[idx])) {\n digit = digit * 10 + (expr[idx] - \'0\');\n }\n else if (expr[idx] == \'/\') {\n frac.above = sign * digit;\n digit = 0;\n sign = 1;\n }\n else {\n frac.below = sign * digit;\n fracs.push_back(frac);\n\n digit = 0;\n sign = expr[idx] == \'+\' ? 1 : -1;\n }\n\n ++idx;\n }\n\n /* Add last frac to fracs */\n frac.below = sign * digit;\n fracs.push_back(frac);\n }\n\n void addFrac(frac_t &result, frac_t toAdd) {\n if (result.below == 0) {\n result = toAdd;\n return ;\n }\n\n /* Get the least common multiple */\n int below_lcm = lcm(result.below, toAdd.below);\n result.above *= below_lcm / result.below;\n toAdd.above *= below_lcm / toAdd.below;\n\n /* Update result */\n result.above += toAdd.above;\n result.below = below_lcm;\n }\n\npublic:\n string fractionAddition(string expression) {\n vector<frac_t> fracs;\n getFracs(fracs, expression);\n\n /* Frac Addition */\n frac_t result(0, 0);\n for (frac_t frac : fracs) {\n addFrac(result, frac);\n }\n\n /* Simplify the result */\n if (result.above == 0) {\n return "0/1";\n }\n\n /* Greatest common divisor */ \n int result_gcd = gcd(result.above, result.below);\n result.above /= result_gcd;\n result.below /= result_gcd;\n\n return to_string(result.above) + "/" + to_string(result.below);\n }\n};\n```
2
0
['Math', 'String', 'Simulation', 'C++']
1
fraction-addition-and-subtraction
C++ | Beats 100% | 0ms | T.C. & S.C. -> O(n)
c-beats-100-0ms-tc-sc-on-by-abhishek_k11-k2av
Intuition\n Describe your first thoughts on how to solve this problem. \nThe task is to evaluate a string representing a series of fraction additions and subtra
abhishek_k11
NORMAL
2024-08-23T00:34:21.636475+00:00
2024-08-23T03:46:41.012689+00:00
230
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe task is to evaluate a string representing a series of fraction additions and subtractions and return the result as a simplified fraction.\n\n---\n---\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n**1. Parsing the Expression:**\n\n- The input expression will be parsed to extract each fraction and its sign (positive or negative).\nFractions are of the form \xB1numerator/denominator and are separated by + or -.\n\n---\n\n\n**2. Initialization:**\n\n- Start by initializing the result with the first fraction. Determine its sign (positive or negative) and extract the numerator and denominator.\n\n---\n\n\n**3. Processing Fractions:**\n\n- For each subsequent fraction, determine its sign and extract the numerator and denominator.\n- Convert all fractions to have a common denominator using the least common multiple (LCM) of the denominators.\n- Update the result by adding or subtracting the new fraction\'s numerator (adjusted to the common denominator).\n\n---\n\n\n**4. Simplification:**\n\n- After processing all fractions, simplify the final result by dividing the numerator and denominator by their greatest common divisor (GCD).\n\n```\nint gcd(int a, int b) {\n return b == 0 ? a : gcd(b, a % b);\n}\n```\n\n---\n\n\n**5. Formatting the Result:**\n\n- If the numerator is zero, the result should be 0/1 to represent zero correctly.\nEnsure the result is in the format of numerator/denominator where the denominator is always positive.\n\n---\n\n\n---\n\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n---\n\n\n---\n\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int gcd(int a, int b) {\n return b == 0 ? a : gcd(b, a % b);\n }\n\n int getNum(int &i, const string &expression) {\n string temp = "";\n while (expression[i] != \'/\') {\n temp += expression[i];\n i++;\n }\n return stoi(temp);\n }\n\n int getDen(int &i, const string &expression) {\n string temp = "";\n while (i < expression.size() && expression[i] != \'+\' && expression[i] != \'-\') {\n temp += expression[i];\n i++;\n }\n return stoi(temp);\n }\n\n string fractionAddition(string expression) {\n int s1 = 1, i = 0;\n\n if (expression[i] == \'-\') {\n s1 = -1;\n i++;\n }\n\n int num1 = getNum(i, expression);\n i++;\n int den1 = getDen(i, expression);\n\n while (i < expression.size()) {\n int s2 = expression[i] == \'-\' ? -1 : 1;\n i++;\n\n int num2 = getNum(i, expression);\n i++;\n int den2 = getDen(i, expression);\n\n int lcm = (den2 * den1) / gcd(den1, den2);\n num1 = s1 * num1 * (lcm / den1) + s2 * num2 * (lcm / den2);\n den1 = lcm;\n\n s1 = (num1 < 0) ? -1 : 1;\n if (num1 < 0) num1 *= -1;\n }\n\n int gc = gcd(num1, den1);\n if (gc > 1) {\n num1 /= gc;\n den1 /= gc;\n }\n\n return (s1 == -1 ? "-" : "") + to_string(num1) + "/" + to_string(den1);\n }\n};\n```\n![Please Upvote (3).jpg](https://assets.leetcode.com/users/images/3fc0ac4f-5a5f-410f-9895-7629196511fb_1724375360.0657377.jpeg)\n\n\n\n\n
2
0
['Math', 'String', 'Simulation', 'C++']
0
fraction-addition-and-subtraction
[Kotlin] Irreducible Fractions: Parsing and Summation Techniques | 139ms
kotlin-irreducible-fractions-parsing-and-78ir
Intuition\nThe problem involves parsing a string representing an expression of fraction addition and subtraction, performing the addition, and then simplifying
teogor
NORMAL
2024-05-02T07:06:44.906130+00:00
2024-05-02T07:06:44.906159+00:00
146
false
# Intuition\nThe problem involves parsing a string representing an expression of fraction addition and subtraction, performing the addition, and then simplifying the resulting fraction. The key challenge is to correctly handle both positive and negative fractions and to simplify the final fraction to its irreducible form.\n\n# Approach\n1. **Parsing Fractions:** To parse the expression, we iterate over each character in the expression. Whenever we encounter a \'+\' or \'-\' character, we split the expression at that point to extract the fraction. We then convert the substrings into integer pairs representing numerators and denominators.\n \n2. **Adding Fractions:** Once we have parsed all the fractions, we need to add them up to get the sum. We iterate over the list of parsed fractions and accumulate the sum in two variables: numerator and denominator. We perform the addition by multiplying each fraction\'s numerator by the product of the denominators and adding it to the product of the denominators multiplied by the numerator.\n\n3. **Simplifying Fraction:** After obtaining the sum of all fractions, we need to simplify the resulting fraction. To do this, we find the greatest common divisor (GCD) of the numerator and denominator using the Euclidean algorithm. Then, we divide both the numerator and denominator by their GCD to obtain the simplified fraction.\n\n4. **Returning Result:** Finally, we return the simplified fraction as a string in the required format, ensuring that negative fractions are represented correctly and that the denominator is always positive.\n\nThis approach ensures that we correctly handle both positive and negative fractions, perform the addition accurately, and simplify the resulting fraction to its irreducible form.\n\n# Complexity\n- **Time complexity:** The time complexity of parsing the fractions, performing addition, and simplifying the fraction is linear, i.e., O(n), where n is the length of the given expression.\n \n- **Space complexity:** The space complexity is also linear, O(n), where n is the number of fractions in the expression.\n\n# Code\n```\nclass Solution {\n fun fractionAddition(expression: String): String {\n val fractions = parseFractions(expression)\n val result = addFractions(fractions)\n return simplifyFraction(result)\n }\n\n private fun parseFractions(expression: String): List<Pair<Int, Int>> {\n val fractions = mutableListOf<Pair<Int, Int>>()\n var numerator = 0\n var denominator = 0\n var sign = 1\n var number = ""\n\n for (char in expression) {\n when (char) {\n \'+\', \'-\' -> {\n if (number.isNotEmpty()) {\n val fraction = number.split("/")\n numerator = sign * fraction[0].toInt()\n denominator = fraction[1].toInt()\n fractions.add(Pair(numerator, denominator))\n }\n sign = if (char == \'+\') 1 else -1\n number = ""\n }\n else -> number += char\n }\n }\n\n if (number.isNotEmpty()) {\n val fraction = number.split("/")\n numerator = sign * fraction[0].toInt()\n denominator = fraction[1].toInt()\n fractions.add(Pair(numerator, denominator))\n }\n\n return fractions\n }\n\n private fun addFractions(fractions: List<Pair<Int, Int>>): Pair<Int, Int> {\n var numerator = 0\n var denominator = 1\n\n for ((num, denom) in fractions) {\n numerator = numerator * denom + num * denominator\n denominator *= denom\n }\n\n return Pair(numerator, denominator)\n }\n\n private fun gcd(a: Int, b: Int): Int {\n return if (b == 0) a else gcd(b, a % b)\n }\n\n private fun simplifyFraction(fraction: Pair<Int, Int>): String {\n val numerator = fraction.first\n val denominator = fraction.second\n\n if (numerator == 0) return "0/1"\n \n val gcd = gcd(Math.abs(numerator), Math.abs(denominator))\n val sign = if (numerator < 0 || denominator < 0) "-" else ""\n \n val simplifiedNumerator = Math.abs(numerator) / gcd\n val simplifiedDenominator = Math.abs(denominator) / gcd\n\n return "$sign$simplifiedNumerator/$simplifiedDenominator"\n }\n}\n\n```
2
1
['Math', 'String', 'Simulation', 'Kotlin']
0
fraction-addition-and-subtraction
✅Easy Brute Force Solution✅
easy-brute-force-solution-by-hacker363-uy68
Intuition\n Describe your first thoughts on how to solve this problem. \nThe code is designed to add fractions together and simplify the result to its simplest
hacker363
NORMAL
2023-10-17T07:40:15.605705+00:00
2023-10-17T07:40:15.605726+00:00
673
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe code is designed to add fractions together and simplify the result to its simplest form. It handles both positive and negative fractions, and its goal is to perform this addition and provide the result as a simplified fraction.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe input expression is split into a list of strings, where each string represents a fraction to be added. The fractions are separated by the \'+\' sign.\nThe code then iterates through this list, parsing each fraction by splitting it based on the \'/\' character.\nWhile parsing each fraction, it keeps track of the numerators and denominators separately.\nThe code applies a sign depending on whether a \'-\' sign is present within the fraction.\nThe Least Common Denominator (LCD) is calculated for all denominators in the list using the reduce function from the functools module.\nOnce the LCD is determined, each numerator is adjusted to have a common denominator by multiplying it by (d//abs(denominator[i])), ensuring that all fractions have the same denominator.\nThe code sums up all the numerators to get the new numerator for the result.\nIt calculates the greatest common divisor (GCD) of the numerator and denominator using the math.gcd function.\nFinally, the code simplifies the fraction by dividing both the numerator and denominator by their GCD to get the simplest form of the result.\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nSplitting the input expression by \'+\' characters and then iterating through the list of fractions takes O(n) time, where n is the length of the expression.\nWithin the iteration, parsing each fraction also takes O(n) time.\nCalculating the Least Common Denominator (LCD) using the reduce function takes O(n) time, as it iterates through the list of denominators.\nAdjusting numerators for a common denominator and summing them up also takes O(n) time.\nCalculating the greatest common divisor (GCD) using the math.gcd function takes O(n) time.\nOverall, the time complexity of the code is O(n).\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is influenced by the data structures used to store fractions (numerators and denominators), the list of fractions, and other variables.\nThe space used to store fractions and the list of fractions is O(n) in the worst case because they grow linearly with the input length.\nOther variables used for temporary calculations, such as the LCD, numerators, denominators, and the result, do not significantly impact the space complexity.\nTherefore, the overall space complexity is O(n) due to the storage of fractions and the list of fractions.\n\n\u2B06**IF IT FIND\'S HELPFUL PLAESE UPVOTE**\u2B06\n# Code\n```\nclass Solution:\n def fractionAddition(self, expression: str) -> str:\n l = expression.split(\'+\')\n\n num = []\n dum = []\n for i in l:\n temp = i.split(\'/\')\n n= True\n\n for i in temp:\n if \'-\' in i and len(i)>2 and i.index(\'-\')>0:\n index = i.index(\'-\')\n\n dum.append(int(i[:index]))\n num.append(int(i[index:]))\n n=False\n else:\n if n:\n num.append(int(i))\n n = False\n else:\n dum.append(int(i))\n n=True\n d = reduce(math.lcm, dum)\n for i in range(len(num)):\n num[i] = num[i]*(d//abs(dum[i]))\n n = sum(num)\n return str(n//gcd(n,d))+"/"+str(d//gcd(n,d))\n```\n\u2B06**IF IT FIND\'S HELPFUL PLAESE UPVOTE**\u2B06
2
0
['Python3']
0
fraction-addition-and-subtraction
✅✅C++ in O(n) Solution...Detailed...No In-built functions used.
c-in-on-solutiondetailedno-in-built-func-lvu9
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nHere simple concept of LCM and GCD are used.\nAlso String is traversed in
Heisenberg2003
NORMAL
2022-11-04T18:52:03.086916+00:00
2022-11-04T18:52:03.086961+00:00
332
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nHere simple concept of LCM and GCD are used.\nAlso String is traversed in a way to first store elements of fractions in pair.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution {\npublic:\n int lcm(int a,int b)\n {\n return (a/gcd(a,b))*b;\n }\n int gcd(int a,int b)\n {\n return b==0?a:gcd(b,a%b);\n }\n string fractionAddition(string expression) \n {\n if(expression[0]!=\'-\')\n {\n expression.insert(0,"+");\n }\n vector<pair<int,int>>numden;\n bool leave=false,ispos=true;\n int tempnum;\n int i=0;\n pair<int,int>temp;\n while(1)\n {\n tempnum=0;\n if(expression[i]==\'+\')\n {\n ispos=true;\n i++;\n }\n else if(expression[i]==\'-\')\n {\n ispos=false;\n i++;\n }\n while(expression[i]<=\'9\' && expression[i]>=\'0\')\n {\n tempnum*=10;\n tempnum+=(int)(expression[i]-\'0\');\n i++;\n if(expression[i]==\'/\')\n {\n i++;\n break;\n }\n }\n if(ispos)\n {\n temp.first=tempnum;\n }\n if(!ispos)\n {\n temp.first=-tempnum;\n }\n tempnum=0;\n while(expression[i]<=\'9\' && expression[i]>=\'0\')\n {\n tempnum*=10;\n tempnum+=(int)(expression[i]-\'0\');\n i++;\n if(i==expression.size())\n {\n leave=true;\n break;\n }\n if(expression[i]==\'+\' || expression[i]==\'-\')\n {\n break;\n }\n }\n temp.second=tempnum;\n numden.push_back(temp);\n if(leave)\n {\n break;\n }\n }\n string ans;\n for(i=0;i<numden.size();i++)\n {\n int GCD=gcd(abs(numden[i].first),abs(numden[i].second));\n numden[i].first/=GCD;\n numden[i].second/=GCD;\n }\n int LCM=numden[0].second;\n for(i=1;i<numden.size();i++)\n {\n LCM=lcm(LCM,numden[i].second);\n }\n int deno=LCM;\n int nume=0;\n for(i=0;i<numden.size();i++)\n {\n nume+=(LCM*numden[i].first)/numden[i].second;\n }\n if(nume<0)\n {\n ans.push_back(\'-\');\n nume=-nume;\n }\n int GCD=gcd(nume,deno);\n nume/=GCD;\n deno/=GCD;\n string numerator,denominator;\n if(nume==0)\n {\n numerator="0";\n }\n while(nume!=0)\n {\n numerator.push_back((char)(nume%10+48));\n nume/=10;\n }\n reverse(numerator.begin(),numerator.end());\n if(deno==0)\n {\n denominator="0";\n }\n while(deno!=0)\n {\n denominator.push_back((char)(deno%10+48));\n deno/=10;\n }\n reverse(denominator.begin(),denominator.end());\n ans.append(numerator);\n ans.push_back(\'/\');\n ans.append(denominator);\n return ans;\n }\n};\n```
2
0
['C++']
0
fraction-addition-and-subtraction
Java Solution
java-solution-by-aditya001-js3d
\nclass Solution {\n public String fractionAddition(String expression) {\n List<Integer> num = new ArrayList<>();\n List<Integer> denom = new A
Aditya001
NORMAL
2022-08-18T06:49:26.990551+00:00
2022-08-18T06:49:26.990582+00:00
849
false
```\nclass Solution {\n public String fractionAddition(String expression) {\n List<Integer> num = new ArrayList<>();\n List<Integer> denom = new ArrayList<>();\n List<String> ope_ope_no_mi = new ArrayList<>();\n int n = expression.length();\n if(expression.charAt(0)!=\'-\'){\n ope_ope_no_mi.add("+");\n }\n for(int i=0;i<n;i++){\n if(expression.charAt(i)==\'-\' || expression.charAt(i)==\'+\'){\n ope_ope_no_mi.add(expression.charAt(i)+"");\n }\n }\n expression = expression.replace(\'+\',\'.\');\n expression = expression.replace(\'-\',\'.\');\n String[] fraction = expression.split("\\\\.");\n for(String i: fraction){\n if(i.length()>1){\n String[] frac = i.split("/");\n num.add(Integer.valueOf(frac[0]));\n denom.add(Integer.valueOf(frac[1]));\n }\n }\n n = num.size();\n // System.out.println(num);\n // System.out.println(denom);\n // System.out.println(ope_ope_no_mi);\n // System.out.print(lcm(denom, 0)+ "\\n");\n int denominator = lcm(denom,0);\n int numerator = 0;\n for(int i=0;i<n;i++){\n if(ope_ope_no_mi.get(i).equals("+")){\n numerator += num.get(i)*(denominator/denom.get(i));\n }else{\n numerator -= num.get(i)*(denominator/denom.get(i));\n }\n }\n \n int div = gcd(numerator,denominator);\n numerator /= div;\n denominator /= div;\n String sign = "";\n \n if(numerator<0 && denominator>0){\n numerator *=-1;\n sign = "-";\n }\n if(numerator>0 && denominator<0){\n denominator *= -1;\n sign = "-";\n }\n return sign+String.valueOf(numerator)+"/"+String.valueOf(denominator);\n }\n \n public int gcd(int a, int b) { \n return b == 0? a:gcd(b, a % b); \n }\n \n public int lcm(List<Integer> arr, int idx){\n if (idx == arr.size()- 1){\n return arr.get(idx);\n }\n int a = arr.get(idx);\n int b = lcm(arr, idx+1);\n return (a*b/gcd(a,b)); //\n }\n}\n```
2
0
['Java']
1
fraction-addition-and-subtraction
Python two solutions👀. Short and Concise✅. Library and No Library🔥
python-two-solutions-short-and-concise-l-zecx
1. A short solution using fractions from python stdlib\n\nfrom fractions import Fraction\nclass Solution:\n def fractionAddition(self, expression: str) -> st
blest
NORMAL
2022-08-15T16:23:13.021375+00:00
2022-08-25T08:59:42.452578+00:00
420
false
**1. A short solution using [fractions](https://docs.python.org/3/library/fractions.html) from python stdlib**\n```\nfrom fractions import Fraction\nclass Solution:\n def fractionAddition(self, expression: str) -> str:\n ans = Fraction(eval(expression))\n return \'/\'.join(map(str, ans.limit_denominator().as_integer_ratio()))\n```\n\n**2. A consise no library solution**\n```\nclass Solution:\n def fractionAddition(self, expression: str) -> str:\n # get all the fractions separately: e.g: "-1/2+1/2" -> [\'-1/2\', \'1/2\']\n fractions = re.findall(r\'-*\\d+/\\d+\', expression)\n \n # separate the numerators and denominators-> [\'-1/2\', \'1/2\'] -> [-1, 1] , [2, 2]\n numerators, denominators = [], []\n for fraction in fractions:\n n, d = map(int, fraction.split(\'/\'))\n numerators.append(n)\n denominators.append(d)\n \n # find the lcm of the denominators\n lcm = reduce(math.lcm, denominators)\n # find with what number the denominators and numerators are to be multipled with\n multiples = [lcm // d for d in denominators]\n # multiply the multipler for each of the numerator\n numerators = [n*m for n, m in zip(numerators, multiples)]\n # multiply the multipler for each of the denominator\n denominators = [d*m for d, m in zip(denominators, multiples)]\n \n # now the denominators are all equal; so take just one; and add the numerator\n numerator, denominator = sum(numerators), denominators[0]\n # find if the numerator and denomitors can further of be reduced...\n gcd = math.gcd(numerator, denominator)\n numerator //= gcd\n denominator //= gcd\n return f\'{numerator}/{denominator}\'\n```
2
0
['Math', 'Python3']
0