├── .vscode └── settings.json ├── Company-wise ├── Amazon │ ├── q_1.js │ ├── q_2.js │ ├── q_3.js │ ├── q_4.js │ ├── q_5.js │ ├── q_6.js │ ├── q_7.js │ ├── q_8.js │ ├── q_9.js │ ├── q_a10.js │ ├── q_a11.js │ ├── q_a12.js │ ├── q_a13.js │ ├── q_a14.js │ ├── q_a15.js │ ├── q_a16.js │ ├── q_a17.js │ ├── q_a18.js │ ├── q_a19.js │ ├── q_a20.js │ └── q_a21.js ├── Facebook │ ├── q_1.js │ ├── q_2.js │ ├── q_3.js │ ├── q_4.js │ ├── q_5.js │ ├── q_6.js │ ├── q_7.js │ ├── q_8.js │ ├── q_9.js │ ├── q_a10.js │ ├── q_a11.js │ ├── q_a12.js │ ├── q_a13.js │ ├── q_a14.js │ ├── q_a15.js │ ├── q_a16.js │ ├── q_a17.js │ ├── q_a18.js │ ├── q_a19.js │ ├── q_a20.js │ ├── q_a21.js │ ├── q_a22.js │ ├── q_a23.js │ ├── q_a24.js │ ├── q_a25.js │ ├── q_a26.js │ ├── q_a27.js │ ├── q_a28.js │ ├── q_a29.js │ ├── q_a30.js │ ├── q_a31.js │ ├── q_a32.js │ ├── q_a33.js │ ├── q_a34.js │ ├── q_a35.js │ ├── q_a36.js │ ├── q_a37.js │ ├── q_a38.js │ ├── q_a39.js │ ├── q_a40.js │ ├── q_a41.js │ ├── q_a42.js │ ├── q_a43.js │ ├── q_a44.js │ ├── q_a45.js │ ├── q_a46.js │ ├── q_a47.js │ ├── q_a48.js │ ├── q_a49.js │ ├── q_a50.js │ ├── q_a51.js │ ├── q_a52.js │ ├── q_a53.js │ ├── q_a54.js │ ├── q_a55.js │ ├── q_a56.js │ ├── q_a57.js │ ├── q_a58.js │ ├── q_a59.js │ ├── q_a60.js │ ├── q_a61.js │ ├── q_a62.js │ ├── q_a63.js │ ├── q_a64.js │ ├── q_a65.js │ └── q_a66.js ├── Goldman_Sachs │ ├── q_1.js │ └── q_2.js ├── Google │ ├── q_1.js │ ├── q_2.js │ ├── q_3.js │ ├── q_4.js │ ├── q_5.js │ ├── q_6.js │ ├── q_7.js │ └── q_8.js └── Microsoft │ ├── q_1.js │ ├── q_2.js │ ├── q_3.js │ ├── q_4.js │ ├── q_5.js │ ├── q_6.js │ ├── q_7.js │ ├── q_8.js │ ├── q_9.js │ ├── q_a10.js │ ├── q_a11.js │ ├── q_a12.js │ ├── q_a13.js │ ├── q_a14.js │ ├── q_a15.js │ ├── q_a16.js │ ├── q_a17.js │ └── q_a18.js ├── README.md ├── Random_700_Qs ├── a_First 100 │ ├── q_1.js │ ├── q_2.js │ ├── q_3.js │ ├── q_4.js │ ├── q_5.js │ ├── q_6.js │ ├── q_7.js │ ├── q_8.js │ ├── q_9.js │ ├── q_a10.js │ ├── q_a11.js │ ├── q_a12.js │ ├── q_a13.js │ ├── q_a14.js │ ├── q_a15.js │ ├── q_a16.js │ ├── q_a17.js │ ├── q_a18.js │ ├── q_a19.js │ ├── q_a20.js │ ├── q_a21.js │ ├── q_a22.js │ ├── q_a23.js │ ├── q_a24.js │ ├── q_a25.js │ ├── q_a26.js │ ├── q_a27.js │ ├── q_a28.js │ ├── q_a29.js │ ├── q_a30.js │ ├── q_a31.js │ ├── q_a32.js │ ├── q_a33.js │ ├── q_a34.js │ ├── q_a35.js │ ├── q_a36.js │ ├── q_a37.js │ ├── q_a38.js │ ├── q_a39.js │ ├── q_a40.js │ ├── q_a41.js │ ├── q_a42.js │ ├── q_a43.js │ ├── q_a44.js │ ├── q_a45.js │ ├── q_a46.js │ ├── q_a47.js │ ├── q_a48.js │ ├── q_a49.js │ ├── q_a50.js │ ├── q_a51.js │ ├── q_a52.js │ ├── q_a53.js │ ├── q_a54.js │ ├── q_a55.js │ ├── q_a56.js │ ├── q_a57.js │ ├── q_a58.js │ ├── q_a59.js │ ├── q_a60.js │ ├── q_a61.js │ ├── q_a62.js │ ├── q_a63.js │ ├── q_a64.js │ ├── q_a65.js │ ├── q_a66.js │ ├── q_a67.js │ ├── q_a68.js │ ├── q_a69.js │ ├── q_a70.js │ ├── q_a71.js │ ├── q_a72.js │ ├── q_a73.js │ ├── q_a74.js │ ├── q_a75.js │ ├── q_a76.js │ ├── q_a77.js │ ├── q_a78.js │ ├── q_a79.js │ ├── q_a80.js │ ├── q_a81.js │ ├── q_a82.js │ ├── q_a83.js │ ├── q_a84.js │ ├── q_a85.js │ ├── q_a86.js │ ├── q_a87.js │ ├── q_a88.js │ ├── q_a89.js │ ├── q_a90.js │ ├── q_a91.js │ ├── q_a92.js │ ├── q_a93.js │ ├── q_a94.js │ ├── q_a95.js │ ├── q_a96.js │ ├── q_a97.js │ ├── q_a98.js │ ├── q_a99.js │ └── q_ab100.js ├── b_Second 100 │ ├── q_a101.js │ ├── q_a102.js │ ├── q_a103.js │ ├── q_a104.js │ ├── q_a105.js │ ├── q_a106.js │ ├── q_a107.js │ ├── q_a108.js │ ├── q_a109.js │ ├── q_a110.js │ ├── q_a111.js │ ├── q_a112.js │ ├── q_a113.js │ ├── q_a114.js │ ├── q_a115.js │ ├── q_a116.js │ ├── q_a117.js │ ├── q_a118.js │ ├── q_a119.js │ ├── q_a120.js │ ├── q_a121.js │ ├── q_a122.js │ ├── q_a123.js │ ├── q_a124.js │ ├── q_a125.js │ ├── q_a126.js │ ├── q_a127.js │ ├── q_a128.js │ ├── q_a129.js │ ├── q_a130.js │ ├── q_a131.js │ ├── q_a132.js │ ├── q_a133.js │ ├── q_a134.js │ ├── q_a135.js │ ├── q_a136.js │ ├── q_a137.js │ ├── q_a138.js │ ├── q_a139.js │ ├── q_a140.js │ ├── q_a141.js │ ├── q_a142.js │ ├── q_a143.js │ ├── q_a144.js │ ├── q_a145.js │ ├── q_a146.js │ ├── q_a147.js │ ├── q_a148.js │ ├── q_a149.js │ ├── q_a150.js │ ├── q_a151.js │ ├── q_a152.js │ ├── q_a153.js │ ├── q_a154.js │ ├── q_a155.js │ ├── q_a156.js │ ├── q_a157.js │ ├── q_a158.js │ ├── q_a159.js │ ├── q_a160.js │ ├── q_a161.js │ ├── q_a162.js │ ├── q_a163.js │ ├── q_a164.js │ ├── q_a165.js │ ├── q_a166.js │ ├── q_a167.js │ ├── q_a168.js │ ├── q_a169.js │ ├── q_a170.js │ ├── q_a171.js │ ├── q_a172.js │ ├── q_a173.js │ ├── q_a174.js │ ├── q_a175.js │ ├── q_a176.js │ ├── q_a177.js │ ├── q_a178.js │ ├── q_a179.js │ ├── q_a180.js │ ├── q_a181.js │ ├── q_a182.js │ ├── q_a183.js │ ├── q_a184.js │ ├── q_a185.js │ ├── q_a186.js │ ├── q_a187.js │ ├── q_a188.js │ ├── q_a189.js │ ├── q_a190.js │ ├── q_a191.js │ ├── q_a192.js │ ├── q_a193.js │ ├── q_a194.js │ ├── q_a195.js │ ├── q_a196.js │ ├── q_a197.js │ ├── q_a198.js │ ├── q_a199.js │ └── q_a200.js ├── c_Third 100 │ ├── q_a201.js │ ├── q_a202.js │ ├── q_a203.js │ ├── q_a204.js │ ├── q_a205.js │ ├── q_a206.js │ ├── q_a207.js │ ├── q_a208.js │ ├── q_a209.js │ ├── q_a210.js │ ├── q_a211.js │ ├── q_a212.js │ ├── q_a213.js │ ├── q_a214.js │ ├── q_a215.js │ ├── q_a216.js │ ├── q_a217.js │ ├── q_a218.js │ ├── q_a219.js │ ├── q_a220.js │ ├── q_a221.js │ ├── q_a222.js │ ├── q_a223.js │ ├── q_a224.js │ ├── q_a225.js │ ├── q_a226.js │ ├── q_a227.js │ ├── q_a228.js │ ├── q_a229.js │ ├── q_a230.js │ ├── q_a231.js │ ├── q_a232.js │ ├── q_a233.js │ ├── q_a234.js │ ├── q_a235.js │ ├── q_a236.js │ ├── q_a237.js │ ├── q_a238.js │ ├── q_a239.js │ ├── q_a240.js │ ├── q_a241.js │ ├── q_a242.js │ ├── q_a243.js │ ├── q_a244.js │ ├── q_a245.js │ ├── q_a246.js │ ├── q_a247.js │ ├── q_a248.js │ ├── q_a249.js │ ├── q_a250.js │ ├── q_a251.js │ ├── q_a252.js │ ├── q_a253.js │ ├── q_a254.js │ ├── q_a255.js │ ├── q_a256.js │ ├── q_a257.js │ ├── q_a258.js │ ├── q_a259.js │ ├── q_a260.js │ ├── q_a261.js │ ├── q_a262.js │ ├── q_a263.js │ ├── q_a264.js │ ├── q_a265.js │ ├── q_a266.js │ ├── q_a267.js │ ├── q_a268.js │ ├── q_a269.js │ ├── q_a270.js │ ├── q_a271.js │ ├── q_a272.js │ ├── q_a273.js │ ├── q_a274.js │ ├── q_a275.js │ ├── q_a276.js │ ├── q_a277.js │ ├── q_a278.js │ ├── q_a279.js │ ├── q_a280.js │ ├── q_a281.js │ ├── q_a282.js │ ├── q_a283.js │ ├── q_a284.js │ ├── q_a285.js │ ├── q_a286.js │ ├── q_a287.js │ ├── q_a288.js │ ├── q_a289.js │ ├── q_a290.js │ ├── q_a291.js │ ├── q_a292.js │ ├── q_a293.js │ ├── q_a294.js │ ├── q_a295.js │ ├── q_a296.js │ ├── q_a297.js │ ├── q_a298.js │ ├── q_a299.js │ └── q_a300.js ├── d_Fourth 100 │ ├── q_a301.js │ ├── q_a302.js │ ├── q_a303.js │ ├── q_a304.js │ ├── q_a305.js │ ├── q_a306.js │ ├── q_a307.js │ ├── q_a308.js │ ├── q_a309.js │ ├── q_a310.js │ ├── q_a311.js │ ├── q_a312.js │ ├── q_a313.js │ ├── q_a314.js │ ├── q_a315.js │ ├── q_a316.js │ ├── q_a317.js │ ├── q_a318.js │ ├── q_a319.js │ ├── q_a320.js │ ├── q_a321.js │ ├── q_a322.js │ ├── q_a323.js │ ├── q_a324.js │ ├── q_a325.js │ ├── q_a326.js │ ├── q_a327.js │ ├── q_a328.js │ ├── q_a329.js │ ├── q_a330.js │ ├── q_a331.js │ ├── q_a332.js │ ├── q_a333.js │ ├── q_a334.js │ ├── q_a335.js │ ├── q_a336.js │ ├── q_a337.js │ ├── q_a338.js │ ├── q_a339.js │ ├── q_a340.js │ ├── q_a341.js │ ├── q_a342.js │ ├── q_a343.js │ ├── q_a344.js │ ├── q_a345.js │ ├── q_a346.js │ ├── q_a347.js │ ├── q_a348.js │ ├── q_a349.js │ ├── q_a350.js │ ├── q_a351.js │ ├── q_a352.js │ ├── q_a353.js │ ├── q_a354.js │ ├── q_a355.js │ ├── q_a356.js │ ├── q_a357.js │ ├── q_a358.js │ ├── q_a359.js │ ├── q_a360.js │ ├── q_a361.js │ ├── q_a362.js │ ├── q_a363.js │ ├── q_a364.js │ ├── q_a365.js │ ├── q_a366.js │ ├── q_a367.js │ ├── q_a368.js │ ├── q_a369.js │ ├── q_a370.js │ ├── q_a371.js │ ├── q_a372.js │ ├── q_a373.js │ ├── q_a374.js │ ├── q_a375.js │ ├── q_a376.js │ ├── q_a377.js │ ├── q_a378.js │ ├── q_a379.js │ ├── q_a380.js │ ├── q_a381.js │ ├── q_a382.js │ ├── q_a383.js │ ├── q_a384.js │ ├── q_a385.js │ ├── q_a386.js │ ├── q_a387.js │ ├── q_a388.js │ ├── q_a389.js │ ├── q_a390.js │ ├── q_a391.js │ ├── q_a392.js │ ├── q_a393.js │ ├── q_a394.js │ ├── q_a395.js │ ├── q_a396.js │ ├── q_a397.js │ ├── q_a398.js │ ├── q_a399.js │ └── q_a400.js ├── e_Fifth_100 │ ├── q_a401.js │ ├── q_a402.js │ ├── q_a403.js │ ├── q_a404.js │ ├── q_a405.js │ ├── q_a406.js │ ├── q_a407.js │ ├── q_a408.js │ ├── q_a409.js │ ├── q_a410.js │ ├── q_a411.js │ ├── q_a412.js │ ├── q_a413.js │ ├── q_a414.js │ ├── q_a415.js │ ├── q_a416.js │ ├── q_a417.js │ ├── q_a418.js │ ├── q_a419.js │ ├── q_a420.js │ ├── q_a421.js │ ├── q_a422.js │ ├── q_a423.js │ ├── q_a424.js │ ├── q_a425.js │ ├── q_a426.js │ ├── q_a427.js │ ├── q_a428.js │ ├── q_a429.js │ ├── q_a430.js │ ├── q_a431.js │ ├── q_a432.js │ ├── q_a433.js │ ├── q_a434.js │ ├── q_a435.js │ ├── q_a436.js │ ├── q_a437.js │ ├── q_a438.js │ ├── q_a439.js │ ├── q_a440.js │ ├── q_a441.js │ ├── q_a442.js │ ├── q_a443.js │ ├── q_a444.js │ ├── q_a445.js │ ├── q_a446.js │ ├── q_a447.js │ ├── q_a448.js │ ├── q_a449.js │ ├── q_a450.js │ ├── q_a451.js │ ├── q_a452.js │ ├── q_a453.js │ ├── q_a454.js │ ├── q_a455.js │ ├── q_a456.js │ ├── q_a457.js │ ├── q_a458.js │ ├── q_a459.js │ ├── q_a460.js │ ├── q_a461.js │ ├── q_a462.js │ ├── q_a463.js │ ├── q_a464.js │ ├── q_a465.js │ ├── q_a466.js │ ├── q_a467.js │ ├── q_a468.js │ ├── q_a469.js │ ├── q_a470.js │ ├── q_a471.js │ ├── q_a472.js │ ├── q_a473.js │ ├── q_a474.js │ ├── q_a475.js │ ├── q_a476.js │ ├── q_a477.js │ ├── q_a478.js │ ├── q_a479.js │ ├── q_a480.js │ ├── q_a481.js │ ├── q_a482.js │ ├── q_a483.js │ ├── q_a484.js │ ├── q_a485.js │ ├── q_a486.js │ ├── q_a487.js │ ├── q_a488.js │ ├── q_a489.js │ ├── q_a490.js │ ├── q_a491.js │ ├── q_a492.js │ ├── q_a493.js │ ├── q_a494.js │ ├── q_a495.js │ ├── q_a496.js │ ├── q_a497.js │ ├── q_a498.js │ ├── q_a499.js │ └── q_a500.js ├── f_Sixth_100 │ ├── q_a501.js │ ├── q_a502.js │ ├── q_a503.js │ ├── q_a504.js │ ├── q_a505.js │ ├── q_a506.js │ ├── q_a507.js │ ├── q_a508.js │ ├── q_a509.js │ ├── q_a510.js │ ├── q_a511.js │ ├── q_a512.js │ ├── q_a513.js │ ├── q_a514.js │ ├── q_a515.js │ ├── q_a516.js │ ├── q_a517.js │ ├── q_a518.js │ ├── q_a519.js │ ├── q_a520.js │ ├── q_a521.js │ ├── q_a522.js │ ├── q_a523.js │ ├── q_a524.js │ ├── q_a525.js │ ├── q_a526.js │ ├── q_a527.js │ ├── q_a528.js │ ├── q_a529.js │ ├── q_a530.js │ ├── q_a531.js │ ├── q_a532.js │ ├── q_a533.js │ ├── q_a534.js │ ├── q_a535.js │ ├── q_a536.js │ ├── q_a537.js │ ├── q_a538.js │ ├── q_a539.js │ ├── q_a540.js │ ├── q_a541.js │ ├── q_a542.js │ ├── q_a543.js │ ├── q_a544.js │ ├── q_a545.js │ ├── q_a546.js │ ├── q_a547.js │ ├── q_a548.js │ ├── q_a549.js │ ├── q_a550.js │ ├── q_a551.js │ ├── q_a552.js │ ├── q_a553.js │ ├── q_a554.js │ ├── q_a555.js │ ├── q_a556.js │ ├── q_a557.js │ ├── q_a558.js │ ├── q_a559.js │ ├── q_a560.js │ ├── q_a561.js │ ├── q_a562.js │ ├── q_a563.js │ ├── q_a564.js │ ├── q_a565.js │ ├── q_a566.js │ ├── q_a567.js │ ├── q_a568.js │ ├── q_a569.js │ ├── q_a570.js │ ├── q_a571.js │ ├── q_a572.js │ ├── q_a573.js │ ├── q_a574.js │ ├── q_a575.js │ ├── q_a576.js │ ├── q_a577.js │ ├── q_a578.js │ ├── q_a579.js │ ├── q_a580.js │ ├── q_a581.js │ ├── q_a582.js │ ├── q_a583.js │ ├── q_a584.js │ ├── q_a585.js │ ├── q_a586.js │ ├── q_a587.js │ ├── q_a588.js │ ├── q_a589.js │ ├── q_a590.js │ ├── q_a591.js │ ├── q_a592.js │ ├── q_a593.js │ ├── q_a594.js │ ├── q_a595.js │ ├── q_a596.js │ ├── q_a597.js │ ├── q_a598.js │ ├── q_a599.js │ └── q_a600.js └── g_Seventh_100 │ ├── q_a601.js │ ├── q_a602.js │ ├── q_a603.js │ ├── q_a604.js │ ├── q_a605.js │ ├── q_a606.js │ ├── q_a607.js │ ├── q_a608.js │ ├── q_a609.js │ ├── q_a610.js │ ├── q_a611.js │ ├── q_a612.js │ ├── q_a613.js │ ├── q_a614.js │ ├── q_a615.js │ ├── q_a616.js │ ├── q_a617.js │ ├── q_a618.js │ ├── q_a619.js │ ├── q_a620.js │ ├── q_a621.js │ ├── q_a622.js │ ├── q_a623.js │ ├── q_a624.js │ ├── q_a625.js │ ├── q_a626.js │ ├── q_a627.js │ ├── q_a628.js │ ├── q_a629.js │ ├── q_a630.js │ ├── q_a631.js │ ├── q_a632.js │ ├── q_a633.js │ ├── q_a634.js │ ├── q_a635.js │ ├── q_a636.js │ ├── q_a637.js │ ├── q_a638.js │ ├── q_a639.js │ ├── q_a640.js │ ├── q_a641.js │ ├── q_a642.js │ ├── q_a643.js │ ├── q_a644.js │ ├── q_a645.js │ ├── q_a646.js │ ├── q_a647.js │ ├── q_a648.js │ ├── q_a649.js │ └── q_a650.js └── Topic-wise ├── Array&String ├── q_1.js ├── q_2.js ├── q_3.js ├── q_4.js ├── q_5.js ├── q_6.js └── q_7.js ├── DP ├── q_1.js ├── q_2.js ├── q_3.js ├── q_4.js └── q_5.js ├── Graph ├── q_1.js └── q_2.js ├── Math ├── q_1.js ├── q_2.js ├── q_3.js ├── q_4.js ├── q_5.js └── q_6.js ├── Queue&Stack ├── q_1.js ├── q_2.js ├── q_3.js ├── q_4.js ├── q_5.js ├── q_6.js ├── q_7.js ├── q_8.js ├── q_9.js ├── q_a10.js ├── q_a11.js ├── q_a12.js ├── q_a13.js ├── q_a14.js ├── q_a15.js ├── q_a16.js └── q_a17.js └── Two_Pointers ├── q_1.js ├── q_2.js ├── q_3.js ├── q_4.js ├── q_5.js ├── q_6.js ├── q_7.js ├── q_8.js ├── q_9.js ├── q_a10.js ├── q_a11.js ├── q_a12.js ├── q_a13.js ├── q_a14.js ├── q_a15.js ├── q_a16.js ├── q_a17.js ├── q_a18.js ├── q_a19.js ├── q_a20.js ├── q_a21.js ├── q_a22.js ├── q_a23.js ├── q_a24.js ├── q_a25.js ├── q_a26.js ├── q_a27.js ├── q_a28.js ├── q_a29.js └── q_a30.js /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | } -------------------------------------------------------------------------------- /Company-wise/Amazon/q_3.js: -------------------------------------------------------------------------------- 1 | /* 2 | Minimum Adjacent Swaps to Reach the Kth Smallest Number 3 | 4 | You are given a string num, representing a large integer, and an integer k. 5 | 6 | We call some integer wonderful if it is a permutation of the digits in num and is greater in value than num. 7 | 8 | There can be many wonderful integers. However, we only care about the smallest-valued ones. 9 | 10 | For example, when num = "5489355142": 11 | The 1st smallest wonderful integer is "5489355214". 12 | The 2nd smallest wonderful integer is "5489355241". 13 | The 3rd smallest wonderful integer is "5489355412". 14 | The 4th smallest wonderful integer is "5489355421". 15 | Return the minimum number of adjacent digit swaps that needs to be applied to num to reach the kth smallest wonderful integer. 16 | 17 | The tests are generated in such a way that kth smallest wonderful integer exists. 18 | */ 19 | -------------------------------------------------------------------------------- /Company-wise/Amazon/q_4.js: -------------------------------------------------------------------------------- 1 | /* 2 | Palindrome Permutation II 3 | 4 | Given a string s, return all the palindromic permutations (without duplicates) of it. 5 | 6 | You may return the answer in any order. If s has no palindromic permutation, return an empty list. 7 | */ 8 | -------------------------------------------------------------------------------- /Company-wise/Amazon/q_5.js: -------------------------------------------------------------------------------- 1 | /* 2 | Number of Dice Rolls With Target Sum 3 | 4 | You have d dice and each die has f faces numbered 1, 2, ..., f. 5 | 6 | Return the number of possible ways (out of fd total ways) modulo 109 + 7 to roll the dice so the sum of the face-up numbers equals target. 7 | */ 8 | -------------------------------------------------------------------------------- /Company-wise/Amazon/q_6.js: -------------------------------------------------------------------------------- 1 | /* 2 | 01 Matrix 3 | 4 | Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell. 5 | 6 | The distance between two adjacent cells is 1. 7 | */ 8 | -------------------------------------------------------------------------------- /Company-wise/Amazon/q_7.js: -------------------------------------------------------------------------------- 1 | /* 2 | Number of Dice Rolls With Target Sum 3 | 4 | You have d dice and each die has f faces numbered 1, 2, ..., f. 5 | 6 | Return the number of possible ways (out of fd total ways) modulo 109 + 7 to roll 7 | 8 | the dice so the sum of the face-up numbers equals target. 9 | */ 10 | 11 | var numRollsToTarget = function (d, f, target) { 12 | return dfs(d, f, target); 13 | // T.C: O(d*f) 14 | // S.C: O(d*f) 15 | }; 16 | 17 | // d: dices remaining 18 | // f: possible outcome of a roll 19 | function dfs(d, f, target, memo = new Map()) { 20 | if (d === 0 && target === 0) { 21 | return 1; 22 | } 23 | if (d === 0 || target <= 0) { 24 | return 0; 25 | } 26 | if (memo.has(`${d}-${target}`)) { 27 | return memo.get(`${d}-${target}`); 28 | } 29 | let count = 0, 30 | M = Math.pow(10, 9) + 7; 31 | for (let i = 1; i <= f; i++) { 32 | count = (count + dfs(d - 1, f, target - i, memo)) % M; 33 | } 34 | memo.set(`${d}-${target}`, count); 35 | return count; 36 | } 37 | -------------------------------------------------------------------------------- /Company-wise/Amazon/q_a11.js: -------------------------------------------------------------------------------- 1 | /* 2 | Longest Substring Without Repeating Characters 3 | 4 | Given a string s, find the length of the longest substring without repeating characters. 5 | */ 6 | 7 | function longestNonRepeatingSubstr(s) { 8 | let start = 0, 9 | set = new Set(); 10 | let max = 0; 11 | for (let end = 0; end < s.length; end++) { 12 | // validate current substring 13 | while (start < end && set.has(s[end])) { 14 | set.delete(s[start++]); 15 | } 16 | set.add(s[end]); 17 | max = Math.max(max, end - start + 1); 18 | } 19 | return max; 20 | // T.C: O(N) 21 | // S.C: O(N) 22 | } 23 | -------------------------------------------------------------------------------- /Company-wise/Amazon/q_a18.js: -------------------------------------------------------------------------------- 1 | var reorderLogFiles = function(logs) { 2 | let letterLogs = [], digitLogs = []; 3 | for (let i = 0; i < logs.length; i++) { 4 | let idx = logs[i].indexOf(" "); 5 | if (logs[i][idx+1] >= "0" && logs[i][idx+1] <= "9") { 6 | digitLogs.push(logs[i]); 7 | } else { 8 | let id = logs[i].substring(0, idx); 9 | let content = logs[i].substring(idx + 1); 10 | letterLogs.push([id, content]); 11 | } 12 | } 13 | letterLogs.sort((a,b) => { 14 | if (a[1] === b[1]) return a[0].localeCompare(b[0]); 15 | else return a[1].localeCompare(b[1]); 16 | }); 17 | letterLogs = letterLogs.map(log => log.join(" ")); 18 | return [...letterLogs, ...digitLogs]; 19 | // T.C: O(Nlog(N) + KN) , N = # of logs, K = maximum length of a log 20 | // S.C: O(N) 21 | }; -------------------------------------------------------------------------------- /Company-wise/Facebook/q_2.js: -------------------------------------------------------------------------------- 1 | /* 2 | Combination Sum 3 | 4 | Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. 5 | 6 | You may return the combinations in any order. 7 | 8 | The same number may be chosen from candidates an unlimited number of times. 9 | 10 | Two combinations are unique if the frequency of at least one of the chosen numbers is different. 11 | 12 | It is guaranteed that the number of unique combinations that sum up to target is less than 150 combinations for the given input. 13 | */ 14 | -------------------------------------------------------------------------------- /Company-wise/Facebook/q_5.js: -------------------------------------------------------------------------------- 1 | /* 2 | Minimizing Permutations 3 | 4 | In this problem, you are given an integer N, and a permutation, P of the integers from 1 to N, denoted as (a_1, a_2, ..., a_N). 5 | You want to rearrange the elements of the permutation into increasing order, repeatedly making the following operation: 6 | Select a sub-portion of the permutation, (a_i, ..., a_j), and reverse its order. 7 | Your goal is to compute the minimum number of such operations required to return the permutation to increasing order. 8 | 9 | Signature 10 | int minOperations(int[] arr) 11 | 12 | Input 13 | Array arr is a permutation of all integers from 1 to N, N is between 1 and 8 14 | 15 | Output 16 | An integer denoting the minimum number of operations required to arrange the permutation in increasing order 17 | 18 | Example 19 | If N = 3, and P = (3, 1, 2), we can do the following operations: 20 | Select (1, 2) and reverse it: P = (3, 2, 1). 21 | Select (3, 2, 1) and reverse it: P = (1, 2, 3). 22 | output = 2 23 | */ 24 | -------------------------------------------------------------------------------- /Company-wise/Facebook/q_6.js: -------------------------------------------------------------------------------- 1 | /* 2 | We have 2 arrays in sorted order, no duplicates. 3 | 4 | We need find the max continuous length AP [arithmetic prog] in the first array 5 | by adding 0 or more elements from the second array. 6 | 7 | example, 8 | 9 | A=[4,8,13] 10 | B=[0,9,12] 11 | 12 | ANSWER = [0,4,8,12], 4 13 | 14 | Constraints 15 | n<=1000 16 | Values are <=10000 17 | */ 18 | -------------------------------------------------------------------------------- /Company-wise/Facebook/q_7.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array and a number k , then check for every number if it is duplicated in previous k or next k numbers 3 | */ 4 | -------------------------------------------------------------------------------- /Company-wise/Facebook/q_8.js: -------------------------------------------------------------------------------- 1 | /* 2 | Invert Binary Tree 3 | 4 | Given the root of a binary tree, invert the tree, and return its root. 5 | */ 6 | 7 | /* 8 | In order to invert a tree, we should swap the left node and the right node for every subtree of the tree. 9 | Hence, we will traverse the given tree in postorder and swap the left subtree and the right subtree recursively. 10 | */ 11 | var invertTree = function (root) { 12 | dfs(root); 13 | return root; 14 | function dfs(root) { 15 | if (!root) { 16 | return null; 17 | } 18 | let left = dfs(root.left); 19 | let right = dfs(root.right); 20 | root.left = right; 21 | root.right = left; 22 | return root; 23 | } 24 | // T.C: O(N) 25 | // S.C: O(H) 26 | }; 27 | -------------------------------------------------------------------------------- /Company-wise/Facebook/q_a14.js: -------------------------------------------------------------------------------- 1 | /* 2 | Tree Diameter 3 | 4 | Given an undirected tree, return its diameter: the number of edges in a longest path in that tree. 5 | 6 | The tree is given as an array of edges where edges[i] = [u, v] is a bidirectional edge between nodes u and v. 7 | 8 | Each node has labels in the set {0, 1, ..., edges.length}. 9 | */ 10 | -------------------------------------------------------------------------------- /Company-wise/Facebook/q_a18.js: -------------------------------------------------------------------------------- 1 | /* 2 | Check if There is a Valid Path in a Grid 3 | 4 | Given a m x n grid. Each cell of the grid represents a street. The street of grid[i][j] can be: 5 | 1 which means a street connecting the left cell and the right cell. 6 | 2 which means a street connecting the upper cell and the lower cell. 7 | 3 which means a street connecting the left cell and the lower cell. 8 | 4 which means a street connecting the right cell and the lower cell. 9 | 5 which means a street connecting the left cell and the upper cell. 10 | 6 which means a street connecting the right cell and the upper cell. 11 | 12 | You will initially start at the street of the upper-left cell (0,0). 13 | 14 | A valid path in the grid is a path which starts from the upper left cell (0,0) and ends at the bottom-right cell (m - 1, n - 1). 15 | 16 | The path should only follow the streets. 17 | 18 | Notice that you are not allowed to change any street. 19 | 20 | Return true if there is a valid path in the grid or false otherwise. 21 | */ 22 | -------------------------------------------------------------------------------- /Company-wise/Facebook/q_a20.js: -------------------------------------------------------------------------------- 1 | /* 2 | Implement Buffer with the following api. 3 | 4 | class Buffer { 5 | 6 | public Buffer(int capacity) { 7 | } 8 | 9 | 10 | // Transfers the content of the given source char array into this buffer. 11 | // Returns the the number of chars that were written into the buffer. 12 | 13 | public int write(char[] src) { 14 | } 15 | 16 | public char[] read(int n) { 17 | } 18 | } 19 | 20 | Example: 21 | 22 | Buffer buf = new Buffer(5); // [. . . . .] 23 | buf.write([abc]); // => 3 [abc . .] 24 | buf.write([def]); // => 2 because the buffer is full, you can only write two chars [abcde] 25 | buf.read(3); // => [abc] [. . . de] 26 | buf.write([xyzabc]); // => 3 [xyzde] 27 | buf.read(8); // returns [dexyz] becuase 'de' was written first [. . . . .] 28 | */ 29 | -------------------------------------------------------------------------------- /Company-wise/Facebook/q_a21.js: -------------------------------------------------------------------------------- 1 | /* 2 | Interval List Intersections 3 | 4 | You are given two lists of closed intervals, firstList and secondList, where firstList[i] = [starti, endi] and secondList[j] = [startj, endj]. 5 | 6 | Each list of intervals is pairwise disjoint and in sorted order. 7 | 8 | Return the intersection of these two interval lists. 9 | 10 | A closed interval [a, b] (with a < b) denotes the set of real numbers x with a <= x <= b. 11 | 12 | The intersection of two closed intervals is a set of real numbers that are either empty or represented as a closed interval. 13 | 14 | For example, the intersection of [1, 3] and [2, 4] is [2, 3]. 15 | */ 16 | -------------------------------------------------------------------------------- /Company-wise/Facebook/q_a25.js: -------------------------------------------------------------------------------- 1 | /* 2 | Convert Binary Search Tree to Sorted Doubly Linked List 3 | 4 | Convert a Binary Search Tree to a sorted Circular Doubly-Linked List in place. 5 | 6 | You can think of the left and right pointers as synonymous to the predecessor and successor pointers in a doubly-linked list. For a circular doubly linked list, the predecessor of the first element is the last element, and the successor of the last element is the first element. 7 | 8 | We want to do the transformation in place. After the transformation, the left pointer of the tree node should point to its predecessor, and the right pointer should point to its successor. You should return the pointer to the smallest element of the linked list. 9 | */ 10 | -------------------------------------------------------------------------------- /Company-wise/Facebook/q_a36.js: -------------------------------------------------------------------------------- 1 | /* 2 | Maximum Sum BST in Binary Tree 3 | 4 | Given a binary tree root, the task is to return the maximum sum of all keys of any sub-tree which is also a Binary Search Tree (BST). 5 | 6 | Assume a BST is defined as follows: 7 | 8 | The left subtree of a node contains only nodes with keys less than the node's key. 9 | The right subtree of a node contains only nodes with keys greater than the node's key. 10 | Both the left and right subtrees must also be binary search trees. 11 | */ 12 | -------------------------------------------------------------------------------- /Company-wise/Facebook/q_a37.js: -------------------------------------------------------------------------------- 1 | /* 2 | Minimum Cost For Tickets 3 | 4 | You have planned some train traveling one year in advance. 5 | 6 | The days of the year in which you will travel are given as an integer array days. Each day is an integer from 1 to 365. 7 | 8 | Train tickets are sold in three different ways: 9 | - a 1-day pass is sold for costs[0] dollars, 10 | - a 7-day pass is sold for costs[1] dollars, and 11 | - a 30-day pass is sold for costs[2] dollars. 12 | 13 | The passes allow that many days of consecutive travel. 14 | - For example, if we get a 7-day pass on day 2, then we can travel for 7 days: 2, 3, 4, 5, 6, 7, and 8. 15 | 16 | Return the minimum number of dollars you need to travel every day in the given list of days. 17 | */ 18 | -------------------------------------------------------------------------------- /Company-wise/Facebook/q_a39.js: -------------------------------------------------------------------------------- 1 | /* 2 | Restore IP Addresses 3 | 4 | Given a string s containing only digits, return all possible valid IP addresses that can be obtained from s. You can return them in any order. 5 | 6 | A valid IP address consists of exactly four integers, each integer is between 0 and 255, separated by single dots and cannot have leading zeros. 7 | 8 | For example, "0.1.2.201" and "192.168.1.1" are valid IP addresses and "0.011.255.245", "192.168.1.312" and "192.168@1.1" are invalid IP addresses. 9 | */ 10 | -------------------------------------------------------------------------------- /Company-wise/Facebook/q_a45.js: -------------------------------------------------------------------------------- 1 | /* 2 | Expression Add Operators 3 | 4 | Given a string num that contains only digits and an integer target, 5 | 6 | return all possibilities to add the binary operators '+', '-', or '*' between the digits of num so that the resultant expression evaluates to the target value. 7 | */ 8 | -------------------------------------------------------------------------------- /Company-wise/Facebook/q_a48.js: -------------------------------------------------------------------------------- 1 | /* 2 | Maximum Size Subarray Sum Equals k 3 | 4 | Given an integer array nums and an integer k, return the maximum length of a subarray that sums to k. 5 | 6 | If there isn't one, return 0 instead. 7 | */ 8 | 9 | var maxSubArrayLen = function (nums, k) { 10 | if (nums === null || nums.length === 0) { 11 | return 0; 12 | } 13 | let m = new Map(), 14 | prefixSum = 0, 15 | max = 0; 16 | m.set(prefixSum, -1); 17 | for (let i = 0; i < nums.length; i++) { 18 | prefixSum += nums[i]; 19 | let diff = prefixSum - k; 20 | if (m.has(diff)) { 21 | max = Math.max(max, i - m.get(diff)); 22 | } 23 | // we want the maximum length of subarray so smaller index should be kept 24 | if (!m.has(prefixSum)) { 25 | m.set(prefixSum, i); 26 | } 27 | } 28 | return max; 29 | // T.C: O(N) 30 | // S.C: O(N) 31 | }; 32 | -------------------------------------------------------------------------------- /Company-wise/Facebook/q_a49.js: -------------------------------------------------------------------------------- 1 | /* 2 | Nested List Weight Sum 3 | 4 | You are given a nested list of integers nestedList. 5 | 6 | Each element is either an integer or a list whose elements may also be integers or other lists. 7 | 8 | The depth of an integer is the number of lists that it is inside of. 9 | 10 | For example, the nested list [1,[2,2],[[3],2],1] has each integer's value set to its depth. 11 | 12 | Return the sum of each integer in nestedList multiplied by its depth. 13 | */ 14 | 15 | var depthSum = function (nestedList) { 16 | return listSum(nestedList); 17 | // T.C: O(N), N = # of all elements 18 | // S.C: O(maxDepth) 19 | }; 20 | 21 | function listSum(list, depth = 1) { 22 | let sum = 0; 23 | for (let i = 0; i < list.length; i++) { 24 | if (list[i].isInteger()) { 25 | sum += depth * list[i].getInteger(); 26 | } else { 27 | sum += listSum(list[i].getList(), depth + 1); 28 | } 29 | } 30 | return sum; 31 | } 32 | -------------------------------------------------------------------------------- /Company-wise/Facebook/q_a51.js: -------------------------------------------------------------------------------- 1 | /* 2 | Intersection of Three Sorted Arrays 3 | 4 | Given three integer arrays arr1, arr2 and arr3 sorted in strictly increasing order, 5 | 6 | return a sorted array of only the integers that appeared in all three arrays. 7 | */ 8 | 9 | var arraysIntersection = function (arr1, arr2, arr3) { 10 | let idx1 = 0, 11 | idx2 = 0, 12 | idx3 = 0; 13 | let res = []; 14 | while (idx1 < arr1.length && idx2 < arr2.length && idx3 < arr3.length) { 15 | if (arr1[idx1] === arr2[idx2] && arr2[idx2] === arr3[idx3]) { 16 | res.push(arr1[idx1]); 17 | idx1++, idx2++, idx3++; 18 | } else if (arr1[idx1] < arr2[idx2]) { 19 | idx1++; 20 | } else if (arr2[idx2] < arr3[idx3]) { 21 | idx2++; 22 | } else { 23 | idx3++; 24 | } 25 | } 26 | return res; 27 | // T.C: O(min(M1, M2, M3)) 28 | // S.C: O(1), assuming that we don't count the output array as extra space 29 | }; 30 | -------------------------------------------------------------------------------- /Company-wise/Facebook/q_a54.js: -------------------------------------------------------------------------------- 1 | /* 2 | Closest Binary Search Tree Value 3 | 4 | Given the root of a binary search tree and a target value, return the value in the BST that is closest to the target. 5 | */ 6 | 7 | var closestValue = function (root, target) { 8 | if (root === null || target === null) { 9 | return null; 10 | } 11 | let minDiff = null, 12 | resVal = root.val; 13 | dfs(root); 14 | return resVal; 15 | function dfs(root) { 16 | if (!root) { 17 | return; 18 | } 19 | let diff = Math.abs(root.val - target); 20 | if (minDiff === null || diff < minDiff) { 21 | minDiff = diff; 22 | resVal = root.val; 23 | } 24 | if (root.val > target) { 25 | dfs(root.left); 26 | } else { 27 | dfs(root.right); 28 | } 29 | } 30 | // T.C: O(log(N)) 31 | // S.C: O(H) 32 | }; 33 | -------------------------------------------------------------------------------- /Company-wise/Facebook/q_a62.js: -------------------------------------------------------------------------------- 1 | /* 2 | Clone Graph 3 | 4 | Given a reference of a node in a connected undirected graph. 5 | 6 | Return a deep copy (clone) of the graph. 7 | 8 | Each node in the graph contains a value (int) and a list (List[Node]) of its neighbors. 9 | 10 | class Node { 11 | public int val; 12 | public List neighbors; 13 | } 14 | */ 15 | 16 | var cloneGraph = function (node, cloneMap = new Map()) { 17 | if (!node) { 18 | return null; 19 | } 20 | if (cloneMap.has(node)) { 21 | return cloneMap.get(node); 22 | } 23 | let cloneNode = new Node(node.val, []); 24 | cloneMap.set(node, cloneNode); 25 | for (let neighbor of node.neighbors) { 26 | cloneNode.neighbors.push(cloneGraph(neighbor, cloneMap)); 27 | } 28 | return cloneNode; 29 | // T.C: O(V+E), we visit every vertex and every edge 30 | // S.C: O(V), cloneMap has a space complexity of O(V) 31 | }; 32 | -------------------------------------------------------------------------------- /Company-wise/Facebook/q_a65.js: -------------------------------------------------------------------------------- 1 | /* 2 | Intersection of Two Arrays 3 | 4 | Given two integer arrays nums1 and nums2, return an array of their intersection. 5 | 6 | Each element in the result must be unique and you may return the result in any order. 7 | */ 8 | 9 | var intersection = function (nums1, nums2) { 10 | let res = []; 11 | nums1.length < nums2.length 12 | ? iterate(nums2, new Set(nums1), res) 13 | : iterate(nums1, new Set(nums2), res); 14 | return res; 15 | // T.C: O(M + N), M = # of nums1, N = # of nums2 16 | // S.C: O(min(M,N)) 17 | }; 18 | 19 | function iterate(arr, set, res) { 20 | for (let i = 0; i < arr.length; i++) { 21 | if (set.has(arr[i])) { 22 | res.push(arr[i]); 23 | set.delete(arr[i]); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Company-wise/Google/q_3.js: -------------------------------------------------------------------------------- 1 | /* 2 | Q.1 Given an array of integers and a number m. We can create m subarrays using the input array. 3 | 4 | The max sum of each subarrays out of each possibilities are taken. Return the minimum number out of them. 5 | 6 | Array can contain negative values. 7 | 8 | Eg: [1 3 9 2 7 8] 9 | m=2 10 | 11 | Possibilities------Sum---Max 12 | [1] [3 9 3 7 8]--- 1, 30----30 13 | [1 3][ 9 2 7 8]--- 4, 27----27 14 | [1 3 9][ 2 7 8]---13, 17----17 15 | [1 3 9 2][ 7 8]---15, 15----15 16 | [1 3 9 2 7][ 8]---22, 8----22 17 | 18 | answer: 15 (as 15 is min of the all maximum sums) 19 | */ 20 | -------------------------------------------------------------------------------- /Company-wise/Google/q_4.js: -------------------------------------------------------------------------------- 1 | /* 2 | Check if there is a square of 1s in a 2d matrix (that contains 0s and 1s). 3 | 4 | The square has the size of at least sqrt(min(N,M)). 5 | 6 | The input either has one valid square or not (all 0s). 7 | 8 | Signature: bool hasSquare(int[][] matrix) 9 | */ 10 | -------------------------------------------------------------------------------- /Company-wise/Google/q_6.js: -------------------------------------------------------------------------------- 1 | /* 2 | Strobogrammatic Number 3 | 4 | Given a string num which represents an integer, return true if num is a strobogrammatic number. 5 | 6 | A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). 7 | */ 8 | 9 | var isStrobogrammatic = function (num) { 10 | let pairs = { 6: "9", 9: "6", 0: "0", 1: "1", 8: "8" }; 11 | let l = 0, 12 | r = num.length - 1; 13 | while (l <= r) { 14 | if ( 15 | pairs[num[l]] !== undefined && 16 | pairs[num[r]] !== undefined && 17 | pairs[num[l]] === num[r] 18 | ) { 19 | l++, r--; 20 | } else { 21 | return false; 22 | } 23 | } 24 | return true; 25 | // T.C: O(N) 26 | // S.C: O(1) 27 | }; 28 | -------------------------------------------------------------------------------- /Company-wise/Google/q_7.js: -------------------------------------------------------------------------------- 1 | /* 2 | Wiggle Sort 3 | 4 | Given an integer array nums, reorder it such that nums[0] <= nums[1] >= nums[2] <= nums[3].... 5 | 6 | You may assume the input array always has a valid answer. 7 | */ 8 | 9 | var wiggleSort = function (nums) { 10 | nums.sort((a, b) => a - b); 11 | for (let i = 1; i < nums.length - 1; i += 2) { 12 | [nums[i], nums[i + 1]] = [nums[i + 1], nums[i]]; 13 | } 14 | // T.C: O(nlog(n)) 15 | // S.C: O(1) 16 | }; 17 | 18 | var wiggleSort = function (nums) { 19 | for (let i = 0; i < nums.length - 1; i++) { 20 | if ( 21 | (i % 2 === 0 && nums[i] > nums[i + 1]) || 22 | (i % 2 === 1 && nums[i] < nums[i + 1]) 23 | ) { 24 | swap(nums, i, i + 1); 25 | } 26 | } 27 | // T.C: O(N) 28 | // S.C: O(1) 29 | }; 30 | 31 | function swap(arr, i, j) { 32 | [arr[i], arr[j]] = [arr[j], arr[i]]; 33 | } 34 | -------------------------------------------------------------------------------- /Company-wise/Microsoft/q_2.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string, what is the minimum number of adjacent swaps required to convert a string into a palindrome. 3 | 4 | If not possible, return -1. 5 | */ 6 | 7 | 8 | -------------------------------------------------------------------------------- /Company-wise/Microsoft/q_3.js: -------------------------------------------------------------------------------- 1 | /* 2 | Alexa is given n piles of equal or unequal heights. In one step, Alexa can remove any number of boxes from the pile which has the maximum height and try to make it equal to the one which is just lower than the maximum height of the stack. Determine the minimum number of steps required to make all of the piles equal in height. 3 | */ 4 | -------------------------------------------------------------------------------- /Company-wise/Microsoft/q_4.js: -------------------------------------------------------------------------------- 1 | /* 2 | Write a function that, given an array A of N integers, returns the lagest integer K > 0 such that both values K and -K exist in array A. If there is no such integer, the function should return 0. 3 | */ 4 | -------------------------------------------------------------------------------- /Company-wise/Microsoft/q_6.js: -------------------------------------------------------------------------------- 1 | /* 2 | Find N Unique Integers Sum up to Zero 3 | 4 | Given an integer n, return any array containing n unique integers such that they add up to 0. 5 | */ 6 | 7 | /* 8 | We can simply add 1 to n-1 and keep track of this array sum and add the negation of that. 9 | */ 10 | var sumZero = function (n) { 11 | let sum = 0, 12 | res = []; 13 | for (let i = 1; i < n; i++) { 14 | res.push(i); 15 | sum += i; 16 | } 17 | res.push(-sum); 18 | return res; 19 | // T.C: O(N) 20 | // S.C: O(N) 21 | }; 22 | 23 | /* 24 | We add pairs of numbers (num, -num) starting from 1 and ending at floor(n/2). 25 | If n is odd, we add 0. 26 | */ 27 | var sumZero = function (n) { 28 | let res = n % 2 === 0 ? [] : [0]; 29 | for (let i = 1; i <= Math.floor(n / 2); i++) { 30 | res.push(i, -i); 31 | } 32 | return res; 33 | // T.C: O(N) 34 | // S.C: O(N) 35 | }; 36 | -------------------------------------------------------------------------------- /Company-wise/Microsoft/q_7.js: -------------------------------------------------------------------------------- 1 | /* 2 | Give you one sorted array, please put them into n buckets, we need to ensure we get n sub array with approximately equal weights. 3 | */ 4 | -------------------------------------------------------------------------------- /Company-wise/Microsoft/q_8.js: -------------------------------------------------------------------------------- 1 | /* 2 | You are given an array of non-negative integers arr and a start index. When you are at an index i, you can move left or right by arr[i]. Your task is to figure out if you can reach value 0. 3 | */ 4 | -------------------------------------------------------------------------------- /Company-wise/Microsoft/q_9.js: -------------------------------------------------------------------------------- 1 | /* 2 | Jump Game III 3 | 4 | Given an array of non-negative integers arr, you are initially positioned at start index of the array. When you are at index i, you can jump to i + arr[i] or i - arr[i], check if you can reach to any index with value 0. 5 | 6 | Notice that you can not jump outside of the array at any time. 7 | */ 8 | 9 | // Recursion, Backtracking 10 | var canReach = function (arr, start) { 11 | if (arr === null || arr.length === 0) { 12 | return false; 13 | } 14 | return dfs(arr, start); 15 | // T.C: O(N) 16 | // S.C: O(N) 17 | }; 18 | 19 | const dfs = (arr, idx) => { 20 | if (arr[idx] === 0) { 21 | return true; 22 | } 23 | if (idx < 0 || idx > arr.length - 1 || arr[idx] < 0) { 24 | return false; 25 | } 26 | let jump = arr[idx]; 27 | arr[idx] = -1; // marking this index as visited 28 | return dfs(arr, idx - jump) || dfs(arr, idx + jump); 29 | }; 30 | -------------------------------------------------------------------------------- /Company-wise/Microsoft/q_a11.js: -------------------------------------------------------------------------------- 1 | /* 2 | Meeting Rooms II 3 | 4 | Given an array of meeting time intervals intervals where intervals[i] = [starti, endi], return the minimum number of conference rooms required. 5 | */ 6 | 7 | // Chronological Ordering 8 | var minMeetingRooms = function (intervals) { 9 | let starts = intervals.map((interval) => interval[0]); 10 | let ends = intervals.map((interval) => interval[1]); 11 | starts.sort((a, b) => a - b); 12 | ends.sort((a, b) => a - b); 13 | let count = 0, 14 | j = 0; 15 | for (let i = 0; i < starts.length; i++) { 16 | count++; 17 | // a meeting ended and its room became available 18 | if (starts[i] >= ends[j]) { 19 | count--; 20 | j++; 21 | } 22 | } 23 | return count; 24 | // T.C: O(Nlog(N)) 25 | // S.C: O(N) 26 | }; 27 | -------------------------------------------------------------------------------- /Company-wise/Microsoft/q_a12.js: -------------------------------------------------------------------------------- 1 | /* 2 | Count Good Nodes in Binary Tree 3 | 4 | Given a binary tree root, a node X in the tree is named good if in the path from root to X there are no nodes with a value greater than X. 5 | 6 | Return the number of good nodes in the binary tree. 7 | */ 8 | 9 | /* 10 | Use DFS to traverse all nodes. We keep track of maximum node value in path at every node 11 | throughout traversal. Therefore, if current node's value is greater than or equal to the 12 | maximum value, current node is a good node. 13 | */ 14 | var goodNodes = function (root) { 15 | let count = 0; 16 | dfs(root, -Infinity); 17 | return count; 18 | // T.C: O(N) 19 | // S.C: O(H) 20 | function dfs(root, max) { 21 | if (!root) { 22 | return; 23 | } 24 | if (root.val >= max) { 25 | count += 1; 26 | } 27 | max = Math.max(max, root.val); 28 | dfs(root.left, max); 29 | dfs(root.right, max); 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /Company-wise/Microsoft/q_a13.js: -------------------------------------------------------------------------------- 1 | /* 2 | Meeting Rooms 3 | 4 | Given an array of meeting time intervals where intervals[i] = [starti, endi], determine if a person could attend all meetings. 5 | */ 6 | 7 | /* 8 | 1. Sort the array in ascending order of start times 9 | 2. If start time of current meeting is greater than or equal to end time of previous 10 | meeting, we can attend the current meeting. Else, we can't. 11 | */ 12 | var canAttendMeetings = function (intervals) { 13 | if (intervals.length === 0) { 14 | return true; 15 | } 16 | intervals.sort((a, b) => a[0] - b[0]); 17 | for (let i = 1; i < intervals.length; i++) { 18 | if (intervals[i][0] < intervals[i - 1][1]) { 19 | return false; 20 | } 21 | } 22 | return true; 23 | // T.C: O(Nlog(N)) 24 | // S.C: O(1) 25 | }; 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Interview Prep in JavaScript 2 | 3 | First seven folders from `a_First 100` to `g_Seventh 100` consist of a total of 700 random interview questions. You may find the same questions more than once because I often find myself solving the same question over and over.
4 | 5 | The other folders consist of company-specific questions and topic-specific questions.
6 | 7 | Each solution has a detailed explanation. I hope it helps your interview prep :)
8 | -------------------------------------------------------------------------------- /Random_700_Qs/a_First 100/q_4.js: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program to find the n-th ugly number. 3 | Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. 4 | 1 is typically treated as an ugly number. 5 | */ 6 | function nthUglyNumber(n) { 7 | let idx2 = 0, idx3 = 0, idx5 = 0; 8 | let next2, next3, next5; 9 | let next; 10 | let nums = [1] 11 | while (nums.length < n) { 12 | next2 = nums[idx2]*2; 13 | next3 = nums[idx3]*3; 14 | next5 = nums[idx5]*5; 15 | next = Math.min(next2,next3,next5); 16 | nums.push(next); 17 | if (next == next2) idx2++; 18 | if (next == next3) idx3++; 19 | if (next == next5) idx5++; 20 | } 21 | return nums[n-1]; 22 | } 23 | 24 | /* 25 | Test Cases: (5) => 5, (9) => 10 26 | Time Complexity: O(n) 27 | Space Complexity: O(n) 28 | Category: Three Pointer 29 | */ -------------------------------------------------------------------------------- /Random_700_Qs/a_First 100/q_9.js: -------------------------------------------------------------------------------- 1 | /* 2 | Write a function to find the longest common prefix string amongst an array of strings. 3 | 4 | If there is no common prefix, return an empty string "". 5 | */ 6 | function longestCommonPrefix(arr) { 7 | if (!arr.length) return ""; 8 | let prefix = ""; 9 | for (let i = 0; i < arr[0].length; i++) { 10 | for (let j = 0; j < arr.length-1; j++) { 11 | if (arr[j][i] !== arr[j+1][i]) return prefix; 12 | } 13 | prefix += arr[0][i]; 14 | } 15 | return prefix; 16 | } 17 | 18 | /* 19 | Test Cases: ['apple', 'app', 'api'] => 'ap' 20 | 21 | Idea: 22 | 1. We will use two loops. One loops over the first word and the other inside this loop loops over the array and check if every word has 23 | this character at the same position. If they do, append this character to return variable. Else, return the prefix we've collected so far. 24 | 25 | Time Complexity: O(n) 26 | Space Complexity: O(1) 27 | 28 | Category: String, Array 29 | */ -------------------------------------------------------------------------------- /Random_700_Qs/a_First 100/q_a10.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. 3 | 4 | You may assume that each input would have exactly one solution, and you may not use the same element twice. 5 | 6 | You can return the answer in any order. 7 | */ 8 | 9 | function twoSum(nums, target) { 10 | let m = new Map(); 11 | for (let i = 0; i < nums.length; i++) { 12 | let complement = target - nums[i]; 13 | if (m.has(complement)) return [i, m.get(complement)]; 14 | else m.set(nums[i], i); 15 | } 16 | return []; 17 | } 18 | 19 | /* 20 | Test Cases: ([2,4,6,3,1], 8) => [0, 2] 21 | 22 | Idea: 23 | Initialise a Map and loop over the array and check if current number's complement (target - current number) 24 | exists in the map. If it exists, return the complement's index and current index as an array. Else, set current number to the map 25 | with its index as the value. 26 | 27 | Time Complexity: O(n) 28 | Space Complexity: O(n) 29 | */ -------------------------------------------------------------------------------- /Random_700_Qs/a_First 100/q_a15.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given a collection of distinct integers, return all possible permutations. 3 | */ 4 | function permutation(nums) { 5 | let res = [], used = []; 6 | function permute(depth, used, cur) { 7 | if (depth == nums.length) { 8 | res.push(cur.slice()); 9 | return; 10 | } 11 | for (let i = 0; i < nums.length; i++) { 12 | if (!used[i]) { 13 | cur.push(nums[i]); 14 | used[i] = true; 15 | 16 | // move to the next depth 17 | permute(depth+1, used, cur); 18 | 19 | // backtrack to the previous partial state 20 | cur.pop(); 21 | used[i] = false; 22 | } 23 | } 24 | return res; 25 | } 26 | return permute(0, used, []); 27 | } 28 | 29 | /* 30 | Time Complexity: O(n!) 31 | Space Complexity: O(n!) 32 | 33 | Category: Backtracking, DFS 34 | */ -------------------------------------------------------------------------------- /Random_700_Qs/a_First 100/q_a23.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string s consists of upper/lower-case alphabets and empty space characters ' ', 3 | return the length of last word (last word means the last appearing word if we loop from left to right) in the string. 4 | 5 | If the last word does not exist, return 0. 6 | 7 | Note: A word is defined as a maximal substring consisting of non-space characters only. 8 | */ 9 | 10 | function lengthOfLastWord(s) { 11 | let words = s.split(" "); 12 | for (let i = words.length-1; i >= 0; i--) { 13 | if (words[i] !== '') return words[i].length; 14 | } 15 | return 0; 16 | } 17 | 18 | /* 19 | Idea: I will split the string with a space between, e.g. String.split(" "), so the resulting array will contains 20 | words and possibly some empty spaces, e.g. ''. So, I will loop over the array from the end and return the length of 21 | the element if it is not equal to empty space. 22 | */ -------------------------------------------------------------------------------- /Random_700_Qs/a_First 100/q_a24.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string, find the first non-repeating character in it and return its index. 3 | 4 | If it doesn't exist, return -1. 5 | */ 6 | 7 | function findNonRepeatingChar(s) { 8 | let m = new Map(); 9 | for (let i = 0; i < s.length; i++) { 10 | (m.has(s[i])) ? m.set(s[i], -1) : m.set(s[i], i); 11 | } 12 | for (let [num, idx] of m) { 13 | if (idx !== -1) return idx; 14 | } 15 | return -1; // Every character repeats in the string. 16 | } 17 | 18 | /* 19 | Test Cases: "ahbabdeb" => 1 20 | 21 | Idea: 22 | 1. Initialise an empty map. 23 | 2. Start looping over every character of given string. If a character does not exist in the map, assign the character 24 | to the map with its index as its value. Else, change the value of the character in the map to -1 because this character 25 | is a repeating character. 26 | 3. Loop over the map and return the first index that is not -1. 27 | 28 | Time Complexity: O(n) 29 | Space Complexity: O(n) 30 | */ -------------------------------------------------------------------------------- /Random_700_Qs/a_First 100/q_a27.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string, your task is to count how many palindromic substrings in this string. 3 | 4 | The substrings with different start indexes or end indexes are counted as different substrings even though they consist of same characters. 5 | */ 6 | 7 | 8 | /* 9 | Test Cases: "abbac" => 7 [a,b,b,a,c,bb,abba] 10 | */ 11 | 12 | /* 13 | Idea: 14 | First, I will figure out when a palindrome is possible. 15 | 1. Every letter occurs an even number of times 16 | 2. Every letter except only one occurs an even number of times 17 | 18 | We start by initialising two pointers l and r. 19 | We expand r pointer and every time a palindrome is "possible" we check if it is palindrome 20 | */ -------------------------------------------------------------------------------- /Random_700_Qs/a_First 100/q_a28.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given an unsorted integer array nums, find the smallest missing positive integer. 3 | 4 | Follow up: Could you implement an algorithm that runs in O(n) time and uses constant extra space? 5 | 6 | Questions to ask: 7 | 1. Could the input array contain duplicates? 8 | 2. Could the input array contain negative integers or zero? 9 | 10 | I will assume YES to both questions above. 11 | */ 12 | function firstMissingPositive(nums) { 13 | let i = 1; 14 | while (true) { 15 | if (!nums.includes(i)) return i; 16 | i++; 17 | } 18 | } 19 | /* 20 | Test Cases: [-1, 9,-3,6,1,5] => 2 21 | 22 | Idea: 23 | Naive approach is to loop over every positive integer from 1 until finding one that does not exist in the array. 24 | */ -------------------------------------------------------------------------------- /Random_700_Qs/a_First 100/q_a46.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers A, find the sum of each sliding window of size K. 3 | 4 | Qs to ask: 5 | 1. How do you want the output? 6 | - As an array. 7 | 2. Is K provided as input? 8 | - Yes. 9 | 3. Can the input array contain negative integers? 10 | - Yes. 11 | 4. If K is greater than the input array's length, should I return an empty array? 12 | - Yes. 13 | 5. If the input array is empty, should I return an empty array? 14 | */ 15 | 16 | function slidingWindow(nums, K) { 17 | let start = 0, end = 0; 18 | let sum = 0, sumArr = []; 19 | while (end < nums.length) { 20 | sum += nums[end++]; 21 | if (end-start == K) { 22 | sumArr.push(sum); 23 | sum -= nums[start++]; 24 | } 25 | } 26 | return sumArr; 27 | } 28 | 29 | /* 30 | Test Cases: 31 | ([1,-1,3,5], 2) => [0, 2, 8] 32 | ([], 2) => [] 33 | ([1], 1) => [1] 34 | 35 | Time Complexity: O(n) 36 | Space Complexity: O(1) 37 | */ -------------------------------------------------------------------------------- /Random_700_Qs/a_First 100/q_a48.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers, both -ve and +ve, find a contiguous subarray that sums to 0. 3 | 4 | Qs to ask: 5 | 1. Is an array with one zero also a valid answer? 6 | - Yes. 7 | 2. What to return if the input array is empty? 8 | - Return an empty array. 9 | 3. What to do if there is no answer? 10 | - Return an empty array. 11 | 4. What to do if there are multiple answers? 12 | - Return any one of them. 13 | */ 14 | 15 | function prefixSum(nums) { 16 | let sum = 0; 17 | let m = new Map(); 18 | for (let i = 0; i < nums.length; i++) { 19 | sum += nums[i]; 20 | if (sum == 0) return nums.slice(0, i+1); 21 | if (m.has(sum)) return nums.slice(m.get(sum)+1, i+1); 22 | m.set(sum, i); 23 | } 24 | return []; 25 | } 26 | 27 | /* 28 | Test Cases: 29 | [] => [] 30 | [1,2,3] => [] 31 | [1,2,-2] => [2, -2] 32 | 33 | Time Complexity: O(n) 34 | Space Complexity: O(n) 35 | */ -------------------------------------------------------------------------------- /Random_700_Qs/a_First 100/q_a53.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers that can be both +ve and -ve, find the contiguous subarray with the largest sum. 3 | 4 | Qs: 5 | 1. If the input array is empty, what should I do? 6 | - Return null. 7 | 2. Is the array sorted? 8 | - No. 9 | 3. Can the input array contain duplicates? 10 | - Yes. 11 | 4. Can the answer subarray be a length of 0? 12 | - No. 13 | */ 14 | function maxSubArray(nums) { 15 | if (!nums.length) return null; 16 | let subArrSum = nums[0], maxSum = nums[0]; 17 | for (let i = 1; i < nums.length; i++) { 18 | subArrSum = Math.max(subArrSum+nums[i], nums[i]); 19 | maxSum = Math.max(maxSum, subArrSum); 20 | } 21 | return maxSum; 22 | } 23 | 24 | /* 25 | Test Cases: 26 | [1,-3,2,0,1] => 3 27 | [] => null 28 | [-2,-3] => 0 29 | [1] => 1 30 | 31 | Time Complexity: O(n) 32 | Space Complexity: O(1) 33 | 34 | Category: DP 35 | */ -------------------------------------------------------------------------------- /Random_700_Qs/a_First 100/q_a54.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of positive integers, find a subarray that sums to a given number X. 3 | 4 | 1. What to do if the input array is empty? 5 | - Return an empty array. 6 | 2. How to return the output? 7 | - As an array of start index and end index. 8 | 3. What to do if there are multiple answers? 9 | - Return the first one. 10 | 4. What to do if there is no answer? 11 | - Return an empty array; 12 | */ 13 | 14 | function findSubarray(nums, X) { 15 | let start = 0, end = 0; 16 | let sum = 0; 17 | while (end < nums.length) { 18 | sum += nums[end]; 19 | while (sum > X) { 20 | sum -= nums[start++]; 21 | } 22 | if (sum == X) return [start, end]; 23 | end++; 24 | } 25 | return []; 26 | } 27 | 28 | /* 29 | Test Cases: 30 | [], 2 => [] 31 | [1,-3,5,6], 2 => [1, 2] 32 | [1, 1], 3 => [] 33 | 34 | Time Complexity: O(n) 35 | Space Complexity: O(1) 36 | 37 | Category: Two Pointer 38 | */ -------------------------------------------------------------------------------- /Random_700_Qs/a_First 100/q_a55.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given a Binary Tree that can contain duplicate elements, find the first occurrence of a number N. 3 | 4 | Qs: 5 | 1. By first occurrence, you mean a node that would come first in an inorder traversal? 6 | - Yes. 7 | */ 8 | 9 | function inorderTraversal(root, N) { 10 | let res = null; 11 | function dfs(root) { 12 | if (root == null || res !== null) return; 13 | dfs(root.left) 14 | if (res == null && root.val == N) res = root; 15 | dfs(root.right) 16 | } 17 | dfs(root); 18 | return res; 19 | } 20 | 21 | /* 22 | Time Complexity: O(n) 23 | Space Complexity: O(1) 24 | */ -------------------------------------------------------------------------------- /Random_700_Qs/a_First 100/q_a66.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set). 3 | 4 | Note: The solution set must not contain duplicate subsets. 5 | */ 6 | 7 | var subsetsWithDup = function(nums) { 8 | let res = []; 9 | nums.sort((a,b) => a-b); 10 | function combine(depth, start, cur) { 11 | res.push(cur.slice()); 12 | 13 | for (let i = start; i < nums.length; i++) { 14 | if (i > start && nums[i] == nums[i-1]) continue; 15 | // for duplicate numbers, we want to recurse only on the first one because we do not want duplicate subsets 16 | cur.push(nums[i]); 17 | 18 | combine(depth+1, i+1, cur); 19 | 20 | cur.pop(); 21 | } 22 | } 23 | combine(0, 0, []); 24 | return res; 25 | }; -------------------------------------------------------------------------------- /Random_700_Qs/a_First 100/q_a75.js: -------------------------------------------------------------------------------- 1 | /* 2 | Count the number of prime numbers less than a non-negative number, n. 3 | */ 4 | 5 | var countPrimes = function (n) { 6 | let primes = []; 7 | for (let i = 0; i < n; i++) primes[i] = true; 8 | primes[0] = false, primes[1] = false; 9 | for (let i = 2; i < Math.sqrt(n); i++) { 10 | if (primes[i] == true) { 11 | for (let j = i**2; j < n; j += i) { // optimisation: we start at i**2 instead of i*2 12 | primes[j] = false; 13 | } 14 | } 15 | } 16 | return primes.map((bool, idx) => bool ? idx : 0) 17 | .filter(val => val > 0).length; 18 | }; 19 | 20 | /* 21 | Sieve of Eratosthenes is an algorithm to find all prime numbers up to any given limit. 22 | Here, we find all prime numbers less than n and return the count of them. 23 | */ 24 | // Time Complexity: O(nlog(n)) 25 | // Space Complexity: O(n) 26 | 27 | -------------------------------------------------------------------------------- /Random_700_Qs/a_First 100/q_a78.js: -------------------------------------------------------------------------------- 1 | /* 2 | Reverse a linked list from position m to n. Do it in one-pass. 3 | 4 | Note: 1 ≤ m ≤ n ≤ length of list. 5 | */ 6 | 7 | var reverseBetween = function(head, m, n) { 8 | let start = head, cur = head; 9 | let curPos = 1; 10 | while (curPos < m) { 11 | start = cur; 12 | cur = cur.next; 13 | curPos++; 14 | } 15 | 16 | let prev = null, tail = cur; 17 | while (curPos <= n) { 18 | let next = cur.next; 19 | cur.next = prev; 20 | prev = cur; 21 | cur = next; 22 | curPos++; 23 | } 24 | start.next = prev; 25 | tail.next = cur; 26 | 27 | return m == 1 ? prev : head; 28 | // Time Complexity: O(n) 29 | // Space Complexity: O(n) 30 | }; 31 | -------------------------------------------------------------------------------- /Random_700_Qs/a_First 100/q_a81.js: -------------------------------------------------------------------------------- 1 | /* 2 | Graph Traversal: Breadth-First-Search (BFS) Technique 3 | 4 | Input is given as adjacency list. 5 | */ 6 | 7 | function bfsWithAdjList(list) { 8 | let visited = new Array(list.length).fill(false); 9 | let queue = [0]; 10 | let res = []; 11 | while (queue.length > 0) { 12 | let node = queue.shift(); 13 | res.push(node); 14 | visited[node] = true; 15 | let neighbours = list[node]; 16 | for (let neighbour of neighbours) { 17 | if (visited[neighbour] === false) { 18 | queue.push(neighbour); 19 | } 20 | } 21 | } 22 | return res; 23 | } 24 | 25 | const adjList = [ 26 | [1, 3], 27 | [0], 28 | [3, 8], 29 | [0, 2, 4, 5], 30 | [3, 6], 31 | [3], 32 | [4, 7], 33 | [6], 34 | [2], 35 | ]; 36 | 37 | console.log(bfsWithAdjList(adjList)); // => [0,1,3,2,4,5,8,6,7] 38 | -------------------------------------------------------------------------------- /Random_700_Qs/a_First 100/q_a83.js: -------------------------------------------------------------------------------- 1 | /* 2 | Graph Traversal: Depth-First-Search (DFS) Technique 3 | 4 | Input is given as adjacency list. 5 | */ 6 | 7 | function dfsWithAdjList(list) { 8 | let visited = new Array(list.length).fill(false); 9 | let res = []; 10 | function dfs(visited, cur) { 11 | res.push(cur); 12 | visited[cur] = true; 13 | let neighbours = list[cur]; 14 | for (let neighbour of neighbours) { 15 | if (visited[neighbour] === false) { 16 | dfs(visited, neighbour); 17 | } 18 | } 19 | } 20 | dfs(visited, 0); 21 | return res; 22 | } 23 | 24 | const adjList = [ 25 | [1, 3], 26 | [0], 27 | [3, 8], 28 | [0, 2, 4, 5], 29 | [3, 6], 30 | [3], 31 | [4, 7], 32 | [6], 33 | [2], 34 | ]; 35 | 36 | console.log(dfsWithAdjList(adjList)); // => [0, 1, 3, 2, 8, 4, 6, 7, 5] 37 | -------------------------------------------------------------------------------- /Random_700_Qs/a_First 100/q_a84.js: -------------------------------------------------------------------------------- 1 | /* 2 | Graph Traversal: Depth-First-Search (BFS) Technique 3 | 4 | Input is given as adjacency matrix. 5 | */ 6 | 7 | function dfsWithAdjMatrix(matrix) { 8 | let visited = new Array(matrix.length).fill(false); 9 | let res = []; 10 | function dfs(visited, cur) { 11 | res.push(cur); 12 | visited[cur] = true; 13 | for (let i = 0; i < matrix[cur].length; i++) { 14 | if (!visited[i] && matrix[cur][i] == 1) { 15 | dfs(visited, i); 16 | } 17 | } 18 | } 19 | dfs(visited, 0); 20 | return res; 21 | } 22 | 23 | const adjMatrix = [ 24 | [0, 1, 0, 1, 0, 0, 0, 0, 0], 25 | [1, 0, 0, 0, 0, 0, 0, 0, 0], 26 | [0, 0, 0, 1, 0, 0, 0, 0, 1], 27 | [1, 0, 1, 0, 1, 1, 0, 0, 0], 28 | [0, 0, 0, 1, 0, 0, 1, 0, 0], 29 | [0, 0, 0, 1, 0, 0, 0, 0, 0], 30 | [0, 0, 0, 0, 1, 0, 0, 1, 0], 31 | [0, 0, 0, 0, 0, 0, 1, 0, 0], 32 | [0, 0, 1, 0, 0, 0, 0, 0, 0], 33 | ]; 34 | 35 | console.log(dfsWithAdjMatrix(adjMatrix)); 36 | -------------------------------------------------------------------------------- /Random_700_Qs/a_First 100/q_a96.js: -------------------------------------------------------------------------------- 1 | /* 2 | Create a class Comparator that has compare(a,b) method which can compare values of integer, string and array. 3 | */ 4 | 5 | class Comparator { 6 | constructor() {} 7 | compare(a, b) { 8 | if (typeof a == "number" && typeof b == "number") return this.a === this.b; 9 | if (typeof a == "string" && typeof b == "string") return this.a === this.b; 10 | if (Array.isArray(a) && Array.isArray(b)) { 11 | if (a.length !== b.length) return false; 12 | for (let i = 0; i < a.length; i++) { 13 | if (a[i] !== b[i]) return false; 14 | } 15 | return true; 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /Random_700_Qs/a_First 100/q_a97.js: -------------------------------------------------------------------------------- 1 | /* 2 | Monica has cooked n dishes and collected the data on the level of satisfaction for all the dishes from a guest. 3 | 4 | The guest returns an array, where the ith element of the array is the liking level of the ith dish. 5 | 6 | Also, the time taken to cook the ith dish is i. 7 | 8 | Like-to-time coefficient of a dish is calculated by multiplying the time taken to cook food with its liking level, i.e., input 2[i]. 9 | 10 | Totally like-to-time coefficient is calculated by summing up all individual coefficients of dishes. 11 | 12 | You want the total like-to-time coefficient to be maximum. 13 | 14 | You can also remove some dishes, in which case, a new coefficient is calculated using the left dishes. 15 | 16 | Find the maximum sum of all possible like-to-time coefficients.​ 17 | */ -------------------------------------------------------------------------------- /Random_700_Qs/a_First 100/q_a98.js: -------------------------------------------------------------------------------- 1 | /* 2 | A chef has collected data on the satisfaction level of his n dishes. Chef can cook any dish in 1 unit of time. 3 | 4 | Like-time coefficient of a dish is defined as the time taken to cook that dish including 5 | previous dishes multiplied by its satisfaction level i.e. time[i]*satisfaction[i] 6 | 7 | Return the maximum sum of Like-time coefficient that the chef can obtain after dishes preparation. 8 | 9 | Dishes can be prepared in any order and the chef can discard some dishes to get this maximum value. 10 | */ -------------------------------------------------------------------------------- /Random_700_Qs/b_Second 100/q_a108.js: -------------------------------------------------------------------------------- 1 | /* 2 | You are given the root node of a binary search tree (BST) and a value to insert into the tree. Return the root node of the BST after the insertion. 3 | 4 | It is guaranteed that the new value does not exist in the original BST. 5 | 6 | Notice that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them. 7 | */ 8 | 9 | // Recursive DFS Solution 10 | var insertIntoBST = function(root, val) { 11 | if (!root) return new TreeNode(val); 12 | if (root.val > val) { 13 | root.left = insertIntoBST(root.left, val); 14 | } else { 15 | root.right = insertIntoBST(root.right, val); 16 | } 17 | return root; 18 | // Time Complexity: O(H) 19 | // Space Complexity: O(H) due to call stack; O(N) in the worst case of the skewed tree 20 | // and O(log(N)) in the average case of the balanced tree 21 | } -------------------------------------------------------------------------------- /Random_700_Qs/b_Second 100/q_a120.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer number n, return the difference between the product of its digits and the sum of its digits. 3 | */ 4 | 5 | var subtractProductAndSum = function(n) { 6 | let product = 1, sum = 0; 7 | while (n > 0) { 8 | let lastDigit = n % 10; 9 | product *= lastDigit; 10 | sum += lastDigit; 11 | n = Math.floor(n / 10); 12 | } 13 | return product - sum; 14 | }; 15 | 16 | // Time Complexity: O(n) 17 | // Space Complexity: O(1) -------------------------------------------------------------------------------- /Random_700_Qs/b_Second 100/q_a121.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer n, return any array containing n unique integers such that they add up to 0. 3 | 4 | Qs: 5 | 1. What to return if n is 0? 6 | - Return an empty array. 7 | */ 8 | 9 | function sumZero(n) { 10 | if (n == 1) return [0]; 11 | let nums = []; 12 | let sum = 0; 13 | for (let i = 1; i < n; i++) { 14 | nums.push(i); 15 | sum += i; 16 | } 17 | nums.push(-sum); 18 | return nums; 19 | } 20 | 21 | console.log(sumZero(1)); 22 | console.log(sumZero(2)); 23 | console.log(sumZero(3)); 24 | console.log(sumZero(4)); 25 | console.log(sumZero(5)); 26 | console.log(sumZero(6)); 27 | -------------------------------------------------------------------------------- /Random_700_Qs/b_Second 100/q_a124.js: -------------------------------------------------------------------------------- 1 | /* 2 | Write a function that, given array A consisting of N integers, returns the biggest value X, which occurs in A exactly X 3 | times. If there is no such value, the function should return 0. 4 | 5 | Qs: 6 | 1. Negative integers are impossible then, right? 7 | - Yes. 8 | */ 9 | 10 | function numberOccurringXTimes(A) { 11 | let m = new Map(); 12 | for (let num of A) { 13 | m.set(num, m.get(num)+1 || 1); 14 | } 15 | let max = 0; 16 | for (let [num, freq] of m) { 17 | if (num == freq && num > max) { 18 | max = num; 19 | } 20 | } 21 | return max; 22 | } 23 | // Time Complexity: O(n) 24 | // Space Complexity: O(n) 25 | 26 | console.log(numberOccurringXTimes([])) 27 | console.log(numberOccurringXTimes([3,5,1,0])) 28 | console.log(numberOccurringXTimes([3,5,1,0,3,3])) 29 | console.log(numberOccurringXTimes([3,3,3,5,1,0,5,5,5,5])) 30 | -------------------------------------------------------------------------------- /Random_700_Qs/b_Second 100/q_a126.js: -------------------------------------------------------------------------------- 1 | /* 2 | You are given a string S consisting of N characters and an integer K. 3 | You can modify string S by removing any substring of it. 4 | A substring is defined as a contiguous segment of a string. 5 | 6 | The goal is to find the shortest substring of S that, after removal, 7 | leaves S containing exactly K different characters. 8 | 9 | 10 | Write a function that, given a non-empty string S consisting of N characters and an integer K, 11 | returns the length of the shortest substring that can be removed. If there is no such substring, 12 | your function should return −1. 13 | */ 14 | 15 | function() { 16 | 17 | } 18 | 19 | -------------------------------------------------------------------------------- /Random_700_Qs/b_Second 100/q_a132.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer n, return any array containing n unique integers such that they add up to 0. 3 | 4 | Qs: 5 | 1. Can n be negative? 6 | - No. 7 | 2. What to return if n is zero? 8 | - Return an empty array. 9 | */ 10 | 11 | var sumZero = function(n) { 12 | let res = (n % 2 == 0) ? [] : [0]; 13 | for (let i = 1; i <= Math.floor(n/2); i++) res.push(i,-i); 14 | return res; 15 | // Time Complexity: O(n) 16 | // Space Complexity: O(1) 17 | // If n is even, we need to start from i=1 and keep pushing i and i-1 until 18 | // the half of n. If n is odd, we do the same except that we initialise our array 19 | // with zero in it so we can have a sum of zero but also have an odd number of unique 20 | // integers as well 21 | }; 22 | 23 | console.log(sumZero(0)) // => [] -------------------------------------------------------------------------------- /Random_700_Qs/b_Second 100/q_a136.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers nums and an integer k, 3 | 4 | return the total number of continuous subarrays whose sum equals to k. 5 | */ 6 | 7 | function subarraySum(nums, k) { 8 | let prefixSum = 0, total = 0; 9 | let m = new Map(); 10 | for (let i = 0; i < nums.length; i++) { 11 | prefixSum += nums[i]; 12 | if (prefixSum == k) total++; 13 | if (m.has(prefixSum-k)) total += m.get(prefixSum-k); 14 | m.set(prefixSum, m.get(prefixSum)+1 || 1); 15 | } 16 | return total; 17 | // key-value pair in m = (prefixSum, number of subarrays that have this prefix sum) 18 | // Time Complexity: O(n) 19 | // Space Complexity: O(n) 20 | } 21 | 22 | console.log(subarraySum([0,0,0,0],0)); 23 | console.log(subarraySum([-3,1,2,0,3,2],5)); -------------------------------------------------------------------------------- /Random_700_Qs/b_Second 100/q_a137.js: -------------------------------------------------------------------------------- 1 | /* 2 | Implement strStr(). 3 | 4 | Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. 5 | 6 | Clarification: 7 | 8 | What should we return when needle is an empty string? This is a great question to ask during an interview. 9 | 10 | For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf(). 11 | */ 12 | 13 | var strStr = function(haystack, needle) { 14 | if (needle.length == 0) return 0; 15 | for (let i = 0; i < haystack.length; i++) { 16 | let k = i, j = 0; 17 | while (haystack[k] == needle[j] && j < needle.length) { 18 | k++, j++; 19 | } 20 | if (j == needle.length) return i; 21 | } 22 | return -1; // couldn't find needle in haystack 23 | // Time Complexity: O(m*n) 24 | // Space Complexity: O(1) 25 | }; -------------------------------------------------------------------------------- /Random_700_Qs/b_Second 100/q_a138.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers nums and an integer k, 3 | 4 | return all continuous subarrays whose sum equals to k. 5 | */ 6 | 7 | function subarraySum(nums, k) { 8 | let prefixSum = 0, res = []; 9 | let m = new Map(); 10 | for (let i = 0; i < nums.length; i++) { 11 | prefixSum += nums[i]; 12 | if (prefixSum == k) res.push(nums.slice(0,i+1)); 13 | if (m.has(prefixSum-k)) { 14 | for (let idx of m.get(prefixSum-k)) { 15 | res.push(nums.slice(idx+1, i+1)); 16 | } 17 | } 18 | if (m.has(prefixSum)) m.set(prefixSum, [...m.get(prefixSum), i]); 19 | else m.set(prefixSum, [i]); 20 | } 21 | return res; 22 | // key-value pair in m = (prefixSum, number of subarrays that have this prefix sum) 23 | // Time Complexity: O(n) 24 | // Space Complexity: O(n) 25 | } 26 | 27 | console.log(subarraySum([0,0,0,0],0)); 28 | console.log(subarraySum([-3,1,2,0,3,2],5)); 29 | console.log(subarraySum([],0)); -------------------------------------------------------------------------------- /Random_700_Qs/b_Second 100/q_a145.js: -------------------------------------------------------------------------------- 1 | /* 2 | Suppose you have a random list of people standing in a queue. 3 | 4 | Each person is described by a pair of integers (h, k), where h is the height of the person and 5 | k is the number of people in front of this person who have a height greater than or equal to h. 6 | 7 | Write an algorithm to reconstruct the queue. 8 | 9 | Note: 10 | The number of people is less than 1,100. 11 | */ 12 | 13 | var reconstructQueue = function(people) { 14 | people.sort((a,b) => (a[0] !== b[0]) ? b[0]-a[0] : a[1]-b[1]); 15 | let res = []; 16 | for (let i = 0; i < people.length; i++) { 17 | let insertIdx = people[i][1]; 18 | res.splice(insertIdx, 0, people[i]); 19 | } 20 | return res; 21 | // Time Complexity: O(n^2) due to splice() function 22 | // Space Complexity: O(1) 23 | }; -------------------------------------------------------------------------------- /Random_700_Qs/b_Second 100/q_a146.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive. 3 | 4 | There is only one duplicate number in nums, return this duplicate number. 5 | 6 | Follow-ups: 7 | - How can we prove that at least one duplicate number must exist in nums? 8 | - Can you solve the problem without modifying the array nums? 9 | - Can you solve the problem using only constant, O(1) extra space? 10 | - Can you solve the problem with runtime complexity less than O(n2)? 11 | */ 12 | 13 | function findDuplicate(nums) { 14 | for (let i = 0; i < nums.length; i++) { 15 | let abs = Math.abs(nums[i]); 16 | if (nums[abs] < 0) return abs; 17 | else nums[abs] *= -1; 18 | } 19 | // Time Complexity: O(n) 20 | // Space Complexity: O(1) 21 | } -------------------------------------------------------------------------------- /Random_700_Qs/b_Second 100/q_a147.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers, find if the array contains any duplicates. 3 | 4 | Your function should return true if any value appears at least twice in the array, 5 | 6 | and it should return false if every element is distinct. 7 | */ 8 | 9 | function hasDuplicates(nums) { 10 | let m = new Map(); 11 | for (let i = 0; i < nums.length; i++) { 12 | if (m.has(nums[i])) return false; 13 | else m.set(nums[i], 1); 14 | } 15 | return true; 16 | // Time Complexity: O(n) 17 | // Space Complexity: O(n) 18 | } 19 | 20 | var containsDuplicate = function(nums) { 21 | return nums.length !== new Set(nums).size; 22 | // Time Complexity: O(n) 23 | // Space Complexity: O(n) 24 | }; -------------------------------------------------------------------------------- /Random_700_Qs/b_Second 100/q_a148.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given a non-empty array of integers nums, every element appears twice except for one. 3 | 4 | Find that single one. 5 | 6 | Follow up: Could you implement a solution with a linear runtime complexity and without using extra memory? 7 | */ 8 | var singleNumber = function(nums) { 9 | let m = new Map(); 10 | for (let num of nums) m.set(num, m.get(num)+1 || 1); 11 | for (let [num, occurr] of m) { 12 | if (occurr == 1) return num; 13 | } 14 | return -1; 15 | // Time Complexity: O(n) 16 | // Space Complexity: O(n) 17 | } 18 | 19 | var singleNumber = function(nums) { 20 | return nums.reduce((acc, cur) => acc ^ cur); 21 | // Time Complexity: O(n) 22 | // Space Complexity: O(1) 23 | }; 24 | // A XOR A is always equal to zero. 25 | // ex) 5 XOR 5 => 101 XOR 101 => 000 26 | // ex) 6 XOR XOR => 110 XOR 110 => 000 27 | // Therefore, if we XOR every number in the array, 28 | // we will be left with the single number. -------------------------------------------------------------------------------- /Random_700_Qs/b_Second 100/q_a149.js: -------------------------------------------------------------------------------- 1 | /* 2 | Reverse a singly linked list. 3 | */ 4 | 5 | function reverseList(head) { 6 | let prev = null, cur = head; 7 | while (cur !== null) { 8 | let next = cur.next; 9 | cur.next = prev; 10 | prev = cur; 11 | cur = next; 12 | } 13 | return prev; 14 | // Time Complexity: O(n) 15 | // Space Complexity: O(1) 16 | } -------------------------------------------------------------------------------- /Random_700_Qs/b_Second 100/q_a150.js: -------------------------------------------------------------------------------- 1 | /* 2 | Reverse a linked list from position m to n. Do it in one-pass. 3 | 4 | Ex) 5 | 1 -> 2 -> 3 -> 4 -> 5 -> NULL, m = 2, n = 4 6 | => 7 | 1 -> 4 -> 3 -> 2 -> 5 -> NULL 8 | */ 9 | 10 | var reverseBetween = function(head, m, n) { 11 | let start = head, cur = head; 12 | let i = 1; 13 | while (i < m) { 14 | start = cur; 15 | cur = cur.next; 16 | i++; 17 | } 18 | let prev = null, tail = cur; 19 | while (i <= n) { 20 | let next = cur.next; 21 | cur.next = prev; 22 | prev = cur; 23 | cur = next; 24 | i++; 25 | } 26 | start.next = prev; 27 | tail.next = cur; 28 | return m == 1 ? prev : head; 29 | // if m == 1, we have no need to connect start list with reversed list reversed list itself is the start (or the head) 30 | // Time Complexity: O(n) 31 | // Space Complexity: O(1) 32 | }; -------------------------------------------------------------------------------- /Random_700_Qs/b_Second 100/q_a152.js: -------------------------------------------------------------------------------- 1 | /* 2 | DFS implementation of traversal of a 2-D array 3 | */ 4 | 5 | function traverse2dArr(grid) { 6 | let height = grid.length, width = grid[0].length; 7 | const DIRECTIONS = [[-1,0],[0,1],[1,0],[0,-1]]; 8 | let res = []; 9 | let visited = new Array(height).fill(0).map(() => new Array(width).fill(false)); 10 | function traverse(row, col, visited) { 11 | if (row < 0 || row >= width || col < 0 || col >= height || visited[row][col] == true) return; 12 | res.push(grid[row][col]); 13 | visited[row][col] = true; 14 | for (let dir of DIRECTIONS) { 15 | traverse(row+dir[0],col+dir[1],visited); 16 | } 17 | } 18 | traverse(0, 0, visited); 19 | return res; 20 | // Time Complexity: O(m*n) where m = number of rows, n = number of columns 21 | // Space Complexity: O(m*n) 22 | } 23 | console.log(traverse2dArr( 24 | [[1,2,3],[4,5,6],[7,8,9]] 25 | )); -------------------------------------------------------------------------------- /Random_700_Qs/b_Second 100/q_a155.js: -------------------------------------------------------------------------------- 1 | /* 2 | BFS implementation of traversal of a 2-D array 3 | */ 4 | 5 | function traverse2dArr(grid) { 6 | let height = grid.length, width = grid[0].length; 7 | let visited = new Array(height).fill(0).map(() => new Array(width).fill(false)); 8 | const DIRECTIONS = [[-1,0],[0,1],[1,0],[0,-1]]; 9 | let values = [], queue = [[0,0]]; 10 | 11 | while (queue.length > 0) { 12 | let [row, col] = queue.shift(); 13 | if (row < 0 || row >= height || col < 0 || col >= width || visited[row][col] == true) { 14 | continue; 15 | } 16 | values.push(grid[row][col]); 17 | visited[row][col] = true; 18 | for (let dir of DIRECTIONS) { 19 | queue.push([row+dir[0], col+dir[1]]); 20 | } 21 | } 22 | return values; 23 | // Time Complexity: O(m*n) where m = number of rows, n = number of columns 24 | // Space Complexity: O(m*n) 25 | } 26 | 27 | console.log(traverse2dArr( 28 | [[1,2,3],[4,5,6],[7,8,9]] 29 | )); -------------------------------------------------------------------------------- /Random_700_Qs/b_Second 100/q_a157.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given an Array A, find the minimum amplitude you can get after changing up to 3 elements. 3 | 4 | Amplitude is the range of the array (basically difference between largest and smallest element). 5 | 6 | Ex) 7 | [-1, 3, -1, 8, 5 4] => 2 8 | [10, 10, 3, 4, 10] => 0 9 | */ -------------------------------------------------------------------------------- /Random_700_Qs/b_Second 100/q_a158.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string S, we can split S into 2 strings: S1 and S2. 3 | 4 | Return the number of ways S can be split such that the number of unique characters between S1 and S2 are the same. 5 | 6 | Ex) 7 | "aaaa" => 3 8 | "bac" => 0 9 | "ababa" => 2 10 | */ -------------------------------------------------------------------------------- /Random_700_Qs/b_Second 100/q_a160.js: -------------------------------------------------------------------------------- 1 | /* 2 | One string is strictly smaller than another when the frequency of occurrence of the smallest character in the string 3 | 4 | is less than the frequency of occurrence of the smallest character in the comparison string. 5 | */ 6 | 7 | -------------------------------------------------------------------------------- /Random_700_Qs/b_Second 100/q_a163.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given a n-ary tree, find its maximum depth. 3 | 4 | The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 5 | */ 6 | 7 | var maxDepth = function(root) { 8 | if (!root) return 0; 9 | let maxDepth = 0; 10 | function traverse(root, depth) { 11 | if (root.children == 0) { 12 | maxDepth = Math.max(maxDepth, depth); 13 | return; 14 | } 15 | for (let child of root.children) { 16 | traverse(child, depth+1); 17 | } 18 | } 19 | traverse(root, 1); 20 | return maxDepth; 21 | // Time Complexity: O(n) 22 | // Space Complexity: O(n) 23 | }; -------------------------------------------------------------------------------- /Random_700_Qs/b_Second 100/q_a164.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). 3 | */ 4 | 5 | function levelOrder(root) { 6 | if (root == null) return []; 7 | let queue = [], values = []; 8 | queue.push(root); 9 | while (queue.length > 0) { 10 | let len = queue.length, level = []; 11 | for (let i = 0; i < len; i++) { 12 | let node = queue.shift(); 13 | level.push(node.val); 14 | if (node.left) queue.push(node.left); 15 | if (node.right) queue.push(node.right); 16 | } 17 | values.push(level); 18 | } 19 | return values; 20 | // Time Complexity: O(n) 21 | // Space Complexity: O(n) 22 | } -------------------------------------------------------------------------------- /Random_700_Qs/b_Second 100/q_a166.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given a complete binary tree, count the number of nodes. 3 | 4 | Note: 5 | In a complete binary tree every level, except possibly the last, is completely filled, 6 | and all nodes in the last level are as far left as possible. 7 | It can have between 1 and 2h nodes inclusive at the last level h. 8 | */ 9 | 10 | -------------------------------------------------------------------------------- /Random_700_Qs/b_Second 100/q_a169.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers, 3 | 4 | write a function that returns true if there is a triplet (a, b, c) that satisfies a2 + b2 = c2. 5 | */ 6 | 7 | function pythagoreanTriplets(nums) { 8 | let set = new Set(nums.map(num => num*num)); 9 | console.log(set) 10 | for (let i = 0; i < nums.length; i++) { 11 | for (let j = i+1; j < nums.length; j++) { 12 | let num1 = nums[i], num2 = nums[j]; 13 | if (set.has(num1**2 + num2**2)) { 14 | return true; 15 | } 16 | } 17 | } 18 | return false; 19 | } 20 | 21 | console.log(pythagoreanTriplets([1,2,5,9,13,12])); // => true 22 | console.log(pythagoreanTriplets([1,2,3,4,5])); // => true 23 | console.log(pythagoreanTriplets([1,2,3])); // => false 24 | 25 | -------------------------------------------------------------------------------- /Random_700_Qs/b_Second 100/q_a171.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given head, the head of a linked list, determine if the linked list has a cycle in it. 3 | 4 | There is a cycle in a linked list if there is some node in the list that can be reached again 5 | 6 | by continuously following the next pointer. 7 | 8 | Return true if there is a cycle in the linked list. Otherwise, return false. 9 | */ 10 | 11 | var hasCycle = function(head) { 12 | let slow = head, fast = head; 13 | while (fast !== null) { 14 | fast = fast.next; 15 | if (slow == fast) return true; 16 | 17 | if (fast == null) break; 18 | else fast = fast.next; 19 | 20 | if (slow == fast) return true; 21 | slow = slow.next; 22 | } 23 | return false; 24 | // Time Complexity: O(n) 25 | // Space Complexity: O(1) 26 | }; -------------------------------------------------------------------------------- /Random_700_Qs/b_Second 100/q_a173.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given a non-empty, singly linked list with head node head, return a middle node of linked list. 3 | 4 | If there are two middle nodes, return the second middle node. 5 | */ 6 | 7 | var middleNode = function(head) { 8 | let slow = head, fast = head; 9 | while (fast !== null) { 10 | fast = fast.next; 11 | if (fast == null) break; 12 | else fast = fast.next; 13 | 14 | slow = slow.next; 15 | } 16 | return slow; 17 | // Time Complexity: O(n) 18 | // Space Complexity: O(1) 19 | }; -------------------------------------------------------------------------------- /Random_700_Qs/b_Second 100/q_a174.js: -------------------------------------------------------------------------------- 1 | /* 2 | Merge two sorted linked lists and return it as a new sorted list. 3 | 4 | The new list should be made by splicing together the nodes of the first two lists. 5 | */ 6 | 7 | var mergeTwoLists = function(l1, l2) { 8 | let dummy = new ListNode(); 9 | let cur = dummy; 10 | while (l1 && l2) { 11 | if (l1.val <= l2.val) { 12 | cur.next = l1; 13 | l1 = l1.next; 14 | } else { 15 | cur.next = l2; 16 | l2 = l2.next; 17 | } 18 | cur = cur.next; 19 | } 20 | if (l1) cur.next = l1; 21 | else if (l2) cur.next = l2; 22 | 23 | return dummy.next; 24 | // Time Complexity: O(n) 25 | // Space Complexity: O(1) 26 | }; -------------------------------------------------------------------------------- /Random_700_Qs/b_Second 100/q_a176.js: -------------------------------------------------------------------------------- 1 | /* 2 | Remove all elements from a linked list of integers that have value val. 3 | */ 4 | 5 | var removeElements = function(head, val) { 6 | let dummy = new ListNode(); 7 | let cur = dummy; 8 | 9 | while (head !== null) { 10 | if (head.val !== val) { 11 | cur.next = head; 12 | cur = cur.next; 13 | } 14 | head = head.next; 15 | } 16 | cur.next = null; 17 | return dummy.next; 18 | // Time Complexity: O(n) 19 | // Space Complexity: O(1) 20 | // Scan through the linked list and append all nodes whose values are different 21 | // from "val" to current list which we will return at the end 22 | // Make sure the last node point to null since it might point to a node 23 | // whose value is equal to "val" 24 | }; -------------------------------------------------------------------------------- /Random_700_Qs/b_Second 100/q_a177.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given head which is a reference node to a singly-linked list. 3 | 4 | The value of each node in the linked list is either 0 or 1. 5 | 6 | The linked list holds the binary representation of a number. 7 | 8 | Return the decimal value of the number in the linked list. 9 | */ 10 | 11 | var getDecimalValue = function(head) { 12 | let exponent = getLengthOfLL(head)-1; 13 | let number = 0; 14 | while (head !== null) { 15 | number += head.val * 2**exponent; 16 | head = head.next; 17 | exponent--; 18 | } 19 | return number; 20 | // Time Complexity: O(n) 21 | // Space Complexity: O(1) 22 | } 23 | 24 | function getLengthOfLL(head) { 25 | let len = 0; 26 | while (head !== null) { 27 | head = head.next; 28 | len++; 29 | } 30 | return len; 31 | } -------------------------------------------------------------------------------- /Random_700_Qs/b_Second 100/q_a178.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? 3 | 4 | Find all unique triplets in the array which gives the sum of zero. 5 | 6 | Notice that the solution set must not contain duplicate triplets. 7 | */ 8 | 9 | var threeSum = function(nums) { 10 | nums.sort((a,b) => a-b); 11 | let set = new Set(), res = []; 12 | for (let i = 0; i < nums.length; i++) { 13 | if (nums[i] == nums[i-1]) continue; // avoid duplicate triplets 14 | let m = new Map(); 15 | for (let j = i+1; j < nums.length; j++) { 16 | let sum = nums[i] + nums[j]; 17 | if (m.has(-sum)) { 18 | set.add(`${nums[i]}#${-sum}#${nums[j]}`); 19 | } 20 | m.set(nums[j], j); 21 | } 22 | } 23 | for (let key of set) { 24 | res.push(key.split("#")); 25 | } 26 | return res; 27 | // Time Complexity: O(n^2) 28 | // Space Complexity: O(n) 29 | }; -------------------------------------------------------------------------------- /Random_700_Qs/b_Second 100/q_a180.js: -------------------------------------------------------------------------------- 1 | /* 2 | Write a function to delete a node in a singly-linked list. You will not be given access to the head of the list, 3 | 4 | instead you will be given access to the node to be deleted directly. 5 | 6 | It is guaranteed that the node to be deleted is not a tail node in the list. 7 | */ 8 | 9 | var deleteNode = function(node) { 10 | node.val = node.next.val; 11 | node.next = node.next.next; 12 | // Time Complexity: O(1) 13 | // Space Complexity: O(1) 14 | }; -------------------------------------------------------------------------------- /Random_700_Qs/b_Second 100/q_a184.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array nums of n integers where n > 1, 3 | 4 | return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. 5 | */ 6 | 7 | var productExceptSelf = function(nums) { 8 | let res = []; 9 | let productL = 1, productR = 1; 10 | for (let i = 0; i < nums.length; i++) { 11 | res[i] = productL; 12 | productL *= nums[i]; 13 | } 14 | for (let i = nums.length-1; i >= 0; i--) { 15 | res[i] *= productR; 16 | productR *= nums[i]; 17 | } 18 | return res; 19 | // Time Complexity: O(n) 20 | // Space Complexity: O(1) 21 | }; -------------------------------------------------------------------------------- /Random_700_Qs/b_Second 100/q_a185.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array nums with n integers, your task is to check if it could become non-decreasing by modifying at most 1 element. 3 | 4 | We define an array is non-decreasing if nums[i] <= nums[i + 1] holds for every i (0-based) such that (0 <= i <= n - 2). 5 | */ 6 | 7 | var checkPossibility = function(nums) { 8 | let elemToModify = 0; 9 | for (i = 0; i < nums.length; i++) { 10 | if (nums[i] > nums[i+1]) { 11 | if (nums[i-1] > nums[i+1]) { 12 | // because otherwise, we need to modify 2 elements 13 | // nums[i] and nums[i-1] 14 | // it is better to modify nums[i+1] instead 15 | nums[i+1] = nums[i]; 16 | } else nums[i] = nums[i+1]; 17 | elemToModify++; 18 | } 19 | if (elemToModify > 1) return false; 20 | } 21 | return true; 22 | // Time Complexity: O(n) 23 | // Space Complexity: O(1) 24 | }; 25 | -------------------------------------------------------------------------------- /Random_700_Qs/b_Second 100/q_a187.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given the head of a linked list, remove the nth node from the end of the list and return its head. 3 | 4 | Follow up: Could you do this in one pass? 5 | */ 6 | 7 | var removeNthFromEnd = function(head, n) { 8 | let ptr1 = head, ptr2 = head; 9 | for (let i = 0; i < n; i++) { 10 | ptr2 = ptr2.next; 11 | } 12 | if (ptr2 == null) { 13 | // we need to delete the first node 14 | head = head.next; 15 | } 16 | else { 17 | while (ptr2.next !== null) { 18 | ptr1 = ptr1.next; 19 | ptr2 = ptr2.next; 20 | } 21 | ptr1.next = ptr1.next.next; 22 | } 23 | return head; 24 | // Time Complexity: O(n) 25 | // Space Complexity: O(1) 26 | }; -------------------------------------------------------------------------------- /Random_700_Qs/b_Second 100/q_a188.js: -------------------------------------------------------------------------------- 1 | /* 2 | Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. 3 | 4 | Qs: 5 | 1. Are there duplicates? 6 | - Yes. 7 | 2. Are there negative integers? 8 | - Yes. 9 | */ 10 | 11 | var findKthLargest = function(nums, k) { 12 | nums.sort((a,b) => b-a); 13 | return nums[k-1]; 14 | // Time Complexity: O(nlog(n)) 15 | // Space Complexity: O(1) 16 | }; -------------------------------------------------------------------------------- /Random_700_Qs/b_Second 100/q_a197.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. 3 | */ 4 | 5 | var generateParenthesis = function(n) { 6 | let res = []; 7 | function permute(open, close, cur) { 8 | if (cur.length === 2*n) { 9 | res.push(cur); 10 | return; 11 | } 12 | if (open > 0) { 13 | permute(open-1, close+1, cur + "("); 14 | } 15 | if (close > 0) { 16 | permute(open, close-1, cur + ")"); 17 | } 18 | } 19 | permute(n, 0, ""); 20 | return res; 21 | // Space Complexity: O(2n) = O(n) 22 | }; 23 | -------------------------------------------------------------------------------- /Random_700_Qs/b_Second 100/q_a198.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, determine if it is height-balanced. 3 | 4 | For this problem, a height-balanced binary tree is defined as: 5 | - a binary tree in which the left and right subtrees of every node differ in height by no more than 1. 6 | */ 7 | 8 | var isBalanced = function(root) { 9 | let balanced = true; 10 | 11 | function findHeight(root) { 12 | if (!root) return 0; 13 | if (balanced === false) return; // optimisation: early exit 14 | 15 | let leftHeight = findHeight(root.left); 16 | let rightHeight = findHeight(root.right); 17 | let diff = Math.abs(leftHeight - rightHeight); 18 | 19 | if (diff > 1) balanced = false; 20 | 21 | return Math.max(leftHeight, rightHeight) + 1; 22 | } 23 | 24 | findHeight(root); 25 | return balanced; 26 | // Time Complexity: O(n), we possibly visit all nodes 27 | // Space Complexity: O(H), call stack will possibly go as deep as height 28 | }; -------------------------------------------------------------------------------- /Random_700_Qs/c_Third 100/q_a201.js: -------------------------------------------------------------------------------- 1 | // Invert a binary tree. 2 | 3 | var invertTree = function(root) { 4 | 5 | function invert(root) { 6 | if (!root) return null; 7 | let invertedLeft = invert(root.left); 8 | let invertedRight = invert(root.right); 9 | root.left = invertedRight; 10 | root.right = invertedLeft; 11 | 12 | return root; 13 | } 14 | invert(root); 15 | 16 | return root; 17 | 18 | // Time Complexity: O(N), we always visit all nodes 19 | // Space Complexity: O(H) or O(N), call stack can possibly go as deep as height of tree and the height can be N at most (in case of a skewed tree) 20 | }; -------------------------------------------------------------------------------- /Random_700_Qs/c_Third 100/q_a204.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given two arrays, write a function to compute their intersection. 3 | - Each element in the result must be unique. 4 | - The result can be in any order. 5 | */ 6 | 7 | var intersection = function(nums1, nums2) { 8 | let m = new Map(), res = []; 9 | for (let i = 0; i < nums1.length; i++) { 10 | m.set(nums1[i], 1); 11 | } 12 | for (let i = 0; i < nums2.length; i++) { 13 | if (m.get(nums2[i]) > 0) { 14 | res.push(nums2[i]); 15 | m.set(nums2[i], 0); 16 | } 17 | } 18 | return res; 19 | // Time Complexity: O(m + n) 20 | // Space Complexity: O(max(m, n)) 21 | }; 22 | 23 | console.log(intersection([1,2,3,4], [4])) -------------------------------------------------------------------------------- /Random_700_Qs/c_Third 100/q_a207.js: -------------------------------------------------------------------------------- 1 | /* 2 | You are given a sorted unique integer array nums. 3 | 4 | Return the smallest sorted list of ranges that cover all the numbers in the array exactly. 5 | 6 | That is, each element of nums is covered by exactly one of the ranges, and there is no integer x such that 7 | x is in one of the ranges but not in nums. 8 | 9 | Each range [a,b] in the list should be output as: 10 | - "a->b" if a != b 11 | - "a" if a == b 12 | */ 13 | 14 | var summaryRanges = function(nums) { 15 | let i = 0, res = []; 16 | for (let j = 0; j < nums.length; j++) { 17 | if (nums[j+1] === nums[j] + 1) continue; 18 | else { 19 | if (i == j) res.push(nums[i] + ""); 20 | else res.push( nums[i] + "->" + nums[j] ); 21 | i = j + 1; 22 | } 23 | } 24 | return res; 25 | // Time Complexity: O(n) 26 | // Space Complexity: O(1) 27 | }; -------------------------------------------------------------------------------- /Random_700_Qs/c_Third 100/q_a209.js: -------------------------------------------------------------------------------- 1 | // Given two numbers, hour and minutes. Return the smaller angle (in degrees) formed between the hour and the minute hand. 2 | 3 | var angleClock = function(hour, minutes) { 4 | let hourAngle = (hour % 12) * 30 + minutes * 0.5; 5 | // hour-hand rotates 30 degrees per hour and 0.5 degrees per minute 6 | let minuteAngle = minutes * 6; 7 | // minute-hand rotates 6 degrees Per minute 8 | 9 | let angle1 = Math.abs(hourAngle - minuteAngle); 10 | let angle2 = 360 - angle1; 11 | 12 | return Math.min(angle1, angle2); 13 | // Time Complexity: O(1) 14 | // Space Complexity: O(1) 15 | }; -------------------------------------------------------------------------------- /Random_700_Qs/c_Third 100/q_a212.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). 3 | */ 4 | 5 | var levelOrder = function(root) { 6 | if (!root) return []; 7 | let queue = [root], res = []; 8 | while (queue.length > 0) { 9 | let len = queue.length, level = []; 10 | for (let i = 0; i < len; i++) { 11 | let node = queue.shift(); 12 | level.push(node.val); 13 | if (node.left) queue.push(node.left); 14 | if (node.right) queue.push(node.right); 15 | } 16 | res.push(level); 17 | } 18 | return res; 19 | // Time Complexity: O(n), we visit all nodes 20 | // Space Complexity: O(n/2) = O(n), the bottom level can contain n/2 nodes at most 21 | }; -------------------------------------------------------------------------------- /Random_700_Qs/c_Third 100/q_a218.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string s consisting only of characters a, b and c. 3 | 4 | Return the number of substrings containing at least one occurrence of all these characters a, b and c. 5 | */ 6 | 7 | var numberOfSubstrings = function(s) { 8 | let obj = {'a': 0, 'b': 0, 'c': 0}; 9 | let total = 0, count = 0, start = 0; 10 | for (let end = 0; end < s.length; end++) { 11 | obj[s[end]]++; 12 | if (obj[s[end]] == 1) count++; 13 | while (count === 3) { 14 | total += s.length - end; 15 | obj[s[start]]--; 16 | if (obj[s[start]] == 0) count--; 17 | start++; 18 | } 19 | } 20 | return total; 21 | // Time Complexity: O(n) 22 | // Space Complexity: O(1) 23 | }; 24 | -------------------------------------------------------------------------------- /Random_700_Qs/c_Third 100/q_a226.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given two binary trees, write a function to check if they are the same or not. 3 | 4 | Two binary trees are considered the same if they are structurally identical and the nodes have the same value. 5 | */ 6 | 7 | var isSameTree = function(p, q) { 8 | function isEqual(root1, root2) { 9 | if (!root1 && !root2) return true; 10 | if (!root1 || !root2) return false; 11 | return (root1.val == root2.val && isEqual(root1.left, root2.left) 12 | && isEqual(root1.right, root2.right)); 13 | } 14 | return isEqual(p, q); 15 | // Time Complexity: O(n), we visit all nodes if they are the same tree 16 | // Space Complexity: O(H), call stack can go as deep as the height of tree, and the height can be n at most in case of a skewed tree so we can say O(n), too. 17 | }; -------------------------------------------------------------------------------- /Random_700_Qs/c_Third 100/q_a227.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 3 | 4 | For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. 5 | */ 6 | 7 | var sortedArrayToBST = function(nums) { 8 | function constructBST(nums) { 9 | // No more available value to construct a node with 10 | if (nums.length == 0) return null; 11 | let mid = Math.floor((nums.length-1) / 2); 12 | let root = new TreeNode(nums[mid]); 13 | let leftSub = constructBST(nums.slice(0,mid)); 14 | let rightSub = constructBST(nums.slice(mid+1)); 15 | root.left = leftSub; 16 | root.right = rightSub; 17 | return root; 18 | } 19 | 20 | return constructBST(nums); 21 | // Time Complexity: O(N), we touch every node once 22 | // Space Complexity: O(H), call stack can go as deep as height 23 | }; -------------------------------------------------------------------------------- /Random_700_Qs/c_Third 100/q_a238.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers arr, sort the array by performing a series of pancake flips. 3 | 4 | In one pancake flip we do the following steps: 5 | - Choose an integer k where 1 <= k <= arr.length. 6 | - Reverse the sub-array arr[1...k]. 7 | 8 | For example, if arr = [3,2,1,4] and we performed a pancake flip choosing k = 3, we reverse the sub-array [3,2,1], so arr = [1,2,3,4] after the pancake flip at k = 3. 9 | 10 | Return the k-values corresponding to a sequence of pancake flips that sort arr. Any valid answer that sorts the array within 10 * arr.length flips will be judged as correct. 11 | */ -------------------------------------------------------------------------------- /Random_700_Qs/c_Third 100/q_a241.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. 3 | 4 | Follow up: The overall run time complexity should be O(log (m+n)). 5 | */ 6 | 7 | // Intuitive Solution 8 | var findMedianSortedArrays = function(nums1, nums2) { 9 | let sorted = []; 10 | let idx1 = 0, idx2 = 0; 11 | while (idx1 < nums1.length && idx2 < nums2.length) { 12 | if (nums1[idx1] < nums2[idx2]) { 13 | sorted.push(nums1[idx1]); 14 | idx1++; 15 | } else { 16 | sorted.push(nums2[idx2]); 17 | idx2++; 18 | } 19 | } 20 | while (idx1 < nums1.length) sorted.push(nums1[idx1++]); 21 | while (idx2 < nums2.length) sorted.push(nums2[idx2++]); 22 | let mid = Math.floor((sorted.length-1) / 2); 23 | return sorted.length % 2 == 1 ? sorted[mid] : (sorted[mid] + sorted[mid+1]) / 2; 24 | // Time Complexity: O(m+n) 25 | // Space Complexity: O(m+n) 26 | }; -------------------------------------------------------------------------------- /Random_700_Qs/c_Third 100/q_a243.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given two strings s and t , write a function to determine if t is an anagram of s. 3 | */ 4 | 5 | var isAnagram = function(s, t) { 6 | if (s.length !== t.length) return false; 7 | let m = new Map(); 8 | for (let i = 0; i < s.length; i++) { 9 | m.set(s[i], m.get(s[i]) + 1 || 1); 10 | } 11 | let count = m.size; 12 | for (let i = 0; i < t.length; i++) { 13 | if (!m.has(t[i])) return false; 14 | m.set(t[i], m.get(t[i]) - 1); 15 | if (m.get(t[i]) == 0) count--; 16 | } 17 | return count == 0; 18 | // Time Complexity: O(n) 19 | // Space Complexity: O(n) 20 | }; -------------------------------------------------------------------------------- /Random_700_Qs/c_Third 100/q_a246.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hbjORbj/interview_prep_javascript/06c8339bc6cac4b87f0da447d08cc4257823cea8/Random_700_Qs/c_Third 100/q_a246.js -------------------------------------------------------------------------------- /Random_700_Qs/c_Third 100/q_a252.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree root and an integer target, delete all the leaf nodes with value target. 3 | 4 | Note that once you delete a leaf node with value target, if it's parent node becomes a leaf node and has the value target, it should also be deleted (you need to continue doing that until you can't). 5 | */ 6 | 7 | var removeLeafNodes = function(root, target) { 8 | function removeTargetLeaves(root, target) { 9 | if (!root) return null; 10 | if (root.val == target && !root.left && !root.right) { 11 | return null; 12 | } 13 | root.left = removeLeafNodes(root.left, target); 14 | root.right = removeLeafNodes(root.right, target); 15 | if (root.val == target && !root.left && !root.right) { 16 | return null; 17 | } 18 | return root; 19 | } 20 | return removeTargetLeaves(root, target); 21 | // Time Complexity: O(N), we visit all nodes 22 | // Space Complexity: O(H), call stack can go as deep as height of tree 23 | }; 24 | -------------------------------------------------------------------------------- /Random_700_Qs/c_Third 100/q_a253.js: -------------------------------------------------------------------------------- 1 | // Given an n-ary tree, return the preorder traversal of its nodes' values. 2 | 3 | // Recursive 4 | var preorder = function(root) { 5 | let res = []; 6 | function dfsTraversal(root) { 7 | if (!root) return; 8 | res.push(root.val); 9 | for (let child of root.children) { 10 | dfsTraversal(child); 11 | } 12 | } 13 | dfsTraversal(root); 14 | return res; 15 | // Time Complexity: O(N) 16 | // Space Complexity: O(H) 17 | }; 18 | 19 | // Iterative 20 | var preorder = function(root) { 21 | if (!root) return []; 22 | let stack = [root], res = []; 23 | while (stack.length > 0) { 24 | let node = stack.pop(); 25 | res.push(node.val); 26 | for (let i = node.children.length - 1; i >= 0; i--) { 27 | if (node.children[i]) stack.push(node.children[i]); 28 | } 29 | } 30 | return res; 31 | // Time Complexity: O(N) 32 | // Space Complexity: O(H) 33 | } -------------------------------------------------------------------------------- /Random_700_Qs/c_Third 100/q_a256.js: -------------------------------------------------------------------------------- 1 | /* 2 | A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. 3 | 4 | Return a deep copy of the list. 5 | */ 6 | 7 | // Bottom-Up Approach 8 | var copyRandomList = function(head) { 9 | let m = new Map(); 10 | function copyList(head) { 11 | if (!head) return null; 12 | if (m.has(head)) return m.get(head); 13 | let newNode = new Node(); 14 | m.set(head, newNode); 15 | newNode.val = head.val; 16 | newNode.next = copyList(head.next); 17 | newNode.random = copyList(head.random); 18 | return newNode; 19 | } 20 | return copyList(head); 21 | // Time Complexity: O(n) 22 | // Space Complexity: O(n) 23 | }; -------------------------------------------------------------------------------- /Random_700_Qs/c_Third 100/q_a260.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. 3 | */ 4 | 5 | var diameterOfBinaryTree = function(root) { 6 | let max = 0; 7 | getDepth(root); // For a subtree, the sum of the left subtree's max depth and the right subtree's max depth is the longest possible path in the subtree. So, we perform this on every subtree and update the maximum length. 8 | return max; 9 | function getDepth(root) { 10 | if (!root) return 0; 11 | let left = getDepth(root.left); 12 | let right = getDepth(root.right); 13 | max = Math.max(max, left + right); 14 | return Math.max(left, right) + 1; 15 | } 16 | // Time Complexity: O(N) 17 | // Space Complexity: O(H) 18 | }; -------------------------------------------------------------------------------- /Random_700_Qs/c_Third 100/q_a265.js: -------------------------------------------------------------------------------- 1 | /* 2 | You are given the root of a binary tree where each node has a value 0 or 1. Each root-to-leaf path represents a binary number starting with the most significant bit. For example, if the path is 0 -> 1 -> 1 -> 0 -> 1, then this could represent 01101 in binary, which is 13. 3 | 4 | For all leaves in the tree, consider the numbers represented by the path from the root to that leaf. 5 | 6 | Return the sum of these numbers. The answer is guaranteed to fit in a 32-bits integer. 7 | */ 8 | 9 | var sumRootToLeaf = function(root) { 10 | let res = 0; 11 | dfs(root); 12 | return res; 13 | function dfs(root, num = "") { 14 | if (!root) return; 15 | if (!root.left && !root.right) { 16 | res += parseInt(num + root.val, 2); 17 | return; 18 | } 19 | dfs(root.left, num + root.val); 20 | dfs(root.right, num + root.val); 21 | } 22 | // Time Complexity: O(N) 23 | // Space Complexity: O(H) 24 | }; -------------------------------------------------------------------------------- /Random_700_Qs/c_Third 100/q_a282.js: -------------------------------------------------------------------------------- 1 | /* 2 | In a binary tree, a lonely node is a node that is the only child of its parent node. 3 | 4 | The root of the tree is not lonely because it does not have a parent node. 5 | 6 | Given the root of a binary tree, return an array containing the values of all lonely nodes in the tree. 7 | 8 | Return the list in any order. 9 | */ 10 | 11 | var getLonelyNodes = function(root) { 12 | let res = []; 13 | dfs(root); 14 | return res; 15 | // Time Complexity: O(N), we visit all nodes 16 | // Space Complexity: O(H), call stack can go as deep as height of tree and this height can be at most N (in case of a skewed tree) 17 | 18 | function dfs(root) { 19 | if (!root) return; 20 | if (root.left && !root.right) { 21 | res.push(root.left.val); 22 | } 23 | if (!root.left && root.right) { 24 | res.push(root.right.val); 25 | } 26 | dfs(root.left); 27 | dfs(root.right); 28 | } 29 | }; -------------------------------------------------------------------------------- /Random_700_Qs/c_Third 100/q_a283.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given the root of a binary tree, return the sum of every tree node's tilt. 3 | 4 | The tilt of a tree node is the absolute difference between the sum of all left subtree node values and all right subtree node values. 5 | 6 | If a node does not have a left child, then the sum of the left subtree node values is treated as 0. 7 | 8 | The rule is similar if there the node does not have a right child. 9 | */ 10 | 11 | var findTilt = function(root) { 12 | let tilt = 0; 13 | computeSum(root); 14 | return tilt; 15 | // Time Complexity: O(N), we visit all nodes once 16 | // Space Complexity: O(H) 17 | 18 | function computeSum(root) { 19 | if (!root) return 0; 20 | let leftSum = computeSum(root.left); 21 | let rightSum = computeSum(root.right); 22 | tilt += Math.abs(leftSum - rightSum); 23 | return root.val + leftSum + rightSum; 24 | } 25 | }; -------------------------------------------------------------------------------- /Random_700_Qs/c_Third 100/q_a285.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array arr of positive integers, consider all binary trees such that: 3 | 4 | -Each node has either 0 or 2 children; 5 | - The values of arr correspond to the values of each leaf in an in-order traversal of the tree. (Recall that a node is a leaf if and only if it has 0 children.) 6 | - The value of each non-leaf node is equal to the product of the largest leaf value in its left and right subtree respectively. 7 | 8 | Among all possible binary trees considered, return the smallest possible sum of the values of each non-leaf node. It is guaranteed this sum fits into a 32-bit integer. 9 | */ 10 | -------------------------------------------------------------------------------- /Random_700_Qs/c_Third 100/q_a298.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. 3 | 4 | Return the linked list sorted as well. 5 | */ 6 | 7 | var deleteDuplicates = function(head) { 8 | let newHead = new ListNode(); 9 | let cur = newHead, duplicate = 0; 10 | while (head !== null) { 11 | if (head.next && head.val == head.next.val) { 12 | duplicate++; 13 | } else { 14 | if (duplicate == 0) { 15 | cur.next = head; 16 | cur = cur.next; 17 | } 18 | duplicate = 0; 19 | } 20 | head = head.next; 21 | } 22 | cur.next = null; 23 | return newHead.next; 24 | // Time Complexity: O(N) 25 | // Space Complexity: O(1) 26 | }; -------------------------------------------------------------------------------- /Random_700_Qs/d_Fourth 100/q_a304.js: -------------------------------------------------------------------------------- 1 | /* 2 | Write a function to find the longest common prefix string amongst an array of strings. 3 | 4 | If there is no common prefix, return an empty string "". 5 | */ 6 | 7 | var longestCommonPrefix = function(strs) { 8 | if (strs.length == 0) return ""; 9 | let prefix = ""; 10 | for (let i = 0; i < strs[0].length; i++) { 11 | let letter = strs[0][i]; 12 | for (let j = 0; j < strs.length; j++) { 13 | if (strs[j][i] !== letter) { 14 | return prefix; 15 | } 16 | } 17 | prefix += letter; 18 | } 19 | return prefix; 20 | // Time Complexity: O(M*N), M = length of shortest word, N = length of given array 21 | // Space Complexity: O(1) 22 | }; 23 | 24 | /* 25 | ["flow"] => "flow" 26 | [] => "" 27 | 1. Scan through the array and check if the first letter of every string is the same. If true, append 28 | the letter to prefix, and scan through again to check the next letter. Else, return the current prefix. 29 | */ -------------------------------------------------------------------------------- /Random_700_Qs/d_Fourth 100/q_a306.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 3 | 4 | An input string is valid if: 5 | - Open brackets must be closed by the same type of brackets. 6 | - Open brackets must be closed in the correct order. 7 | */ 8 | 9 | var isValid = function(s) { 10 | let stack = []; 11 | for (let i = 0; i < s.length; i++) { 12 | let par = s[i]; 13 | if (par == ')') { 14 | if (stack.pop() !== '(') return false; 15 | } else if (par == ']') { 16 | if (stack.pop() !== '[') return false; 17 | } else if (par == '}') { 18 | if (stack.pop() !== '{') return false; 19 | } else { // open parentheses 20 | stack.push(par); 21 | } 22 | } 23 | return stack.length == 0; // there might still be remaining parenthese to be closed 24 | // Time Complexity: O(N) 25 | // Space Complexity: O(N) 26 | }; 27 | 28 | -------------------------------------------------------------------------------- /Random_700_Qs/d_Fourth 100/q_a307.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given a 32-bit signed integer, reverse digits of an integer. 3 | 4 | Note: 5 | Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. 6 | 7 | For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. 8 | */ 9 | 10 | var reverse = function(x) { 11 | let arr = x.toString().split(""); 12 | let left = (arr[0] == '-') ? 1 : 0; 13 | let right = arr.length - 1; 14 | while (left < right) { 15 | [arr[left], arr[right]] = [arr[right], arr[left]]; 16 | left++, right--; 17 | } 18 | let res = Number(arr.join("")); 19 | return (res >= -(2**31) && res <= 2**31-1) ? res : 0; 20 | // Time Complexity: O(N) where N = length of input as string 21 | // Space Complexity: O(N) where N = length of input as string 22 | }; -------------------------------------------------------------------------------- /Random_700_Qs/d_Fourth 100/q_a311.js: -------------------------------------------------------------------------------- 1 | /* 2 | Reverse a singly linked list. 3 | */ 4 | 5 | var reverseList = function(head) { 6 | let prev = null, cur = head; 7 | while (cur !== null) { 8 | let next = cur.next; 9 | cur.next = prev; 10 | prev = cur; 11 | cur = next; 12 | } 13 | return prev; 14 | // Time Complexity: O(N) 15 | // Space Complexity: O(1) 16 | }; 17 | 18 | /* 19 | We simply need to make our current node point to its previous node. We do this for every node of the list 20 | and return the new head (which used to be the tail of the original list) 21 | */ -------------------------------------------------------------------------------- /Random_700_Qs/d_Fourth 100/q_a315.js: -------------------------------------------------------------------------------- 1 | /* 2 | You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). 3 | 4 | You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. 5 | */ 6 | 7 | // Get the transpose of given matrix and reverse every row 8 | // Definition of transpose: an operator which flips a matrix over its diagonal 9 | var rotate = function(matrix) { 10 | if (matrix.length == 0 || matrix[0].length == 0) return; 11 | for (let row = 0; row < matrix.length; row++) { 12 | for (let col = row; col < matrix[0].length; col++) { 13 | if (row == col) continue; 14 | [matrix[row][col], matrix[col][row]] = [matrix[col][row], matrix[row][col]]; 15 | } 16 | } 17 | for (let row of matrix) { 18 | row.reverse(); 19 | } 20 | // Time Complexity: O(N^2) 21 | // Space Complexity: O(1) 22 | }; 23 | -------------------------------------------------------------------------------- /Random_700_Qs/d_Fourth 100/q_a319.js: -------------------------------------------------------------------------------- 1 | // Invert a binary tree. 2 | 3 | var invertTree = function(root) { 4 | return invert(root); 5 | function invert(root) { 6 | if (!root) return null; 7 | let invertedLeft = invert(root.left); 8 | let invertedRight = invert(root.right); 9 | root.left = invertedRight; 10 | root.right = invertedLeft; 11 | return root; 12 | // Time Complexity: O(N), we visit every node exactly once 13 | // Space Complexity: O(H), call stack can go as deep as height of tree 14 | } 15 | }; 16 | 17 | // For every root node, we need to switch the left subtree and the right subtree 18 | // We will use a bottom-up approach so as we go up from the bottom to the top, 19 | // we will pass on inverted left subtrees and right subtrees and we repeat this until 20 | // we reach the root of the entire tree. -------------------------------------------------------------------------------- /Random_700_Qs/d_Fourth 100/q_a320.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, you need to compute the length of the diameter of the tree. 3 | 4 | The diameter of a binary tree is the length of the longest path between any two nodes in a tree. 5 | 6 | This path may or may not pass through the root. 7 | 8 | The path is the number of edges in the path, not the number of nodes. 9 | */ 10 | 11 | var diameterOfBinaryTree = function (root) { 12 | if (!root) return null; 13 | let max = 0; 14 | getHeight(root); 15 | return max; 16 | function getHeight(root) { 17 | if (!root) return 0; // height is defined to be the number of nodes in the path in this particular question instead of the number of edges 18 | let leftHeight = getHeight(root.left); 19 | let rightHeight = getHeight(root.right); 20 | max = Math.max(max, leftHeight + rightHeight); 21 | return Math.max(leftHeight, rightHeight) + 1; 22 | } 23 | }; 24 | 25 | // Diameter: Height of left subtree + Height of right subtree 26 | // Height: Max(Height of left subtree, Height of right subtree) + 1 27 | -------------------------------------------------------------------------------- /Random_700_Qs/d_Fourth 100/q_a321.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, find its minimum depth. 3 | 4 | The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. 5 | 6 | Note: A leaf is a node with no children. 7 | */ 8 | 9 | var minDepth = function(root) { 10 | if (!root) return 0; 11 | let queue = [{node: root, depth: 1}]; 12 | while (queue.length > 0) { 13 | let {node, depth} = queue.shift(); 14 | if (!node.left && !node.right) return depth; 15 | if (node.left) { 16 | queue.push({node: node.left, depth: depth + 1}); 17 | } 18 | if (node.right) { 19 | queue.push({node: node.right, depth: depth + 1}); 20 | } 21 | } 22 | // Time Complexity: O(N), in the worst case, we visit all nodes 23 | // Space Complexity: O(N), the bottom level can contain at most N / 2 nodes, and therefore queue can contain N / 2 nodes at most as well 24 | }; 25 | -------------------------------------------------------------------------------- /Random_700_Qs/d_Fourth 100/q_a322.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, determine if it is height-balanced. 3 | 4 | For this problem, a height-balanced binary tree is defined as: 5 | - a binary tree in which the left and right subtrees of every node differ in height by no more than 1. 6 | */ 7 | 8 | var isBalanced = function(root) { 9 | let balanced = true; 10 | isBalanced(root); 11 | return balanced; 12 | function isBalanced(root) { 13 | if (!root) return 0; 14 | if (!balanced) return; 15 | let leftDepth = isBalanced(root.left); 16 | let rightDepth = isBalanced(root.right); 17 | if (Math.abs(leftDepth - rightDepth) > 1) balanced = false; 18 | return Math.max(leftDepth, rightDepth) + 1; 19 | } 20 | // Time Complexity: O(N), we visit every node exactly once 21 | // Space Complexity: O(H), call stack can go as deep as height of tree 22 | }; -------------------------------------------------------------------------------- /Random_700_Qs/d_Fourth 100/q_a324.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). 3 | */ 4 | 5 | var isSymmetric = function(root) { 6 | if (!root) return true; 7 | return checkSymmetry(root.left, root.right); 8 | // Time Complexity: O(N), we visit every node exactly once 9 | // Space Complexity: O(H), call stack can go as deep as height of tree 10 | }; 11 | 12 | function checkSymmetry(root1, root2) { 13 | if (!root1 && !root2) return true; 14 | if (!root1 || !root2) return false; 15 | return root1.val == root2.val && checkSymmetry(root1.left, root2.right) 16 | && checkSymmetry(root1.right, root2.left); 17 | } 18 | -------------------------------------------------------------------------------- /Random_700_Qs/d_Fourth 100/q_a325.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, return all root-to-leaf paths. 3 | 4 | Note: A leaf is a node with no children. 5 | */ 6 | 7 | var binaryTreePaths = function(root) { 8 | let paths = []; 9 | findPath(root, ""); 10 | return paths; 11 | function findPath(root, path) { 12 | if (!root) return; 13 | if (!root.left && !root.right) { 14 | paths.push(path + root.val.toString()); 15 | return; 16 | } 17 | findPath(root.left, path + root.val.toString() + "->"); 18 | findPath(root.right, path + root.val.toString() + "->"); 19 | } 20 | // Time Complexity: O(N), we visit every node exactly once 21 | // Space Complexity: O(H), call stack can go as deep as height of tree 22 | }; -------------------------------------------------------------------------------- /Random_700_Qs/d_Fourth 100/q_a326.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. 3 | 4 | Follow up: If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle. 5 | */ 6 | 7 | var maxSubArray = function(nums) { 8 | let subArrSum = nums[0], maxSum = nums[0]; 9 | for (let i = 1; i < nums.length; i++) { 10 | // choosing between starting a new subarray and adding a number to current subarray 11 | subArrSum = Math.max(subArrSum + nums[i], nums[i]); 12 | maxSum = Math.max(maxSum, subArrSum); 13 | } 14 | return maxSum; 15 | // Time Complexity: O(N) 16 | // Space Complexity: O(1) 17 | }; 18 | -------------------------------------------------------------------------------- /Random_700_Qs/d_Fourth 100/q_a328.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given the root of a binary tree, return its maximum depth. 3 | 4 | A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 5 | */ 6 | 7 | var maxDepth = function(root) { 8 | let max = 0; 9 | dfs(root, 0); 10 | return max; 11 | function dfs(root, depth) { 12 | if (!root) { 13 | max = Math.max(max, depth); 14 | return; 15 | } 16 | dfs(root.left, depth + 1); 17 | dfs(root.right, depth + 1); 18 | } 19 | // Time Complexity: O(N), we visit every node exactly once 20 | // Space Complexity: O(H), call stack can go as deep as height of tree 21 | }; -------------------------------------------------------------------------------- /Random_700_Qs/d_Fourth 100/q_a329.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. 3 | 4 | You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree. 5 | */ 6 | 7 | var mergeTrees = function(t1, t2) { 8 | return merge(t1, t2); 9 | function merge(t1, t2) { 10 | if (t1 && t2) t1.val += t2.val; 11 | else return t1 || t2; 12 | t1.left = merge(t1.left, t2.left); 13 | t1.right = merge(t1.right, t2.right); 14 | return t1; 15 | } 16 | // Time Complexity: O(min(M,N)), 17 | // Space Complexity: O(min(H of t1, H of t2)) 18 | }; -------------------------------------------------------------------------------- /Random_700_Qs/d_Fourth 100/q_a330.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given the root node of a binary search tree, return the sum of values of all nodes with a value in the range [low, high]. 3 | */ 4 | 5 | var rangeSumBST = function(root, low, high) { 6 | let sum = 0; 7 | dfs(root); 8 | return sum; 9 | function dfs(root) { 10 | if (!root) return; 11 | if (root.val >= low && root.val <= high) { 12 | sum += root.val; 13 | } 14 | dfs(root.left); 15 | dfs(root.right); 16 | } 17 | // Time Complexity: O(N), we visit every node exactly once 18 | // Space Complexity: O(H), call stack can go as deep as height of tree 19 | }; -------------------------------------------------------------------------------- /Random_700_Qs/d_Fourth 100/q_a331.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root). 3 | 4 | For example: 5 | Given binary tree [3,9,20,null,null,15,7], 6 | */ 7 | 8 | var levelOrderBottom = function(root) { 9 | if (!root) return []; 10 | let traversal = [], queue = [root]; 11 | while (queue.length > 0) { 12 | let len = queue.length; 13 | let level = []; 14 | for (let i = 0; i < len; i++) { 15 | let node = queue.shift(); 16 | level.push(node.val); 17 | if (node.left) queue.push(node.left); 18 | if (node.right) queue.push(node.right); 19 | } 20 | traversal.push(level); 21 | } 22 | return traversal.reverse(); 23 | // Time Complexity: O(N), we visit every node exactly once 24 | // Space Complexity: O(N), the bottom level can contain at most N / 2 nodes and therefore 25 | // queue can contain at most N / 2 nodes as well 26 | }; -------------------------------------------------------------------------------- /Random_700_Qs/d_Fourth 100/q_a332.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 3 | 4 | For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. 5 | */ 6 | 7 | var sortedArrayToBST = function(nums) { 8 | return createBST(nums); 9 | function createBST(nums) { 10 | if (nums.length == 0) return null; 11 | let mid = Math.floor(nums.length / 2); 12 | let root = new TreeNode(nums[mid]); 13 | root.left = createBST(nums.slice(0,mid)); 14 | root.right = createBST(nums.slice(mid+1)); 15 | return root; 16 | } 17 | // Time Complexity: O(N), we visit every element exactly once 18 | // Space Complexity: O(N), call stack can go as deep as number of elements 19 | }; -------------------------------------------------------------------------------- /Random_700_Qs/d_Fourth 100/q_a333.js: -------------------------------------------------------------------------------- 1 | /* 2 | Count the number of prime numbers less than a non-negative number, n. 3 | */ 4 | 5 | var countPrimes = function (n) { 6 | let primes = new Array(n).fill(true); 7 | primes[0] = false, primes[1] = false; 8 | for (let i = 2; i < n; i++) { 9 | for (let j = i**2; j < n; j += i) { 10 | primes[j] = false; 11 | } 12 | } 13 | return primes.filter(bool => bool == true).length; 14 | // Time Complexity: O(nlog(n)) 15 | // Space Complexity: O(n) 16 | }; 17 | -------------------------------------------------------------------------------- /Random_700_Qs/d_Fourth 100/q_a334.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given a non-empty array of integers nums, every element appears twice except for one. Find that single one. 3 | 4 | Follow up: Could you implement a solution with a linear runtime complexity and without using extra memory? 5 | */ 6 | 7 | var singleNumber = function(nums) { 8 | let m = new Map(); 9 | for (let i = 0; i < nums.length; i++) { 10 | m.set(nums[i], m.get(nums[i]) + 1 || 1); 11 | } 12 | for (let [num, freq] of m) { 13 | if (freq == 1) return num; 14 | } 15 | return -1; 16 | // Time Complexity: O(N) 17 | // Space Complexity: O(N) 18 | }; 19 | 20 | var singleNumber = function(nums) { 21 | return nums.reduce((acc, cur) => acc ^ cur); 22 | // Time Complexity: O(N) 23 | // Space Complexity: O(1) 24 | // a XOR a = 0 25 | // 0 XOR b = b 26 | // So, if we take of XOR of every number in the input array, we will be left with the single number. 27 | }; -------------------------------------------------------------------------------- /Random_700_Qs/d_Fourth 100/q_a335.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. 3 | 4 | You may assume that the array is non-empty and the majority element always exist in the array. 5 | */ 6 | 7 | var majorityElement = function(nums) { 8 | let len = Math.floor(nums.length / 2); 9 | let m = new Map(); 10 | for (let i = 0; i < nums.length; i++) { 11 | m.set(nums[i], m.get(nums[i]) + 1 || 1); 12 | } 13 | for (let [num, freq] of m) { 14 | if (freq > len) return num; 15 | } 16 | return -1; 17 | // Time Complexity: O(N) 18 | // Space Complexity: O(N) 19 | }; -------------------------------------------------------------------------------- /Random_700_Qs/d_Fourth 100/q_a336.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. 3 | 4 | Note: 5 | - You must do this in-place without making a copy of the array. 6 | - Minimize the total number of operations. 7 | */ 8 | 9 | var moveZeroes = function(nums) { 10 | let idx = 0; 11 | for (let i = 0; i < nums.length; i++) { 12 | if (nums[i] !== 0) { 13 | [nums[idx], nums[i]] = [nums[i], nums[idx]]; 14 | idx++; 15 | } 16 | } 17 | // Scan through the array and every time we encounter a non-zero, we swap it with the number 18 | // at position "idx". "idx" represents the index the next non-zero should come in. 19 | // Because we've moved all non-zeros to the front, we have all zeros at the end now. 20 | // Time Complexity: O(N) 21 | // Space Complexity: O(1) 22 | }; -------------------------------------------------------------------------------- /Random_700_Qs/d_Fourth 100/q_a338.js: -------------------------------------------------------------------------------- 1 | /* 2 | You are climbing a staircase. It takes n steps to reach the top. 3 | 4 | Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 5 | */ 6 | 7 | var climbStairs = function(n) { 8 | // dp[i] represents # of ways to reach i-th floor 9 | let dp = new Array(n+1); // size is n+1 because array is zero-indexed 10 | dp[0] = 1, dp[1] = 1; 11 | for (let i = 2; i <= n; i++) { 12 | dp[i] = dp[i-1] + dp[i-2]; 13 | } 14 | return dp[n]; 15 | // Time Complexity: O(N) 16 | // Space Complexity: O(N) 17 | }; 18 | 19 | // # of ways to reach i-th floor = # of ways to reach i-1 floor + # of ways to reach i-2 floor 20 | // base cases: 21 | // 1. # of ways to reach 0-th floor is 1 22 | // 2. # of ways to reach 1-st floor is 1 23 | 24 | -------------------------------------------------------------------------------- /Random_700_Qs/d_Fourth 100/q_a340.js: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program to find the node at which the intersection of two singly linked lists begins. 3 | */ 4 | 5 | var getIntersectionNode = function(headA, headB) { 6 | let lenA = getLength(headA), lenB = getLength(headB); 7 | let curA = headA, curB = headB; 8 | for (let i = 0; i < Math.abs(lenA - lenB); i++) { 9 | if (lenA > lenB) { 10 | curA = curA.next; 11 | } else { 12 | curB = curB.next; 13 | } 14 | } 15 | while (curA !== curB && curA && curB) { 16 | curA = curA.next; 17 | curB = curB.next; 18 | } 19 | return curA; 20 | // Time Complexity: O(m + n) 21 | // Space Complexity: O(1) 22 | }; 23 | 24 | function getLength(head) { 25 | let len = 0; 26 | while (head !== null) { 27 | head = head.next; 28 | len++; 29 | } 30 | return len; 31 | } -------------------------------------------------------------------------------- /Random_700_Qs/d_Fourth 100/q_a342.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive. 3 | 4 | There is only one duplicate number in nums, return this duplicate number. 5 | */ 6 | 7 | var findDuplicate = function(nums) { 8 | for (let i = 0; i < nums.length; i++) { 9 | let idx = Math.abs(nums[i]); 10 | if (nums[idx] > 0) nums[idx] *= -1; 11 | else return idx; 12 | // Time Complexity: O(N) 13 | // Space Complexity: O(1) 14 | } 15 | // For every integer we encounter, we will negate nums[integer]. 16 | // If nums[integer] is already negative, that means integer is the duplicate number. 17 | }; -------------------------------------------------------------------------------- /Random_700_Qs/d_Fourth 100/q_a343.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array nums of distinct integers, return all the possible permutations. 3 | 4 | You can return the answer in any order. 5 | */ 6 | 7 | var permute = function(nums) { 8 | let res = []; 9 | let visited = new Array(nums.length).fill(false); 10 | dfs([], 0, visited); 11 | return res; 12 | 13 | function dfs(cur, depth, visited) { 14 | if (depth == nums.length) { 15 | res.push(cur.slice()); 16 | return; 17 | } 18 | for (let i = 0; i < nums.length; i++) { 19 | if (visited[i] == false) { 20 | visited[i] = true; 21 | cur.push(nums[i]); 22 | 23 | dfs(cur, depth + 1, visited); 24 | 25 | cur.pop(); 26 | visited[i] = false; 27 | } 28 | } 29 | } 30 | 31 | // Time Complexity: O(N!), number of possible permutations is N! / (N-r)! and therefore N! in this case 32 | // Space Complexity: O(N!) 33 | }; -------------------------------------------------------------------------------- /Random_700_Qs/d_Fourth 100/q_a344.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer array nums, return all possible subsets (the power set). 3 | 4 | The solution set must not contain duplicate subsets. 5 | */ 6 | 7 | var subsets = function(nums) { 8 | let res = []; 9 | combine([], 0); 10 | return res; 11 | 12 | function combine(cur, start) { 13 | res.push(cur.slice()); 14 | for (let i = start; i < nums.length; i++) { 15 | cur.push(nums[i]); 16 | 17 | combine(cur, i + 1); 18 | 19 | cur.pop(); 20 | } 21 | } 22 | // Time Complexity: O(n * 2^n) 23 | // Space Complexity: O(n * 2^n) 24 | }; -------------------------------------------------------------------------------- /Random_700_Qs/d_Fourth 100/q_a346.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string, your task is to count how many palindromic substrings in this string. 3 | 4 | The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters. 5 | */ 6 | 7 | -------------------------------------------------------------------------------- /Random_700_Qs/d_Fourth 100/q_a347.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. 3 | */ 4 | 5 | var generateParenthesis = function(n) { 6 | let res = []; 7 | generate(n, 0, ""); 8 | return res; 9 | 10 | function generate(open, close, str) { 11 | if (open == 0 && close == 0) { 12 | res.push(str); 13 | return; 14 | } 15 | if (open > 0) { 16 | generate(open - 1, close + 1, str + "("); 17 | } 18 | if (close > 0) { 19 | generate(open, close - 1, str + ")"); 20 | } 21 | } 22 | // Space Complexity: O(2N) = O(N), call stack can go as deep as 2N 23 | }; 24 | 25 | -------------------------------------------------------------------------------- /Random_700_Qs/d_Fourth 100/q_a348.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given the root of a binary tree, return the inorder traversal of its nodes' values. 3 | */ 4 | 5 | var inorderTraversal = function(root) { 6 | let values = []; 7 | inorder(root); 8 | return values; 9 | 10 | function inorder(root) { 11 | if (!root) return; 12 | inorder(root.left); 13 | values.push(root.val); 14 | inorder(root.right); 15 | }; 16 | // Time Complexity: O(N), we visit every node exactly once 17 | // Space Complexity: O(H), call stack can go as deep as height of tree 18 | }; -------------------------------------------------------------------------------- /Random_700_Qs/d_Fourth 100/q_a349.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), 3 | 4 | find the minimum number of conference rooms required. 5 | */ -------------------------------------------------------------------------------- /Random_700_Qs/d_Fourth 100/q_a352.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, flatten it to a linked list in-place. 3 | */ 4 | 5 | var flatten = function(root) { 6 | flattenHelper(root); 7 | return root; 8 | 9 | function flattenHelper(root) { 10 | if (!root) return null; 11 | let leftTail = flattenHelper(root.left); 12 | let rightTail = flattenHelper(root.right); 13 | if (!leftTail && !rightTail) return root; 14 | if (leftTail) { 15 | leftTail.right = root.right; 16 | root.right = root.left; 17 | root.left = null; 18 | }; 19 | return rightTail ? rightTail : leftTail; 20 | } 21 | // Time Complexity: O(N), we visit every node exactly once 22 | // Space Complexity: O(N), call stack can go as deep as number of nodes 23 | }; 24 | 25 | -------------------------------------------------------------------------------- /Random_700_Qs/d_Fourth 100/q_a353.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). 3 | 4 | n vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0). 5 | 6 | Find two lines, which, together with the x-axis forms a container, such that the container contains the most water. 7 | 8 | Notice that you may not slant the container. 9 | */ 10 | 11 | var maxArea = function(height) { 12 | let left = 0, right = height.length - 1; 13 | let maxArea = 0; 14 | while (left < right) { 15 | let area = Math.min(height[left], height[right]) * (right - left); 16 | maxArea = Math.max(maxArea, area); 17 | if (height[left] < height[right]) left++; 18 | else right--; 19 | } 20 | return maxArea; 21 | // Time Complexity: O(N) 22 | // Space Complexity: O(1) 23 | }; -------------------------------------------------------------------------------- /Random_700_Qs/d_Fourth 100/q_a357.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n? 3 | */ -------------------------------------------------------------------------------- /Random_700_Qs/d_Fourth 100/q_a359.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given n non-negative integers representing an elevation map where the width of each bar is 1, 3 | 4 | compute how much water it can trap after raining. 5 | */ -------------------------------------------------------------------------------- /Random_700_Qs/d_Fourth 100/q_a363.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. 3 | 4 | Note: 5 | - The number of elements initialized in nums1 and nums2 are m and n respectively. 6 | - You may assume that nums1 has enough space (size that is equal to m + n) to hold additional elements from nums2. 7 | */ 8 | 9 | var merge = function(nums1, m, nums2, n) { 10 | let idx1 = m - 1, idx2 = n - 1, insertIdx = m + n - 1; 11 | while (idx2 >= 0) { // nums1 is already sorted 12 | if (nums1[idx1] > nums2[idx2]) { 13 | nums1[insertIdx] = nums1[idx1--]; 14 | } else { 15 | nums1[insertIdx] = nums2[idx2--]; 16 | } 17 | insertIdx--; 18 | } 19 | // Time Complexity: O(M + N) 20 | // Space Complexity: O(1) 21 | }; 22 | -------------------------------------------------------------------------------- /Random_700_Qs/d_Fourth 100/q_a364.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given two binary strings a and b, return their sum as a binary string. 3 | */ 4 | 5 | var addBinary = function(a, b) { 6 | let binaryA = BigInt(`0b${a}`); 7 | let binaryB = BigInt(`0b${b}`); 8 | let sum = binaryA + binaryB; 9 | return sum.toString(2); 10 | }; 11 | 12 | var addBinary = function(a, b) { 13 | let idxA = a.length - 1; 14 | let idxB = b.length - 1; 15 | let carry = 0; 16 | let res = ""; 17 | while (idxA >= 0 || idxB >= 0) { 18 | let digA = idxA >= 0 ? Number(a[idxA--]) : 0; 19 | let digB = idxB >= 0 ? Number(b[idxB--]) : 0; 20 | let sum = digA + digB + carry; 21 | res = (sum % 2).toString() + res; 22 | carry = Math.floor(sum / 2); 23 | } 24 | if (carry) { 25 | res = carry + res; 26 | } 27 | return res; 28 | // Time Complexity: max(m, n), m = length of a, n = length of b 29 | // Space Complexity: max(m, n) 30 | }; -------------------------------------------------------------------------------- /Random_700_Qs/d_Fourth 100/q_a367.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. 3 | 4 | Note: For the purpose of this problem, we define empty string as valid palindrome. 5 | */ 6 | 7 | var isPalindrome = function(s) { 8 | s = s.toLowerCase().replace(/[^a-z0-9]/ig, ''); 9 | let l = 0, r = s.length - 1; 10 | while (l < r) { 11 | if (s[l] !== s[r]) return false; 12 | l++, r--; 13 | } 14 | return true; 15 | // Time Complexity: O(N) 16 | // Space Complexity: O(N) 17 | }; -------------------------------------------------------------------------------- /Random_700_Qs/d_Fourth 100/q_a368.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome. 3 | */ 4 | 5 | var validPalindrome = function(s) { 6 | return isPalindrome(0, s.length-1, 0); 7 | 8 | function isPalindrome(start, end, deleted) { 9 | while (start < end) { 10 | if (s[start] !== s[end]) { 11 | if (deleted == 0) { 12 | return isPalindrome(start + 1, end, deleted + 1) || 13 | isPalindrome(start, end - 1, deleted + 1); 14 | } 15 | else return false; 16 | } 17 | start++, end--; 18 | } 19 | return true; 20 | } 21 | // Time Complexity: O(N), we visit every letter once 22 | // Space Complexity: O(1), call stack can go as deep as 1 23 | }; 24 | 25 | -------------------------------------------------------------------------------- /Random_700_Qs/d_Fourth 100/q_a373.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given two lists of closed intervals, each list of intervals is pairwise disjoint and in sorted order. 3 | 4 | Return the intersection of these two interval lists. 5 | 6 | (Formally, a closed interval [a, b] (with a <= b) denotes the set of real numbers x with a <= x <= b. 7 | 8 | The intersection of two closed intervals is a set of real numbers that is either empty, or can be represented as a closed interval. 9 | 10 | For example, the intersection of [1, 3] and [2, 4] is [2, 3].) 11 | */ -------------------------------------------------------------------------------- /Random_700_Qs/d_Fourth 100/q_a374.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given two sparse vectors, compute their dot product. 3 | 4 | Implement class SparseVector: 5 | - SparseVector(nums) Initializes the object with the vector nums 6 | - dotProduct(vec) Compute the dot product between the instance of SparseVector and vec 7 | 8 | A sparse vector is a vector that has mostly zero values, you should store the sparse vector efficiently and compute the dot product between two SparseVector. 9 | 10 | Follow up: What if only one of the vectors is sparse? 11 | */ -------------------------------------------------------------------------------- /Random_700_Qs/d_Fourth 100/q_a375.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom. 3 | */ 4 | 5 | // Modified Pre-order: we will visit right node, root node and left node. 6 | var rightSideView = function(root) { 7 | let values = []; 8 | traverse(root, 0); 9 | return values; 10 | 11 | function traverse(root, depth) { 12 | if (!root) return; 13 | traverse(root.right, depth + 1); 14 | if (values[depth] == undefined) { 15 | values[depth] = root.val; 16 | } 17 | traverse(root.left, depth + 1); 18 | } 19 | // Time Complexity: O(N), we visit every node exactly once 20 | // Space Complexity: O(H), call stack can go as deep as height of tree 21 | }; -------------------------------------------------------------------------------- /Random_700_Qs/d_Fourth 100/q_a376.js: -------------------------------------------------------------------------------- 1 | /* 2 | The Hamming distance between two integers is the number of positions at which the corresponding bits are different. 3 | 4 | Given two integers x and y, calculate the Hamming distance. 5 | */ 6 | 7 | var hammingDistance = function(x, y) { 8 | return (x ^ y).toString(2).replace(/0/g,"").length; 9 | }; 10 | 11 | // We want to find two bits to be different so we need XOR 12 | // 000 XOR 111 => 111 -------------------------------------------------------------------------------- /Random_700_Qs/d_Fourth 100/q_a381.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array, reverse the order of its elements. 3 | 4 | For example, [3,5,2,5,2,3,9] -> [9,3,2,5,2,5,3] 5 | 6 | Qs. 7 | 1. Should I reverse the order in-place? 8 | - Yes. 9 | */ 10 | 11 | var reverseArray = function (arr) { 12 | if (arr == null) return null; 13 | let start = 0, 14 | end = arr.length - 1; 15 | while (start < end) { 16 | [arr[start], arr[end]] = [arr[end], arr[start]]; 17 | start++, end--; 18 | } 19 | return arr; 20 | }; 21 | 22 | /* 23 | Time Complexity: O(N) 24 | Space Complexity: O(1) 25 | 26 | null => null 27 | [] => [] 28 | [1] => [1] 29 | */ 30 | 31 | console.log(reverseArray(null)); 32 | console.log(reverseArray([])); 33 | console.log(reverseArray([1])); 34 | console.log(reverseArray([3, 5, 2, 5, 2, 3, 9])); 35 | console.log(reverseArray([1, 2, 3])); 36 | console.log(reverseArray([9, 3, 2, 1])); 37 | -------------------------------------------------------------------------------- /Random_700_Qs/d_Fourth 100/q_a387.js: -------------------------------------------------------------------------------- 1 | /* 2 | Print a 2D array in Diagonal ZigZag order. 3 | 4 | ex) 5 | 1 2 3 4 6 | 5 6 7 8 7 | 9 0 1 2 8 | -> 9 | 1 2 5 9 6 3 4 7 0 1 8 2 10 | 11 | Qs 12 | 1. Can the matrix be a rectangle? 13 | - Yes. 14 | 2. What if the matrix is null or empty? 15 | - Print nothing. 16 | */ 17 | 18 | /* 19 | Test cases: 20 | null -> 21 | [] -> 22 | matrix -> array 23 | [1] -> [1] 24 | 25 | 1. 26 | 2. 27 | 3. 28 | */ 29 | -------------------------------------------------------------------------------- /Random_700_Qs/d_Fourth 100/q_a390.js: -------------------------------------------------------------------------------- 1 | /* 2 | You are given stock prices and the corresponding day of each stock price. 3 | 4 | ex) (32, 1), (45, 1), (37, 2), (42, 3) ... 5 | Here, 32 is the price and 1 is the day of the price. 6 | Say you are given these prices as an input stream. You should provide a function for the user to input a stock price and day. 7 | Your system should be able to tell the maximum stock price in the last 3 days. 8 | */ -------------------------------------------------------------------------------- /Random_700_Qs/d_Fourth 100/q_a398.js: -------------------------------------------------------------------------------- 1 | /* 2 | Check if a string is a rotation of another. 3 | 4 | ex) 5 | "canada", "dacana" -> true 6 | "canada", "canada" -> true 7 | "canada", "canary" -> false 8 | */ 9 | 10 | const findRotation = (str1, str2) => { 11 | if (str1 === null || str2 === null || str1.length !== str2.length) { 12 | return false; 13 | } 14 | const concatenatedStr1 = str1.concat(str1); 15 | return concatenatedStr1.includes(str2); 16 | // Time Complexity: O(n) 17 | // Space Complexity: O(2n) = O(n) 18 | }; 19 | 20 | console.log(findRotation("canada", "dacana")); 21 | console.log(findRotation("canada", "canada")); 22 | console.log(findRotation("canada", "canary")); 23 | -------------------------------------------------------------------------------- /Random_700_Qs/e_Fifth_100/q_a408.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of numbers, replace each even number with two of the same number. e.g, [1,2,5,6,8, , , ,] -> [1,2,2,5,6,6,8,8]. 3 | 4 | Assume that the array has the exact amount of space to accommodate the result. 5 | */ 6 | 7 | const doubleEvens = (arr) => { 8 | let i = getLastIndex(arr); 9 | let end = arr.length - 1; 10 | while (i >= 0) { 11 | if (arr[i] % 2 === 0) { 12 | arr[end] = arr[i]; 13 | end--; 14 | } 15 | arr[end] = arr[i]; 16 | end--; 17 | i--; 18 | } 19 | return arr; 20 | // T.C: O(N) 21 | // S.C: O(1) 22 | }; 23 | 24 | const getLastIndex = (arr) => { 25 | let i = 0; 26 | while (arr[i + 1] !== -1) { 27 | i++; 28 | } 29 | return i; 30 | }; 31 | 32 | let testArr = new Array(8); 33 | testArr[0] = 1; 34 | testArr[1] = 2; 35 | testArr[2] = 5; 36 | testArr[3] = 6; 37 | testArr[4] = 8; 38 | testArr[5] = -1; 39 | testArr[6] = -1; 40 | testArr[7] = -1; 41 | console.log(doubleEvens(testArr)); 42 | -------------------------------------------------------------------------------- /Random_700_Qs/e_Fifth_100/q_a409.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hbjORbj/interview_prep_javascript/06c8339bc6cac4b87f0da447d08cc4257823cea8/Random_700_Qs/e_Fifth_100/q_a409.js -------------------------------------------------------------------------------- /Random_700_Qs/e_Fifth_100/q_a417.js: -------------------------------------------------------------------------------- 1 | /* 2 | Merge Sorted Array 3 | 4 | Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. 5 | 6 | The number of elements initialized in nums1 and nums2 are m and n respectively. 7 | 8 | You may assume that nums1 has a size equal to m + n such that it has enough space to hold additional elements from nums2. 9 | */ 10 | 11 | var merge = function (nums1, m, nums2, n) { 12 | let i = m - 1, 13 | j = n - 1; 14 | let end = m + n - 1; 15 | while (i >= 0 && j >= 0) { 16 | if (nums1[i] < nums2[j]) { 17 | nums1[end--] = nums2[j--]; 18 | } else { 19 | nums1[end--] = nums1[i--]; 20 | } 21 | } 22 | while (j >= 0) { 23 | nums1[end--] = nums2[j--]; 24 | } 25 | // T.C: O(M + N) 26 | // S.C: O(1) 27 | }; 28 | -------------------------------------------------------------------------------- /Random_700_Qs/e_Fifth_100/q_a418.js: -------------------------------------------------------------------------------- 1 | /* 2 | Merge Two Sorted Lists 3 | 4 | Merge two sorted linked lists and return it as a sorted list. 5 | 6 | The list should be made by splicing together the nodes of the first two lists. 7 | */ 8 | 9 | var mergeTwoLists = function (l1, l2) { 10 | let cur1 = l1, 11 | cur2 = l2; 12 | let newHead = new ListNode(); 13 | let newCur = newHead; 14 | while (cur1 !== null && cur2 !== null) { 15 | if (cur1.val < cur2.val) { 16 | newCur.next = cur1; 17 | newCur = newCur.next; 18 | cur1 = cur1.next; 19 | } else { 20 | newCur.next = cur2; 21 | newCur = newCur.next; 22 | cur2 = cur2.next; 23 | } 24 | } 25 | while (cur1 !== null) { 26 | newCur.next = cur1; 27 | newCur = newCur.next; 28 | cur1 = cur1.next; 29 | } 30 | while (cur2 !== null) { 31 | newCur.next = cur2; 32 | newCur = newCur.next; 33 | cur2 = cur2.next; 34 | } 35 | return newHead.next; 36 | // T.C: O(M + N) 37 | // S.C: O(1) 38 | }; 39 | -------------------------------------------------------------------------------- /Random_700_Qs/e_Fifth_100/q_a424.js: -------------------------------------------------------------------------------- 1 | /* 2 | Combinations 3 | 4 | Given two integers n and k, return all possible combinations of k numbers out of the range [1, n]. 5 | 6 | You may return the answer in any order. 7 | */ 8 | 9 | var combine = function (n, k) { 10 | let res = []; 11 | dfsTraversal(1, [], n, k, res); 12 | return res; 13 | }; 14 | 15 | const dfsTraversal = (start, curPath, n, k, res) => { 16 | if (curPath.length === k) { 17 | res.push(curPath.slice()); 18 | return; 19 | } 20 | for (let i = start; i <= n; i++) { 21 | // i doesn't start from zero because if we don't regard an element already visited again in combinations; 22 | // in contrast to permutations, we consider the same set of elements with different ordering the same in combinations 23 | curPath.push(i); 24 | 25 | dfsTraversal(i + 1, curPath, n, k, res); 26 | 27 | curPath.pop(); 28 | } 29 | }; 30 | // T.C: O(C(n,k)) 31 | // S.C: O(C(n,k)) 32 | -------------------------------------------------------------------------------- /Random_700_Qs/e_Fifth_100/q_a425.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given a pattern and a string s, find if s follows the same pattern. 3 | 4 | Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s. 5 | */ 6 | 7 | var wordPattern = function (pattern, s) { 8 | let words = s.split(" "); 9 | let m = new Map(); 10 | let used = new Set(); 11 | if (pattern.length !== words.length) { 12 | return false; 13 | } 14 | for (let i = 0; i < pattern.length; i++) { 15 | if (m.has(pattern[i])) { 16 | if (m.get(pattern[i]) !== words[i]) { 17 | return false; 18 | } 19 | } else { 20 | if (used.has(words[i])) { 21 | return false; 22 | } 23 | m.set(pattern[i], words[i]); 24 | used.add(words[i]); 25 | } 26 | } 27 | return true; 28 | // T.C: O(N), N = # of characters in pattern 29 | // S.C: O(N) 30 | }; 31 | -------------------------------------------------------------------------------- /Random_700_Qs/e_Fifth_100/q_a435.js: -------------------------------------------------------------------------------- 1 | /* 2 | Rotate Array 3 | 4 | Given an array, rotate the array to the right by k steps, where k is non-negative. 5 | */ 6 | 7 | var rotate = function (nums, k) { 8 | if (nums === null || nums.length === 0) { 9 | return; 10 | } 11 | k = k % nums.length; 12 | if (k === 0) { 13 | return; 14 | } 15 | nums.reverse(); 16 | reverse(nums, 0, k - 1); 17 | reverse(nums, k, nums.length - 1); 18 | // T.C: O(N) 19 | // S.C: O(1) 20 | }; 21 | 22 | const reverse = (arr, start, end) => { 23 | while (start < end) { 24 | let temp = arr[start]; 25 | arr[start] = arr[end]; 26 | arr[end] = temp; 27 | start++, end--; 28 | } 29 | }; 30 | 31 | /* 32 | Solution: 33 | 1. Reverse the entire array. 34 | 2. Reverse the first k elements. 35 | 3. Reverse the rest. 36 | */ 37 | -------------------------------------------------------------------------------- /Random_700_Qs/e_Fifth_100/q_a438.js: -------------------------------------------------------------------------------- 1 | /* 2 | Rotate String 3 | 4 | We are given two strings, A and B. 5 | 6 | A shift on A consists of taking string A and moving the leftmost character to the rightmost position. 7 | 8 | For example, if A = 'abcde', then it will be 'bcdea' after one shift on A. 9 | 10 | Return True if and only if A can become B after some number of shifts on A. 11 | */ 12 | 13 | var rotateString = function (A, B) { 14 | if (A === null || B === null) { 15 | return false; 16 | } 17 | if (A.length !== B.length) { 18 | return false; 19 | } 20 | for (let i = 0; i <= A.length; i++) { 21 | let prefix = A.substring(0, i); 22 | let suffix = A.substring(i); 23 | let str = suffix + prefix; 24 | if (str === B) { 25 | return true; 26 | } 27 | } 28 | return false; 29 | // T.C: O(N) 30 | // S.C: O(N) 31 | }; 32 | // Use every character of A as pivot and take prefix and suffix with respect to the pivot 33 | // suffix + prefix is the result of shifting on A so compare this to B 34 | -------------------------------------------------------------------------------- /Random_700_Qs/e_Fifth_100/q_a442.js: -------------------------------------------------------------------------------- 1 | /* 2 | Valid Palindrome II 3 | 4 | Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome. 5 | */ 6 | 7 | var validPalindrome = function (s) { 8 | let low = 0, 9 | high = s.length - 1; 10 | while (low < high) { 11 | if (s[low] !== s[high]) { 12 | // 1st case: delete char at low 13 | // 2nd case: delete char at high 14 | return isSymmetric(s, low + 1, high) || isSymmetric(s, low, high - 1); 15 | } 16 | low++, high--; 17 | } 18 | return true; 19 | // T.C: O(N) 20 | // S.C: O(1) 21 | }; 22 | 23 | const isSymmetric = (s, low, high) => { 24 | while (low < high) { 25 | if (s[low] !== s[high]) { 26 | return false; 27 | } 28 | low++, high--; 29 | } 30 | return true; 31 | }; 32 | -------------------------------------------------------------------------------- /Random_700_Qs/e_Fifth_100/q_a445.js: -------------------------------------------------------------------------------- 1 | /* 2 | K Closest Points to Origin 3 | 4 | Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0). 5 | 6 | The distance between two points on the X-Y plane is the Euclidean distance (i.e., √(x1 - x2)2 + (y1 - y2)2). 7 | 8 | You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in). 9 | */ 10 | 11 | var kClosest = function (points, k) { 12 | let sorted = points.map((p, idx) => { 13 | let dist = (p[0] ** 2 + p[1] ** 2) ** 0.5; 14 | return [dist, idx]; 15 | }); 16 | sorted.sort((a, b) => a[0] - b[0]); 17 | let res = []; 18 | for (let i = 0; i < k; i++) { 19 | let idx = sorted[i][1]; 20 | res.push(points[idx]); 21 | } 22 | return res; 23 | // T.C: O(nlog(n)) 24 | // S.C: O(n) 25 | }; 26 | -------------------------------------------------------------------------------- /Random_700_Qs/e_Fifth_100/q_a446.js: -------------------------------------------------------------------------------- 1 | /* 2 | Subarray Sum Equals K 3 | 4 | Given an array of integers nums and an integer k, return the total number of continuous subarrays whose sum equals to k. 5 | */ 6 | 7 | var subarraySum = function (nums, k) { 8 | let count = 0; 9 | let cumSum = 0; 10 | let m = new Map(); 11 | for (let i = 0; i < nums.length; i++) { 12 | cumSum += nums[i]; 13 | if (cumSum === k) { 14 | count += 1; 15 | } 16 | if (m.has(cumSum - k)) { 17 | count += m.get(cumSum - k); 18 | } 19 | m.set(cumSum, m.get(cumSum) + 1 || 1); 20 | } 21 | return count; 22 | // T.C: O(N) 23 | // S.C: O(N) 24 | }; 25 | 26 | /* 27 | We keep track of cumulative sum at each index 28 | 29 | if cumulative sum at nums[j] - cumulative sum at nums[i] = k 30 | the subarray nums[i+1...j] has a sum of k 31 | Therefore, at every index, we check if such index i exists and if it exists how many such indices there are. 32 | Another edge case to consider is that the subarray nums[0...i] can have a sum of k 33 | */ 34 | -------------------------------------------------------------------------------- /Random_700_Qs/e_Fifth_100/q_a447.js: -------------------------------------------------------------------------------- 1 | /* 2 | Binary Tree Right Side View 3 | 4 | Given the root of a binary tree, imagine yourself standing on the right side of it, 5 | 6 | return the values of the nodes you can see ordered from top to bottom. 7 | */ 8 | 9 | var rightSideView = function (root) { 10 | let res = []; 11 | let rightLeafDepth = 0; 12 | dfsTraversal(root, res, 0); 13 | return res; 14 | }; 15 | 16 | const dfsTraversal = (root, res, depth) => { 17 | if (!root) { 18 | return; 19 | } 20 | if (depth > res.length - 1) { 21 | res.push(root.val); 22 | } 23 | dfsTraversal(root.right, res, depth + 1); 24 | dfsTraversal(root.left, res, depth + 1); 25 | }; 26 | 27 | // perform preorder traversal that visits root, right, left instead of root, left, right 28 | // keep track of the depth of the right-most leaf 29 | // if the first node with greater depth is found during traversing the rest of the tree, 30 | // record the node, increment depth and continue 31 | -------------------------------------------------------------------------------- /Random_700_Qs/e_Fifth_100/q_a448.js: -------------------------------------------------------------------------------- 1 | /* 2 | Range Sum of BST 3 | 4 | Given the root node of a binary search tree, 5 | 6 | return the sum of values of all nodes with a value in the range [low, high]. 7 | 8 | Qs: 9 | 1. Is the range inclusive? 10 | - Yes. 11 | */ 12 | 13 | var rangeSumBST = function (root, low, high) { 14 | let sum = 0; 15 | dfsTraversal(root); 16 | return sum; 17 | function dfsTraversal(root) { 18 | if (!root) { 19 | return; 20 | } 21 | if (root.val >= low && root.val <= high) { 22 | sum += root.val; 23 | } 24 | dfsTraversal(root.left); 25 | dfsTraversal(root.right); 26 | } 27 | // T.C: O(N), visit all nodes 28 | // S.C: O(H), call stack can go as deep as the height of tree 29 | }; 30 | 31 | /* 32 | Solution: 33 | 1. Perform a DFS traversal to visit all nodes. 34 | 2. At each node, check if its value falls within the range and if so add it to 35 | a global variable `sum`. 36 | */ 37 | -------------------------------------------------------------------------------- /Random_700_Qs/e_Fifth_100/q_a455.js: -------------------------------------------------------------------------------- 1 | /* 2 | Symmetric Tree 3 | 4 | Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center). 5 | */ 6 | 7 | var isSymmetric = function (root) { 8 | if (!root) { 9 | return true; 10 | } 11 | return areTwoTreesSymmetric(root.left, root.right); 12 | // T.C: O(N) // visit all nodes in the worst case 13 | // S.C: O(H) // call stack can go as deep as the height of tree 14 | }; 15 | 16 | const areTwoTreesSymmetric = (root1, root2) => { 17 | if (!root1 && !root2) { 18 | // Reached leaf nodes 19 | return true; 20 | } 21 | if (!root1 || !root2) { 22 | // asymmetric 23 | return false; 24 | } 25 | return ( 26 | root1.val === root2.val && 27 | areTwoTreesSymmetric(root1.left, root2.right) && 28 | areTwoTreesSymmetric(root1.right, root2.left) 29 | ); 30 | }; 31 | -------------------------------------------------------------------------------- /Random_700_Qs/e_Fifth_100/q_a456.js: -------------------------------------------------------------------------------- 1 | /* 2 | Search Insert Position 3 | 4 | Given a sorted array of distinct integers and a target value, return the index if the target is found. 5 | 6 | If not, return the index where it would be if it were inserted in order. 7 | */ 8 | 9 | var searchInsert = function (nums, target) { 10 | if (nums === null || nums.length === 0) { 11 | return -1; 12 | } 13 | let low = 0, 14 | high = nums.length - 1; 15 | let mid = 0; 16 | while (low <= high) { 17 | mid = low + Math.floor((high - low) / 2); 18 | if (nums[mid] > target) { 19 | high = mid - 1; 20 | } else if (nums[mid] < target) { 21 | low = mid + 1; 22 | } else { 23 | return mid; 24 | } 25 | } 26 | return nums[mid] < target ? mid + 1 : mid; 27 | // if target is not found, 28 | // mid is the index of a number nearest to target 29 | // if target > nums[mid] we insert in the next index 30 | // if target < nums[mid] we insert in the current index 31 | // T.C: O(log(N)) 32 | // S.C: O(1) 33 | }; 34 | -------------------------------------------------------------------------------- /Random_700_Qs/e_Fifth_100/q_a458.js: -------------------------------------------------------------------------------- 1 | /* 2 | Two Sum II - Input array is sorted 3 | 4 | Given an array of integers numbers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. 5 | 6 | Return the indices of the two numbers (1-indexed) as an integer array answer of size 2, where 1 <= answer[0] < answer[1] <= numbers.length. 7 | 8 | You may assume that each input would have exactly one solution and you may not use the same element twice. 9 | */ 10 | 11 | var twoSum = function (numbers, target) { 12 | let low = 0, 13 | high = numbers.length - 1; 14 | while (low < high) { 15 | let sum = numbers[low] + numbers[high]; 16 | if (sum > target) { 17 | high--; 18 | } else if (sum < target) { 19 | low++; 20 | } else { 21 | return [low + 1, high + 1]; 22 | } 23 | } 24 | return [-1, -1]; 25 | // Two pointer 26 | // T.C: O(N) 27 | // S.C: O(1) 28 | }; 29 | -------------------------------------------------------------------------------- /Random_700_Qs/e_Fifth_100/q_a460.js: -------------------------------------------------------------------------------- 1 | /* 2 | Is Unique 3 | 4 | Implement an algorithm to determine if a string has all unique characters. 5 | 6 | What if you cannot use additional data structures? 7 | */ 8 | 9 | /* 10 | Qs: 11 | 1. Is the given string an ASCII string or an Unicode string? 12 | 13 | ASCII: 128 characters 14 | Extended ASCII: 256 characters 15 | Unicode: 143,859 characters 16 | */ 17 | 18 | // Assume that the given string is an ASCII string 19 | const isUnique = (str) => { 20 | let arr = new Array(128).fill(false); 21 | for (let i = 0; i < str.length; i++) { 22 | let charCode = str[i].charCodeAt(); 23 | if (arr[charCode]) { 24 | return false; 25 | } 26 | arr[charCode] = true; 27 | } 28 | return true; 29 | // T.C: O(N) 30 | // S.C: O(1) 31 | }; 32 | 33 | console.log(isUnique("abca")); 34 | console.log(isUnique("abc")); 35 | -------------------------------------------------------------------------------- /Random_700_Qs/e_Fifth_100/q_a465.js: -------------------------------------------------------------------------------- 1 | /* 2 | String Compression 3 | 4 | Implement a method to perform basic string compression using the counts of repeated characters. 5 | 6 | For example, the string aabcccccaaa would become a2blc5a3. 7 | 8 | If the "compressed" string would not become smaller than the original string, 9 | 10 | your method should return the original string. 11 | 12 | You can assume the string has only uppercase and lowercase letters (a - z). 13 | */ 14 | -------------------------------------------------------------------------------- /Random_700_Qs/e_Fifth_100/q_a466.js: -------------------------------------------------------------------------------- 1 | /* 2 | Rotate Matrix 3 | 4 | Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, 5 | 6 | write a method to rotate the image by 90 degrees. 7 | 8 | Can you do this in place? 9 | */ 10 | -------------------------------------------------------------------------------- /Random_700_Qs/e_Fifth_100/q_a467.js: -------------------------------------------------------------------------------- 1 | /* 2 | Zero Matrix 3 | 4 | Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column are set to 0. 5 | */ 6 | -------------------------------------------------------------------------------- /Random_700_Qs/e_Fifth_100/q_a468.js: -------------------------------------------------------------------------------- 1 | /* 2 | String Rotation 3 | 4 | Assume you have a method isSubstringwhich checks if one word is a substring of another. 5 | 6 | Given two strings, sl and s2, write code to check if s2 is a rotation of sl using only one call to isSubstring (e.g.,"waterbottle" is a rotation of"erbottlewat"). 7 | */ 8 | -------------------------------------------------------------------------------- /Random_700_Qs/e_Fifth_100/q_a470.js: -------------------------------------------------------------------------------- 1 | /* 2 | Number of Islands II 3 | 4 | You are given an empty 2D binary grid grid of size m x n. 5 | 6 | The grid represents a map where 0's represent water and 1's represent land. Initially, all the cells of grid are water cells (i.e., all the cells are 0's). 7 | 8 | We may perform an add land operation which turns the water at position into a land. 9 | 10 | You are given an array positions where positions[i] = [ri, ci] is the position (ri, ci) at which we should operate the ith operation. 11 | 12 | Return an array of integers answer where answer[i] is the number of islands after turning the cell (ri, ci) into a land. 13 | 14 | An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. 15 | */ 16 | -------------------------------------------------------------------------------- /Random_700_Qs/e_Fifth_100/q_a474.js: -------------------------------------------------------------------------------- 1 | /* 2 | Validate Binary Search Tree 3 | 4 | Given the root of a binary tree, determine if it is a valid binary search tree (BST). 5 | 6 | A valid BST is defined as follows: 7 | 8 | The left subtree of a node contains only nodes with keys less than the node's key. 9 | The right subtree of a node contains only nodes with keys greater than the node's key. 10 | Both the left and right subtrees must also be binary search trees. 11 | */ 12 | 13 | var isValidBST = function (root, parentVal) { 14 | return isValidBSTHelper(root, -Infinity, Infinity); 15 | // T.C: O(N) 16 | // S.C: O(H), call stack can go as deep as the height of tree 17 | }; 18 | 19 | const isValidBSTHelper = (root, low, high) => { 20 | if (!root) { 21 | return true; 22 | } 23 | return ( 24 | root.val > low && 25 | root.val < high && 26 | isValid(root.left, low, root.val) && 27 | isValid(root.right, root.val, high) 28 | ); 29 | }; 30 | -------------------------------------------------------------------------------- /Random_700_Qs/e_Fifth_100/q_a475.js: -------------------------------------------------------------------------------- 1 | /* 2 | Invert Binary Tree 3 | 4 | Given the root of a binary tree, invert the tree, and return its root. 5 | */ 6 | 7 | /* 8 | The inverse of a tree with root r and left subtree l1 and right subtree r1 9 | is a tree with root r with an inverse of r1 as left subtree and an inverse of l1 as right subtree. 10 | */ 11 | var invertTree = function (root) { 12 | if (!root) { 13 | return null; 14 | } 15 | let invertedLeft = invertTree(root.left); 16 | let invertedRight = invertTree(root.right); 17 | root.left = invertedRight; 18 | root.right = invertedLeft; 19 | return root; 20 | // T.C: O(N) 21 | // S.C: O(H) 22 | }; 23 | -------------------------------------------------------------------------------- /Random_700_Qs/e_Fifth_100/q_a476.js: -------------------------------------------------------------------------------- 1 | /* 2 | Binary Tree Level Order Traversal II 3 | 4 | Given the root of a binary tree, return the bottom-up level order traversal of its nodes' values. 5 | 6 | (i.e., from left to right, level by level from leaf to root). 7 | */ 8 | 9 | var levelOrderBottom = function (root) { 10 | if (!root) { 11 | return []; 12 | } 13 | let res = []; 14 | let queue = []; // temporarily store the next nodes to visit 15 | queue.push(root); 16 | while (queue.length > 0) { 17 | let len = queue.length; 18 | let nodeValsInCurLevel = []; 19 | for (let i = 0; i < len; i++) { 20 | let node = queue.shift(); 21 | nodeValsInCurLevel.push(node.val); 22 | if (node.left) { 23 | queue.push(node.left); 24 | } 25 | if (node.right) { 26 | queue.push(node.right); 27 | } 28 | } 29 | res.push(nodeValsInCurLevel); 30 | } 31 | res.reverse(); 32 | return res; 33 | // T.C: O(N) 34 | // S.C: O(N) 35 | }; 36 | -------------------------------------------------------------------------------- /Random_700_Qs/e_Fifth_100/q_a482.js: -------------------------------------------------------------------------------- 1 | /* 2 | N-ary Tree Preorder Traversal 3 | 4 | Given the root of an n-ary tree, return the preorder traversal of its nodes' values. 5 | 6 | N-ary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples) 7 | */ 8 | 9 | var preorder = function (root) { 10 | let res = []; 11 | dfsTraversal(root, res); 12 | return res; 13 | // T.C: O(N) 14 | // S.C: O(H) 15 | }; 16 | 17 | const dfsTraversal = (root, values) => { 18 | if (!root) { 19 | return; 20 | } 21 | values.push(root.val); 22 | for (let i = 0; i < root.children.length; i++) { 23 | dfsTraversal(root.children[i], values); 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Random_700_Qs/e_Fifth_100/q_a483.js: -------------------------------------------------------------------------------- 1 | /* 2 | N-ary Tree Postorder Traversal 3 | 4 | Given the root of an n-ary tree, return the postorder traversal of its nodes' values. 5 | 6 | Nary-Tree input serialization is represented in their level order traversal. 7 | 8 | Each group of children is separated by the null value (See examples) 9 | */ 10 | 11 | var postorder = function (root) { 12 | let values = []; 13 | dfsTraversal(root, values); 14 | return values; 15 | // T.C: O(N) 16 | // S.C: O(H) 17 | }; 18 | 19 | const dfsTraversal = (root, values) => { 20 | if (!root) { 21 | return; 22 | } 23 | for (let i = 0; i < root.children.length; i++) { 24 | dfsTraversal(root.children[i], values); 25 | } 26 | values.push(root.val); 27 | }; 28 | -------------------------------------------------------------------------------- /Random_700_Qs/e_Fifth_100/q_a484.js: -------------------------------------------------------------------------------- 1 | /* 2 | Search in a Binary Search Tree 3 | 4 | You are given the root of a binary search tree (BST) and an integer val. 5 | 6 | Find the node in the BST that the node's value equals val and return the subtree rooted with that node. 7 | 8 | If such a node does not exist, return null. 9 | */ 10 | 11 | var searchBST = function (root, val) { 12 | if (!root) { 13 | return null; 14 | } 15 | if (root.val === val) { 16 | return root; 17 | } else if (root.val < val) { 18 | return searchBST(root.right, val); 19 | } else { 20 | return searchBST(root.left, val); 21 | } 22 | // T.C: O(log(N)) 23 | // S.C: O(H) 24 | }; 25 | -------------------------------------------------------------------------------- /Random_700_Qs/e_Fifth_100/q_a488.js: -------------------------------------------------------------------------------- 1 | /* 2 | Maximum Depth of N-ary Tree 3 | 4 | Given a n-ary tree, find its maximum depth. 5 | 6 | The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 7 | 8 | Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples). 9 | */ 10 | 11 | var maxDepth = function (root) { 12 | if (!root) { 13 | return 0; 14 | } 15 | let max = 0; 16 | for (let i = 0; i < root.children.length; i++) { 17 | max = Math.max(max, maxDepth(root.children[i])); 18 | } 19 | return max + 1; 20 | // T.C: O(N) 21 | // S.C: O(H) 22 | }; 23 | -------------------------------------------------------------------------------- /Random_700_Qs/e_Fifth_100/q_a491.js: -------------------------------------------------------------------------------- 1 | /* 2 | Reverse Linked List 3 | 4 | Given the head of a singly linked list, reverse the list, and return the reversed list. 5 | */ 6 | 7 | var reverseList = function (head) { 8 | let prev = null; 9 | let cur = head; 10 | while (cur !== null) { 11 | let next = cur.next; 12 | cur.next = prev; 13 | prev = cur; 14 | cur = next; 15 | } 16 | return prev; 17 | // T.C: O(N) 18 | // S.C: O(1) 19 | }; 20 | -------------------------------------------------------------------------------- /Random_700_Qs/e_Fifth_100/q_a496.js: -------------------------------------------------------------------------------- 1 | /* 2 | Remove Linked List Elements 3 | 4 | Given the head of a linked list and an integer val, 5 | 6 | remove all the nodes of the linked list that has Node.val == val, and return the new head. 7 | */ 8 | 9 | // We keep track of previous node, so that when we encounter a node with val, 10 | // we set prev node's next pointer to next node 11 | // if prev is null, next node becomes the new head 12 | var removeElements = function (head, val) { 13 | if (!head) { 14 | return null; 15 | } 16 | let prev = null, 17 | cur = head; 18 | while (cur !== null) { 19 | if (cur.val === val) { 20 | if (prev) { 21 | prev.next = cur.next; 22 | } else { 23 | head = cur.next; 24 | } 25 | // we do not update prev here because this node is not part of list 26 | } else { 27 | prev = cur; 28 | } 29 | cur = cur.next; 30 | } 31 | return head; 32 | // T.C: O(N) 33 | // S.C: O(1) 34 | }; 35 | -------------------------------------------------------------------------------- /Random_700_Qs/f_Sixth_100/q_a503.js: -------------------------------------------------------------------------------- 1 | /* 2 | Remove Duplicates from Sorted List 3 | 4 | Given the head of a sorted linked list, delete all duplicates such that each element appears only once. 5 | 6 | Return the linked list sorted as well. 7 | */ 8 | 9 | /* 10 | Solution 11 | 12 | 1. We keep track of previous node 13 | 2. If prev's value == cur's value 14 | set prev node point to next node 15 | */ 16 | var deleteDuplicates = function (head) { 17 | if (!head) { 18 | return null; 19 | } 20 | let prev = null, 21 | cur = head; 22 | while (cur !== null) { 23 | if (prev && prev.val === cur.val) { 24 | prev.next = cur.next; 25 | // prev node stays the same because current node is not part of list 26 | } else { 27 | prev = cur; 28 | } 29 | cur = cur.next; 30 | } 31 | return head; 32 | // T.C: O(N) 33 | // S.C: O(1) 34 | }; 35 | -------------------------------------------------------------------------------- /Random_700_Qs/f_Sixth_100/q_a505.js: -------------------------------------------------------------------------------- 1 | /* 2 | Convert Binary Number in a Linked List to Integer 3 | 4 | Given head which is a reference node to a singly-linked list. 5 | 6 | The value of each node in the linked list is either 0 or 1. 7 | 8 | The linked list holds the binary representation of a number. 9 | 10 | Return the decimal value of the number in the linked list. 11 | */ 12 | 13 | var getDecimalValue = function (head) { 14 | let cur = reverseList(head); 15 | let pow = 0; 16 | let sum = 0; 17 | while (cur !== null) { 18 | if (cur.val === 1) { 19 | sum += 2 ** pow; 20 | } 21 | pow++; 22 | cur = cur.next; 23 | } 24 | return sum; 25 | // T.C: O(2N) = O(N) 26 | // S.C: O(1) 27 | }; 28 | 29 | const reverseList = (head) => { 30 | if (!head) { 31 | return null; 32 | } 33 | let prev = null, 34 | cur = head; 35 | while (cur !== null) { 36 | let next = cur.next; 37 | cur.next = prev; 38 | prev = cur; 39 | cur = next; 40 | } 41 | return prev; 42 | }; 43 | -------------------------------------------------------------------------------- /Random_700_Qs/f_Sixth_100/q_a514.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers where each element appears twice except one, find the element which appears once. 3 | */ 4 | 5 | /* 6 | Solution 7 | 8 | Get the XOR of every number in given array and we will be left with the one element that appears once only. 9 | Every number occurring twice results in zero because x XOR x is zero. 10 | */ 11 | const findOneElement = (nums) => { 12 | let xor = 0; 13 | for (let i = 0; i < nums.length; i++) { 14 | xor = xor ^ nums[i]; 15 | } 16 | return xor; 17 | // T.C: O(N) 18 | // S.C: O(1) 19 | }; 20 | 21 | console.log(findOneElement([3, 7, 3, 5, 5])); 22 | -------------------------------------------------------------------------------- /Random_700_Qs/f_Sixth_100/q_a518.js: -------------------------------------------------------------------------------- 1 | /* 2 | Best Time to Buy and Sell Stock 3 | 4 | You are given an array prices where prices[i] is the price of a given stock on the ith day. 5 | 6 | You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. 7 | 8 | Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. 9 | */ 10 | 11 | var maxProfit = function (prices) { 12 | if (prices === null || prices.length === 0) return 0; 13 | let buyingPrice = prices[0]; 14 | let maxProfit = 0; 15 | for (let i = 1; i < prices.length; i++) { 16 | let possibleProfit = prices[i] - buyingPrice; 17 | maxProfit = Math.max(maxProfit, possibleProfit); 18 | if (prices[i] < buyingPrice) { 19 | buyingPrice = prices[i]; 20 | } 21 | } 22 | return maxProfit; 23 | // T.C: O(N) 24 | // S.C: O(1) 25 | }; 26 | -------------------------------------------------------------------------------- /Random_700_Qs/f_Sixth_100/q_a529.js: -------------------------------------------------------------------------------- 1 | /* 2 | Container With Most Water 3 | 4 | Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). 5 | 6 | n vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0). 7 | 8 | Find two lines, which, together with the x-axis forms a container, such that the container contains the most water. 9 | 10 | Notice that you may not slant the container. 11 | */ 12 | 13 | var maxArea = function (height) { 14 | let low = 0, 15 | high = height.length - 1; 16 | let maxArea = 0; 17 | while (low < high) { 18 | let width = high - low; 19 | let area = width * Math.min(height[low], height[high]); 20 | maxArea = Math.max(maxArea, area); 21 | 22 | if (height[low] > height[high]) { 23 | high--; 24 | } else { 25 | low++; 26 | } 27 | } 28 | return maxArea; 29 | // T.C: O(N) 30 | // S.C: O(1) 31 | }; 32 | -------------------------------------------------------------------------------- /Random_700_Qs/f_Sixth_100/q_a536.js: -------------------------------------------------------------------------------- 1 | /* 2 | Longest Substring Without Repeating Characters 3 | 4 | Given a string s, find the length of the longest substring without repeating characters. 5 | */ 6 | 7 | var lengthOfLongestSubstring = function (s) { 8 | let start = 0, 9 | end = 0; 10 | let m = new Map(); 11 | let maxLen = 0; 12 | while (end < s.length) { 13 | while (start < end && m.get(s[end]) === 1) { 14 | m.set(s[start], m.get(s[start]) - 1); 15 | start++; 16 | } 17 | maxLen = Math.max(maxLen, end - start + 1); 18 | m.set(s[end], 1); 19 | end++; 20 | } 21 | return maxLen; 22 | // T.C: O(N) 23 | // S.C: O(N) 24 | }; 25 | -------------------------------------------------------------------------------- /Random_700_Qs/f_Sixth_100/q_a537.js: -------------------------------------------------------------------------------- 1 | /* 2 | Longest Repeating Character Replacement 3 | 4 | You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. 5 | 6 | You can perform this operation at most k times. 7 | 8 | Return the length of the longest substring containing the same letter you can get after performing the above operations. 9 | */ 10 | 11 | -------------------------------------------------------------------------------- /Random_700_Qs/f_Sixth_100/q_a543.js: -------------------------------------------------------------------------------- 1 | /* 2 | Beautiful Arrangement 3 | 4 | Suppose you have n integers labeled 1 through n. 5 | 6 | A permutation of those n integers perm (1-indexed) is considered a beautiful arrangement if for every i (1 <= i <= n), either of the following is true: 7 | 8 | perm[i] is divisible by i. 9 | i is divisible by perm[i]. 10 | Given an integer n, return the number of the beautiful arrangements that you can construct. 11 | */ 12 | -------------------------------------------------------------------------------- /Random_700_Qs/f_Sixth_100/q_a544.js: -------------------------------------------------------------------------------- 1 | /* 2 | Maximum Length of a Concatenated String with Unique Characters 3 | 4 | Given an array of strings arr. String s is a concatenation of a sub-sequence of arr which have unique characters. 5 | 6 | Return the maximum possible length of s. 7 | */ 8 | -------------------------------------------------------------------------------- /Random_700_Qs/f_Sixth_100/q_a546.js: -------------------------------------------------------------------------------- 1 | /* 2 | Subsets 3 | 4 | Given an integer array nums of unique elements, return all possible subsets (the power set). 5 | 6 | The solution set must not contain duplicate subsets. Return the solution in any order. 7 | */ 8 | 9 | /* 10 | Use DFS to find all possible combinations of length nums.length. 11 | Record all combinations in progress. 12 | */ 13 | var subsets = function (nums) { 14 | if (nums === null || nums.length === 0) { 15 | return []; 16 | } 17 | let res = []; 18 | dfsTraversal(nums, 0, [], res); 19 | return res; 20 | // T.C: O(n * 2^n), there are 2^n possible subsets; 21 | // we multiply n for copying subset to result array (slice()) 22 | // S.C: O(2^n) 23 | }; 24 | 25 | const dfsTraversal = (nums, curIdx, curPath, res) => { 26 | res.push(curPath.slice()); 27 | 28 | for (let i = curIdx; i < nums.length; i++) { 29 | curPath.push(nums[i]); 30 | 31 | dfsTraversal(nums, i + 1, curPath, res); 32 | 33 | curPath.pop(); 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /Random_700_Qs/f_Sixth_100/q_a547.js: -------------------------------------------------------------------------------- 1 | /* 2 | Permutations II 3 | 4 | Given a collection of numbers, nums, that might contain duplicates, 5 | 6 | return all possible unique permutations in any order. 7 | */ 8 | 9 | var permuteUnique = function (nums) { 10 | let map = new Map(); 11 | for (let i = 0; i < nums.length; i++) { 12 | map.set(nums[i], map.get(nums[i]) + 1 || 1); 13 | } 14 | let res = []; 15 | dfsTraversal(new Set(nums), [], res, map, nums.length); 16 | return res; 17 | // T.C: O(N!) 18 | // S.C: O(N) 19 | }; 20 | 21 | const dfsTraversal = (nums, curPath, res, map, targetLen) => { 22 | if (curPath.length === targetLen) { 23 | res.push(curPath.slice()); 24 | return; 25 | } 26 | for (let num of nums) { 27 | if (map.get(num) > 0) { 28 | curPath.push(num); 29 | map.set(num, map.get(num) - 1); 30 | 31 | dfsTraversal(nums, curPath, res, map, targetLen); 32 | 33 | curPath.pop(); 34 | map.set(num, map.get(num) + 1); 35 | } 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /Random_700_Qs/f_Sixth_100/q_a548.js: -------------------------------------------------------------------------------- 1 | /* 2 | Subsets II 3 | 4 | Given an integer array nums that may contain duplicates, return all possible subsets (the power set). 5 | 6 | The solution set must not contain duplicate subsets. Return the solution in any order. 7 | */ 8 | 9 | var subsetsWithDup = function (nums) { 10 | if (nums === null || nums.length === 0) { 11 | return []; 12 | } 13 | nums.sort((a, b) => a - b); 14 | let res = []; 15 | dfsTraversal(nums, 0, [], res); 16 | return res; 17 | // T.C: O(N * 2^N) 18 | // S.C: O(2^N) 19 | }; 20 | 21 | const dfsTraversal = (nums, curIdx, curPath, res) => { 22 | res.push(curPath.slice()); 23 | 24 | for (let i = curIdx; i < nums.length; i++) { 25 | // i > curIdx because without this we may skip necessary subsets 26 | if (i > curIdx && nums[i] === nums[i - 1]) { 27 | continue; 28 | } 29 | curPath.push(nums[i]); 30 | 31 | dfsTraversal(nums, i + 1, curPath, res); 32 | 33 | curPath.pop(); 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /Random_700_Qs/f_Sixth_100/q_a553.js: -------------------------------------------------------------------------------- 1 | /* 2 | Longest Increasing Subsequence 3 | 4 | Given an integer array nums, return the length of the longest strictly increasing subsequence. 5 | 6 | A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. 7 | 8 | For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7]. 9 | */ 10 | 11 | var lengthOfLIS = function (nums) { 12 | if (nums === null || nums.length === 0) { 13 | return 0; 14 | } 15 | let dp = new Array(nums.length); // dp[i] is the length of longest increasing subsequence "ending" at index i 16 | dp[0] = 1; 17 | for (let i = 1; i < nums.length; i++) { 18 | let maxLen = 1; 19 | for (let j = 0; j < i; j++) { 20 | if (nums[j] < nums[i]) { 21 | maxLen = Math.max(maxLen, dp[j] + 1); 22 | } 23 | } 24 | dp[i] = maxLen; 25 | } 26 | return Math.max(...dp); 27 | // T.C: O(N^2) 28 | // S.C: O(N) 29 | }; 30 | -------------------------------------------------------------------------------- /Random_700_Qs/f_Sixth_100/q_a557.js: -------------------------------------------------------------------------------- 1 | /* 2 | Delete and Earn 3 | 4 | Given an array nums of integers, you can perform operations on the array. 5 | 6 | In each operation, you pick any nums[i] and delete it to earn nums[i] points. After, you must delete every element equal to nums[i] - 1 or nums[i] + 1. 7 | 8 | You start with 0 points. Return the maximum number of points you can earn by applying such operations. 9 | */ 10 | -------------------------------------------------------------------------------- /Random_700_Qs/f_Sixth_100/q_a563.js: -------------------------------------------------------------------------------- 1 | /* 2 | Find All The Lonely Nodes 3 | 4 | In a binary tree, a lonely node is a node that is the only child of its parent node. 5 | 6 | The root of the tree is not lonely because it does not have a parent node. 7 | 8 | Given the root of a binary tree, return an array containing the values of all lonely nodes in the tree. 9 | 10 | Return the list in any order. 11 | */ 12 | 13 | /* 14 | Use DFS to traverse all nodes 15 | At every node, we check if it only has one child. If so, that child is a lonely node. 16 | */ 17 | var getLonelyNodes = function (root) { 18 | let res = []; 19 | dfsTraversal(root, res); 20 | return res; 21 | // T.C: O(N) 22 | // S.C: O(H) 23 | }; 24 | 25 | const dfsTraversal = (root, res) => { 26 | if (!root) { 27 | return; 28 | } 29 | if (root.left && !root.right) { 30 | res.push(root.left.val); 31 | } 32 | if (!root.left && root.right) { 33 | res.push(root.right.val); 34 | } 35 | dfsTraversal(root.left, res); 36 | dfsTraversal(root.right, res); 37 | }; 38 | -------------------------------------------------------------------------------- /Random_700_Qs/f_Sixth_100/q_a565.js: -------------------------------------------------------------------------------- 1 | /* 2 | N-ary Tree Preorder Traversal 3 | 4 | Given the root of an n-ary tree, return the preorder traversal of its nodes' values. 5 | 6 | Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples) 7 | */ 8 | 9 | var preorder = function (root) { 10 | let res = []; 11 | dfsTraversal(root, res); 12 | return res; 13 | // T.C: O(N) 14 | // S.C: O(H) 15 | }; 16 | 17 | const dfsTraversal = (root, res) => { 18 | if (!root) { 19 | return; 20 | } 21 | res.push(root.val); 22 | for (let i = 0; i < root.children.length; i++) { 23 | dfsTraversal(root.children[i], res); 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Random_700_Qs/f_Sixth_100/q_a568.js: -------------------------------------------------------------------------------- 1 | /* 2 | Binary Tree Postorder Traversal 3 | 4 | Given the root of a binary tree, return the postorder traversal of its nodes' values. 5 | */ 6 | 7 | var postorderTraversal = function (root) { 8 | if (!root) { 9 | return []; 10 | } 11 | let res = []; 12 | dfsTraversal(root, res); 13 | return res; 14 | // T.C: O(N) 15 | // S.C: O(H) 16 | }; 17 | 18 | const dfsTraversal = (root, res) => { 19 | if (!root) { 20 | return; 21 | } 22 | dfsTraversal(root.left, res); 23 | dfsTraversal(root.right, res); 24 | res.push(root.val); 25 | }; 26 | -------------------------------------------------------------------------------- /Random_700_Qs/f_Sixth_100/q_a570.js: -------------------------------------------------------------------------------- 1 | /* 2 | N-ary Tree Postorder Traversal 3 | 4 | Given the root of an n-ary tree, return the postorder traversal of its nodes' values. 5 | 6 | Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples) 7 | */ 8 | 9 | var postorder = function (root) { 10 | let res = []; 11 | dfs(root, res); 12 | return res; 13 | // T.C: O(N) 14 | // S.C: O(H) 15 | }; 16 | 17 | const dfs = (root, res) => { 18 | if (!root) { 19 | return; 20 | } 21 | for (let i = 0; i < root.children.length; i++) { 22 | dfs(root.children[i], res); 23 | } 24 | res.push(root.val); 25 | }; 26 | -------------------------------------------------------------------------------- /Random_700_Qs/f_Sixth_100/q_a573.js: -------------------------------------------------------------------------------- 1 | /* 2 | Univalued Binary Tree 3 | 4 | A binary tree is univalued if every node in the tree has the same value. 5 | 6 | Return true if and only if the given tree is univalued. 7 | */ 8 | 9 | var isUnivalTree = function (root) { 10 | if (!root) { 11 | return false; 12 | } 13 | return dfsTraversal(root, root.val); 14 | // T.C: O(N) 15 | // S.C: O(H) 16 | }; 17 | 18 | const dfsTraversal = (root, val) => { 19 | if (!root) { 20 | return; 21 | } 22 | if (root.val !== val) { 23 | return false; 24 | } 25 | if ( 26 | dfsTraversal(root.left, val) === false || 27 | dfsTraversal(root.right, val) === false 28 | ) { 29 | return false; 30 | } 31 | return true; 32 | }; 33 | -------------------------------------------------------------------------------- /Random_700_Qs/f_Sixth_100/q_a577.js: -------------------------------------------------------------------------------- 1 | /* 2 | Increasing Order Search Tree 3 | 4 | Given the root of a binary search tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, 5 | 6 | and every node has no left child and only one right child. 7 | */ 8 | 9 | var increasingBST = function (root) { 10 | let dummyRoot = new TreeNode(); 11 | let cur = dummyRoot; 12 | dfs(root); 13 | return dummyRoot.right; 14 | // T.C: O(N) 15 | // S.C: O(H) 16 | function dfs(root) { 17 | if (!root) { 18 | return; 19 | } 20 | 21 | dfs(root.left); 22 | cur.right = root; 23 | cur = cur.right; 24 | cur.left = null; 25 | dfs(root.right); 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Random_700_Qs/f_Sixth_100/q_a580.js: -------------------------------------------------------------------------------- 1 | /* 2 | Construct Binary Tree from Inorder and Postorder Traversal 3 | 4 | Given two integer arrays inorder and postorder 5 | 6 | where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, 7 | 8 | construct and return the binary tree. 9 | */ 10 | 11 | var buildTree = function (inorder, postorder) { 12 | let m = new Map(); 13 | for (let i = 0; i < inorder.length; i++) { 14 | m.set(inorder[i], i); 15 | } 16 | return dfs(0, postorder.length - 1); 17 | function dfs(start, end) { 18 | if (start > end) return null; 19 | let root = new TreeNode(postorder.pop()); 20 | let idx = m.get(root.val); 21 | root.right = dfs(idx + 1, end); // since we are traversing backwards 22 | root.left = dfs(start, idx - 1); 23 | return root; 24 | } 25 | // T.C: O(N) 26 | // S.C: O(N) 27 | }; 28 | -------------------------------------------------------------------------------- /Random_700_Qs/f_Sixth_100/q_a582.js: -------------------------------------------------------------------------------- 1 | /* 2 | Path Sum 3 | 4 | Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum. 5 | 6 | A leaf is a node with no children. 7 | */ 8 | 9 | /* 10 | 1. Use DFS to try all possible paths. 11 | 2. Keep track of the sum of path during traversal. When leaf node is reached, check if 12 | the sum of path equals the target. If so, return true, else continue DFS traversal to 13 | try other paths. 14 | */ 15 | var hasPathSum = function (root, targetSum) { 16 | return dfs(root, targetSum); 17 | // T.C: O(N) 18 | // S.C: O(H) 19 | }; 20 | 21 | const dfs = (root, target) => { 22 | if (!root) { 23 | return false; 24 | } 25 | if (!root.left && !root.right) { 26 | return target - root.val === 0; 27 | } 28 | return ( 29 | dfs(root.left, target - root.val) || dfs(root.right, target - root.val) 30 | ); 31 | }; 32 | -------------------------------------------------------------------------------- /Random_700_Qs/f_Sixth_100/q_a585.js: -------------------------------------------------------------------------------- 1 | /* 2 | Same Tree 3 | 4 | Given the roots of two binary trees p and q, write a function to check if they are the same or not. 5 | 6 | Two binary trees are considered the same if they are structurally identical, and the nodes have the same value. 7 | */ 8 | 9 | /* 10 | Use DFS to traverse two trees simultaneously 11 | If all corresponding nodes don't have the same values, they are not the same 12 | */ 13 | var isSameTree = function (p, q) { 14 | return dfs(p, q); 15 | // T.C: O(N) 16 | // S.C: O(H) 17 | }; 18 | 19 | const dfs = (root1, root2) => { 20 | if (!root1 && !root2) { 21 | return true; 22 | } 23 | if (!root1 || !root2 || root1.val !== root2.val) { 24 | return false; 25 | } 26 | return dfs(root1.left, root2.left) && dfs(root1.right, root2.right); 27 | }; 28 | -------------------------------------------------------------------------------- /Random_700_Qs/f_Sixth_100/q_a587.js: -------------------------------------------------------------------------------- 1 | /* 2 | Closest Binary Search Tree Value 3 | 4 | Given the root of a binary search tree and a target value, return the value in the BST that is closest to the target. 5 | */ 6 | 7 | var closestValue = function (root, target) { 8 | if (root === null || target === null) { 9 | return null; 10 | } 11 | return dfs(root, target, root.val); 12 | // T.C: O(log(N)) 13 | // S.C: O(H) 14 | }; 15 | 16 | const dfs = (root, target, closest) => { 17 | if (!root) { 18 | return; 19 | } 20 | if (Math.abs(closest - target) > Math.abs(root.val - target)) { 21 | closest = root.val; 22 | } 23 | if (!root.left && !root.right) { 24 | return closest; 25 | } 26 | if (root.val > target) { 27 | let left = dfs(root.left, target, closest); 28 | if (left !== undefined) { 29 | closest = left; 30 | } 31 | } else { 32 | let right = dfs(root.right, target, closest); 33 | if (right !== undefined) { 34 | closest = right; 35 | } 36 | } 37 | return closest; 38 | }; 39 | -------------------------------------------------------------------------------- /Random_700_Qs/f_Sixth_100/q_a588.js: -------------------------------------------------------------------------------- 1 | /* 2 | Binary Tree Level Order Traversal II 3 | 4 | Given the root of a binary tree, return the bottom-up level order traversal of its nodes' values. (i.e., from left to right, level by level from leaf to root). 5 | */ 6 | 7 | var levelOrderBottom = function (root) { 8 | if (!root) { 9 | return []; 10 | } 11 | let queue = [], 12 | res = []; 13 | queue.push(root); 14 | while (queue.length > 0) { 15 | let queueLen = queue.length; 16 | let nodes = []; 17 | for (let i = 0; i < queueLen; i++) { 18 | let node = queue.shift(); 19 | nodes.push(node.val); 20 | if (node.left) { 21 | queue.push(node.left); 22 | } 23 | if (node.right) { 24 | queue.push(node.right); 25 | } 26 | } 27 | res.push(nodes); 28 | } 29 | res.reverse(); 30 | return res; 31 | // T.C: O(N) 32 | // S.C: O(N) 33 | }; 34 | -------------------------------------------------------------------------------- /Random_700_Qs/f_Sixth_100/q_a590.js: -------------------------------------------------------------------------------- 1 | /* 2 | Range Sum of BST 3 | 4 | Given the root node of a binary search tree and two integers low and high, 5 | 6 | return the sum of values of all nodes with a value in the inclusive range [low, high]. 7 | */ 8 | 9 | var rangeSumBST = function (root, low, high) { 10 | let sum = 0; 11 | dfs(root); 12 | return sum; 13 | // T.C: O(N) 14 | // S.C: O(H) 15 | function dfs(root) { 16 | if (!root) { 17 | return; 18 | } 19 | if (root.val < low) { 20 | dfs(root.right); 21 | } else if (root.val > high) { 22 | dfs(root.left); 23 | } else { 24 | sum += root.val; 25 | dfs(root.left); 26 | dfs(root.right); 27 | } 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /Random_700_Qs/f_Sixth_100/q_a591.js: -------------------------------------------------------------------------------- 1 | /* 2 | Maximum Depth of Binary Tree 3 | 4 | Given the root of a binary tree, return its maximum depth. 5 | 6 | A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 7 | */ 8 | 9 | /* 10 | Use DFS to try all possible paths. For each path, keep track of depth. 11 | When end of path is reached, update the global variable if the depth is the maximum. 12 | */ 13 | var maxDepth = function (root) { 14 | let max = 0; 15 | dfs(root, 1); 16 | return max; 17 | function dfs(root, depth) { 18 | if (!root) { 19 | return; 20 | } 21 | if (!root.left && !root.right) { 22 | max = Math.max(max, depth); 23 | } 24 | dfs(root.left, depth + 1); 25 | dfs(root.right, depth + 1); 26 | } 27 | // T.C: O(N) 28 | // S.C: O(H) 29 | }; 30 | -------------------------------------------------------------------------------- /Random_700_Qs/f_Sixth_100/q_a593.js: -------------------------------------------------------------------------------- 1 | /* 2 | Binary Tree Paths 3 | 4 | Given the root of a binary tree, return all root-to-leaf paths in any order. 5 | 6 | A leaf is a node with no children. 7 | */ 8 | 9 | /* 10 | Use DFS to try all possible paths. Keep track of path using string. Pass it to next node and 11 | if leaf node is reached, push the path string to the result array. 12 | */ 13 | var binaryTreePaths = function (root) { 14 | let res = []; 15 | dfs(root, "", res); 16 | return res; 17 | // T.C: O(N) 18 | // S.C: O(H) 19 | }; 20 | 21 | const dfs = (root, path, res) => { 22 | if (!root) { 23 | return; 24 | } 25 | if (!root.left && !root.right) { 26 | res.push(path + root.val); 27 | } 28 | dfs(root.left, path + root.val + "->", res); 29 | dfs(root.right, path + root.val + "->", res); 30 | }; 31 | -------------------------------------------------------------------------------- /Random_700_Qs/f_Sixth_100/q_a597.js: -------------------------------------------------------------------------------- 1 | /* 2 | Search in a Binary Search Tree 3 | 4 | You are given the root of a binary search tree (BST) and an integer val. 5 | 6 | Find the node in the BST that the node's value equals val and return the subtree rooted with that node. 7 | 8 | If such a node does not exist, return null. 9 | */ 10 | 11 | var searchBST = function (root, val) { 12 | return dfs(root, val); 13 | // T.C: O(log(N)) 14 | // S.C: O(H) 15 | }; 16 | 17 | const dfs = (root, target) => { 18 | if (!root) { 19 | return; 20 | } 21 | if (root.val > target) { 22 | let left = dfs(root.left, target); 23 | if (left) { 24 | return left; 25 | } 26 | } else if (root.val < target) { 27 | let right = dfs(root.right, target); 28 | if (right) { 29 | return right; 30 | } 31 | } else { 32 | return root; 33 | } 34 | return null; 35 | }; 36 | -------------------------------------------------------------------------------- /Random_700_Qs/f_Sixth_100/q_a600.js: -------------------------------------------------------------------------------- 1 | /* 2 | Minimum Depth of Binary Tree 3 | 4 | Given a binary tree, find its minimum depth. 5 | 6 | The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. 7 | 8 | Note: A leaf is a node with no children. 9 | */ 10 | 11 | /* 12 | Use DFS to find every possible path. For every path, keep track of depth and 13 | update the global variable for minimum depth when smaller depth is found. 14 | */ 15 | var minDepth = function (root) { 16 | let min = Infinity; 17 | dfs(root, 1); 18 | return min === Infinity ? 0 : min; 19 | function dfs(root, depth) { 20 | if (!root) { 21 | return; 22 | } 23 | if (!root.left && !root.right) { 24 | min = Math.min(min, depth); 25 | } 26 | dfs(root.left, depth + 1); 27 | dfs(root.right, depth + 1); 28 | } 29 | // T.C: O(N) 30 | // S.C: O(H) 31 | }; 32 | -------------------------------------------------------------------------------- /Random_700_Qs/g_Seventh_100/q_a601.js: -------------------------------------------------------------------------------- 1 | /* 2 | Flatten Binary Tree to Linked List 3 | 4 | Given the root of a binary tree, flatten the tree into a "linked list": 5 | 6 | The "linked list" should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null. 7 | The "linked list" should be in the same order as a pre-order traversal of the binary tree. 8 | */ 9 | -------------------------------------------------------------------------------- /Random_700_Qs/g_Seventh_100/q_a602.js: -------------------------------------------------------------------------------- 1 | /* 2 | Convert Sorted Array to Binary Search Tree 3 | 4 | Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree. 5 | 6 | A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one. 7 | */ 8 | 9 | var sortedArrayToBST = function (nums) { 10 | return buildTree(nums, 0, nums.length - 1); 11 | }; 12 | 13 | const buildTree = (nums, start, end) => { 14 | if (start > end) { 15 | return null; 16 | } 17 | let mid = start + Math.floor((end - start) / 2); 18 | let root = new TreeNode(nums[mid]); 19 | root.left = buildTree(nums, start, mid - 1); 20 | root.right = buildTree(nums, mid + 1, end); 21 | return root; 22 | }; 23 | -------------------------------------------------------------------------------- /Random_700_Qs/g_Seventh_100/q_a604.js: -------------------------------------------------------------------------------- 1 | /* 2 | Invert Binary Tree 3 | 4 | Given the root of a binary tree, invert the tree, and return its root. 5 | */ 6 | 7 | /* 8 | To invert a tree, we should swap the left subtree and the right subtree at every node of the 9 | tree. We do this in a bottom-up fashion using postorder traversal. 10 | */ 11 | var invertTree = function (root) { 12 | if (!root) { 13 | return null; 14 | } 15 | let left = invertTree(root.left); 16 | let right = invertTree(root.right); 17 | root.left = right; 18 | root.right = left; 19 | return root; 20 | // T.C: O(N) 21 | // S.C: O(H) 22 | }; 23 | -------------------------------------------------------------------------------- /Random_700_Qs/g_Seventh_100/q_a605.js: -------------------------------------------------------------------------------- 1 | /* 2 | Populating Next Right Pointers in Each Node 3 | 4 | You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition: 5 | 6 | struct Node { 7 | int val; 8 | Node *left; 9 | Node *right; 10 | Node *next; 11 | } 12 | Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. 13 | 14 | Initially, all next pointers are set to NULL. 15 | 16 | Follow up: 17 | 18 | You may only use constant extra space. 19 | Recursive approach is fine, you may assume implicit stack space does not count as extra space for this problem. 20 | */ 21 | -------------------------------------------------------------------------------- /Random_700_Qs/g_Seventh_100/q_a610.js: -------------------------------------------------------------------------------- 1 | /* 2 | Binary Tree Right Side View 3 | 4 | Given the root of a binary tree, imagine yourself standing on the right side of it, 5 | 6 | return the values of the nodes you can see ordered from top to bottom. 7 | */ 8 | 9 | /* 10 | Use DFS to traverse all nodes. We'll traverse nodes in preorder but prioritise right node 11 | over left node (root - right - left). We will keep track of depth at each node. Only nodes with depth greater than global maximum depth will be pushed to result array (only these can be seen from the right side). 12 | */ 13 | var rightSideView = function (root) { 14 | let res = []; 15 | dfs(root, 1, res); 16 | return res; 17 | // T.C: O(N) 18 | // S.C: O(H) 19 | }; 20 | 21 | // length of result array tells the maximum depth 22 | const dfs = (root, depth, res) => { 23 | if (!root) { 24 | return; 25 | } 26 | if (depth > res.length) { 27 | res.push(root.val); 28 | } 29 | dfs(root.right, depth + 1, res); 30 | dfs(root.left, depth + 1, res); 31 | }; 32 | -------------------------------------------------------------------------------- /Random_700_Qs/g_Seventh_100/q_a613.js: -------------------------------------------------------------------------------- 1 | /* 2 | Binary Search Tree Iterator 3 | 4 | Implement the BSTIterator class that represents an iterator over the in-order traversal of a binary search tree (BST): 5 | 6 | BSTIterator(TreeNode root) Initializes an object of the BSTIterator class. 7 | 8 | The root of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST. 9 | boolean hasNext() Returns true if there exists a number in the traversal to the right of the pointer, otherwise returns false. 10 | int next() Moves the pointer to the right, then returns the number at the pointer. 11 | Notice that by initializing the pointer to a non-existent smallest number, the first call to next() will return the smallest element in the BST. 12 | 13 | You may assume that next() calls will always be valid. That is, there will be at least a next number in the in-order traversal when next() is called. 14 | */ 15 | -------------------------------------------------------------------------------- /Random_700_Qs/g_Seventh_100/q_a614.js: -------------------------------------------------------------------------------- 1 | /* 2 | Construct Binary Tree from Inorder and Postorder Traversal 3 | 4 | Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, 5 | 6 | construct and return the binary tree. 7 | */ 8 | 9 | var buildTree = function (inorder, postorder) { 10 | let m = new Map(); 11 | for (let i = 0; i < inorder.length; i++) { 12 | m.set(inorder[i], i); 13 | } 14 | return dfs(0, postorder.length - 1); 15 | function dfs(start, end) { 16 | if (start > end) return null; 17 | let root = new TreeNode(postorder.pop()); 18 | let idx = m.get(root.val); 19 | root.right = dfs(idx + 1, end); // since we are traversing backwards 20 | root.left = dfs(start, idx - 1); 21 | return root; 22 | } 23 | // T.C: O(N) 24 | // S.C: O(N) 25 | }; 26 | -------------------------------------------------------------------------------- /Random_700_Qs/g_Seventh_100/q_a621.js: -------------------------------------------------------------------------------- 1 | /* 2 | Counting Bits 3 | 4 | Given an integer num, return an array of the number of 1's in the binary representation of every number in the range [0, num]. 5 | */ 6 | -------------------------------------------------------------------------------- /Random_700_Qs/g_Seventh_100/q_a622.js: -------------------------------------------------------------------------------- 1 | /* 2 | Count Numbers with Unique Digits 3 | 4 | Given an integer n, return the count of all numbers with unique digits, x, where 0 <= x < 10^n. 5 | */ 6 | -------------------------------------------------------------------------------- /Random_700_Qs/g_Seventh_100/q_a624.js: -------------------------------------------------------------------------------- 1 | /* 2 | Integer Break 3 | 4 | Given an integer n, break it into the sum of k positive integers, where k >= 2, and maximize the product of those integers. 5 | 6 | Return the maximum product you can get. 7 | */ 8 | 9 | var integerBreak = function (n) { 10 | if (n < 2) { 11 | return -1; 12 | } 13 | return dfs(n, new Map()); 14 | // T.C: O(N^2) 15 | // S.C: O(N^2) 16 | }; 17 | 18 | // returns the possible maximum product 19 | const dfs = (n, memo) => { 20 | if (n === 1) { 21 | return 1; 22 | } 23 | if (memo.has(n)) { 24 | return memo.get(n); 25 | } 26 | let max = 0; 27 | for (let i = 1; i < n; i++) { 28 | max = Math.max(max, i * Math.max(n - i, dfs(n - i, memo))); 29 | } 30 | memo.set(n, max); 31 | return max; 32 | }; 33 | -------------------------------------------------------------------------------- /Random_700_Qs/g_Seventh_100/q_a625.js: -------------------------------------------------------------------------------- 1 | /* 2 | Unique Binary Search Trees 3 | 4 | Given an integer n, return the number of structurally unique BST's (binary search trees) which has exactly n nodes of unique values from 1 to n. 5 | */ 6 | 7 | var numTrees = function (n) { 8 | return numberOfBSTs(1, n, new Map()); 9 | // T.C: O(N^2) 10 | // S.C: O(N^2) 11 | }; 12 | 13 | const numberOfBSTs = (low, high, memo) => { 14 | if (low > high) { 15 | return 1; 16 | } 17 | if (memo.has(`${low}-${high}`)) { 18 | return memo.get(`${low}-${high}`); 19 | } 20 | let total = 0; 21 | for (let i = low; i <= high; i++) { 22 | let left = numberOfBSTs(low, i - 1, memo); 23 | let right = numberOfBSTs(i + 1, high, memo); 24 | total += left * right; 25 | } 26 | memo.set(`${low}-${high}`, total); 27 | return total; 28 | }; 29 | -------------------------------------------------------------------------------- /Random_700_Qs/g_Seventh_100/q_a630.js: -------------------------------------------------------------------------------- 1 | /* 2 | Longest Duplicate Substring 3 | 4 | Given a string s, consider all duplicated substrings: (contiguous) substrings of s that occur 2 or more times. 5 | 6 | The occurrences may overlap. 7 | 8 | Return any duplicated substring that has the longest possible length. 9 | 10 | If s does not have a duplicated substring, the answer is "". 11 | */ 12 | -------------------------------------------------------------------------------- /Random_700_Qs/g_Seventh_100/q_a631.js: -------------------------------------------------------------------------------- 1 | /* 2 | Longest Repeating Substring 3 | 4 | Given a string s, find out the length of the longest repeating substring(s). Return 0 if no repeating substring exists. 5 | */ 6 | -------------------------------------------------------------------------------- /Random_700_Qs/g_Seventh_100/q_a634.js: -------------------------------------------------------------------------------- 1 | /* 2 | When passed a positive integer returns true if the decimal representation of that integer contains no odd digits and otherwise returns false. 3 | */ 4 | 5 | function onlyEvenDigits(n) { 6 | let onlyEvenDigits = true; 7 | while (n > 0) { 8 | let rightMostDigit = n % 10; 9 | if (rightMostDigit % 2 === 1) { 10 | onlyEvenDigits = false; 11 | break; 12 | } 13 | n = Math.floor(n / 10); 14 | } 15 | return onlyEvenDigits; 16 | // T.C: O(K), K = length of given number; for example, length of 333 is 3. 17 | // S.C: O(1) 18 | } 19 | 20 | console.log(onlyEvenDigits(22222)); 21 | // console.log(onlyEvenDigits(22220)); 22 | // console.log(onlyEvenDigits(10)); 23 | -------------------------------------------------------------------------------- /Random_700_Qs/g_Seventh_100/q_a635.js: -------------------------------------------------------------------------------- 1 | /* 2 | When passed a decimal digit X, return the value of X+XX+XXX+XXXX. 3 | 4 | E.g. if the supplied digit is 3 it should return 3702 (3+33+333+3333). 5 | */ 6 | 7 | /* 8 | In order to compute a new value, We repeatedly multiply10 to given number and add the previous value. 9 | Hence, we will keep track of previous value and add it to figure out the correct current value. 10 | */ 11 | function encodeNumber(X) { 12 | if (X === 0) return 0; 13 | let res = 0, prev = 0; 14 | for (let i = 0; i < 4; i++) { 15 | let cur = prev + X * Math.pow(10, i); 16 | res += cur; 17 | prev = cur; 18 | } 19 | return res; 20 | // T.C: O(1) 21 | // S.C: O(1) 22 | } 23 | 24 | console.log(encodeNumber(3)); 25 | -------------------------------------------------------------------------------- /Random_700_Qs/g_Seventh_100/q_a640.js: -------------------------------------------------------------------------------- 1 | /* 2 | Palindrome Partitioning 3 | 4 | Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s. 5 | 6 | A palindrome string is a string that reads the same backward as forward. 7 | */ 8 | -------------------------------------------------------------------------------- /Random_700_Qs/g_Seventh_100/q_a641.js: -------------------------------------------------------------------------------- 1 | /* 2 | Add Bold Tag in String 3 | 4 | Given a string s and a list of strings dict, you need to add a closed pair of bold tag and 5 | 6 | to wrap the substrings in s that exist in dict. 7 | 8 | If two such substrings overlap, you need to wrap them together by only one pair of closed bold tag. 9 | 10 | Also, if two substrings wrapped by bold tags are consecutive, you need to combine them. 11 | */ 12 | -------------------------------------------------------------------------------- /Random_700_Qs/g_Seventh_100/q_a642.js: -------------------------------------------------------------------------------- 1 | /* 2 | N-th Tribonacci Number 3 | 4 | The Tribonacci sequence Tn is defined as follows: 5 | 6 | T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0. 7 | 8 | Given n, return the value of Tn. 9 | */ 10 | -------------------------------------------------------------------------------- /Random_700_Qs/g_Seventh_100/q_a645.js: -------------------------------------------------------------------------------- 1 | /* 2 | Question Link: https://leetcode.com/discuss/interview-question/541160/Twilio-OA-2020 3 | */ 4 | function productSort(arr) { 5 | let m = new Map(); 6 | for (let i = 0; i < arr.length; i++) { 7 | m.set(arr[i], m.get(arr[i]) + 1 || 1); 8 | } 9 | m = Array.from(m.entries()); 10 | m.sort((a, b) => { 11 | if (a[1] === b[1]) return a[0] - b[0]; 12 | else return a[1] - b[1]; 13 | }); 14 | let res = []; 15 | for (let [num, freq] of m) { 16 | for (let i = 0; i < freq; i++) res.push(num); 17 | } 18 | return res; 19 | // T.C: O(Nlog(N)), N = length of arr 20 | // S.C: O(N) 21 | } 22 | 23 | console.log(productSort([4, 5, 6, 5, 4, 3])); 24 | -------------------------------------------------------------------------------- /Random_700_Qs/g_Seventh_100/q_a649.js: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program to print. 3 | [ * ] when n=1 4 | [[ * ]] when n=2 5 | [[[ * ]]] when n=3 6 | [[[[ * ]]]] when n=4 7 | */ 8 | 9 | function constructPattern(n) { 10 | if (n < 1) return null; 11 | let res = new Array(3 + n * 2); 12 | let mid = Math.floor(res.length / 2); 13 | res[mid] = "*"; 14 | res[mid - 1] = " "; 15 | res[mid + 1] = " "; 16 | let l = mid - 2; 17 | let r = mid + 2; 18 | while (l >= 0 && r < res.length) { 19 | res[l] = "["; 20 | res[r] = "]"; 21 | l--, r++; 22 | } 23 | return res.join(""); 24 | // T.C: O(N) 25 | // S.C: O(N) 26 | } 27 | 28 | console.log(constructPattern(1)); 29 | console.log(constructPattern(2)); 30 | console.log(constructPattern(3)); 31 | -------------------------------------------------------------------------------- /Random_700_Qs/g_Seventh_100/q_a650.js: -------------------------------------------------------------------------------- 1 | var countCharacters = function (words, chars) { 2 | if (words.length === 0 || chars.length === 0) { 3 | return 0; 4 | } 5 | let arr = new Array(26).fill(0); 6 | let count = 0; 7 | for (let i = 0; i < chars.length; i++) { 8 | let idx = chars.charCodeAt(i) - 97; 9 | arr[idx] += 1; 10 | } 11 | for (let i = 0; i < words.length; i++) { 12 | let isGood = true; 13 | for (let j = 0; j < words[i].length; j++) { 14 | let idx = words[i].charCodeAt(j) - 97; 15 | if (arr[idx] === 0) { 16 | isGood = false; 17 | } 18 | arr[idx]--; 19 | } 20 | if (isGood) count += words[i].length; 21 | for (let j = 0; j < words[i].length; j++) { 22 | let idx = words[i].charCodeAt(j) - 97; 23 | arr[idx]++; 24 | } 25 | } 26 | return count; 27 | // T.C: O(2N + M) = O(N + M), N = # of all characters in `words` array, M = length of `chars` 28 | // S.C: O(1) 29 | }; 30 | -------------------------------------------------------------------------------- /Topic-wise/Array&String/q_2.js: -------------------------------------------------------------------------------- 1 | /* 2 | Split Array Largest Sum 3 | 4 | Given an array nums which consists of non-negative integers and an integer m, 5 | 6 | you can split the array into m non-empty continuous subarrays. 7 | 8 | Write an algorithm to minimize the largest sum among these m subarrays. 9 | */ 10 | -------------------------------------------------------------------------------- /Topic-wise/Array&String/q_5.js: -------------------------------------------------------------------------------- 1 | /* 2 | Missing Number 3 | 4 | Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array. 5 | 6 | Follow up: Could you implement a solution using only O(1) extra space complexity and O(n) runtime complexity? 7 | */ 8 | 9 | var missingNumber = function (nums) { 10 | // total number of elements 11 | let N = nums.length; 12 | let numOfElements = N + 1; 13 | let sumFromZeroToN = (N / 2) * numOfElements; 14 | let arrSum = nums.reduce((acc, cur) => acc + cur); 15 | return sumFromZeroToN - arrSum; 16 | // T.C: O(N) 17 | // S.C: O(1) 18 | }; 19 | -------------------------------------------------------------------------------- /Topic-wise/DP/q_1.js: -------------------------------------------------------------------------------- 1 | /* 2 | Minimum Jumps to Reach Home 3 | 4 | A certain bug's home is on the x-axis at position x. Help them get there from position 0. 5 | 6 | The bug jumps according to the following rules: 7 | - It can jump exactly a positions forward (to the right). 8 | - It can jump exactly b positions backward (to the left). 9 | - It cannot jump backward twice in a row. 10 | - It cannot jump to any forbidden positions. 11 | 12 | The bug may jump forward beyond its home, but it cannot jump to positions numbered with negative integers. 13 | 14 | Given an array of integers forbidden, where forbidden[i] means that the bug cannot jump to the position forbidden[i], and integers a, b, and x, 15 | return the minimum number of jumps needed for the bug to reach its home. 16 | 17 | If there is no possible sequence of jumps that lands the bug on position x, return -1. 18 | */ 19 | -------------------------------------------------------------------------------- /Topic-wise/DP/q_2.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hbjORbj/interview_prep_javascript/06c8339bc6cac4b87f0da447d08cc4257823cea8/Topic-wise/DP/q_2.js -------------------------------------------------------------------------------- /Topic-wise/DP/q_3.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hbjORbj/interview_prep_javascript/06c8339bc6cac4b87f0da447d08cc4257823cea8/Topic-wise/DP/q_3.js -------------------------------------------------------------------------------- /Topic-wise/DP/q_4.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hbjORbj/interview_prep_javascript/06c8339bc6cac4b87f0da447d08cc4257823cea8/Topic-wise/DP/q_4.js -------------------------------------------------------------------------------- /Topic-wise/DP/q_5.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hbjORbj/interview_prep_javascript/06c8339bc6cac4b87f0da447d08cc4257823cea8/Topic-wise/DP/q_5.js -------------------------------------------------------------------------------- /Topic-wise/Queue&Stack/q_7.js: -------------------------------------------------------------------------------- 1 | /* 2 | Next Palindrome Using Same Digits 3 | 4 | You are given a numeric string num, representing a very large palindrome. 5 | 6 | Return the smallest palindrome larger than num that can be created by rearranging its digits. 7 | 8 | If no such palindrome exists, return an empty string "". 9 | 10 | A palindrome is a number that reads the same backward as forward. 11 | */ 12 | -------------------------------------------------------------------------------- /Topic-wise/Queue&Stack/q_9.js: -------------------------------------------------------------------------------- 1 | /* 2 | Score of Parentheses 3 | 4 | Given a balanced parentheses string s, compute the score of the string based on the following rule: 5 | 6 | () has score 1 7 | AB has score A + B, where A and B are balanced parentheses strings. 8 | (A) has score 2 * A, where A is a balanced parentheses string. 9 | */ 10 | -------------------------------------------------------------------------------- /Topic-wise/Queue&Stack/q_a10.js: -------------------------------------------------------------------------------- 1 | /* 2 | Minimum Cost Tree From Leaf Values 3 | 4 | Given an array arr of positive integers, consider all binary trees such that: 5 | 6 | - Each node has either 0 or 2 children 7 | - The values of arr correspond to the values of each leaf in an in-order traversal of the tree. (Recall that a node is a leaf if and only if it has 0 children.) 8 | - The value of each non-leaf node is equal to the product of the largest leaf value in its left and right subtree respectively. 9 | 10 | Among all possible binary trees considered, return the smallest possible sum of the values of each non-leaf node. It is guaranteed this sum fits into a 32-bit integer. 11 | */ 12 | -------------------------------------------------------------------------------- /Topic-wise/Queue&Stack/q_a14.js: -------------------------------------------------------------------------------- 1 | /* 2 | Shortest Subarray with Sum at Least K 3 | 4 | Return the length of the shortest, non-empty, contiguous subarray of nums with sum at least k. 5 | 6 | If there is no non-empty subarray with sum at least k, return -1. 7 | */ 8 | -------------------------------------------------------------------------------- /Topic-wise/Queue&Stack/q_a15.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hbjORbj/interview_prep_javascript/06c8339bc6cac4b87f0da447d08cc4257823cea8/Topic-wise/Queue&Stack/q_a15.js -------------------------------------------------------------------------------- /Topic-wise/Two_Pointers/q_a11.js: -------------------------------------------------------------------------------- 1 | /* 2 | Squares of a Sorted Array 3 | 4 | Given an integer array nums sorted in non-decreasing order, 5 | 6 | return an array of the squares of each number sorted in non-decreasing order. 7 | */ 8 | 9 | /* 10 | We will create a new array and fill it so that squared numbers are in 11 | descending order. We will then reverse it. 12 | 13 | The potential greatest number is the left-most number or the right-most number. 14 | We compare the squares of the two numbers and push the greater number into the result 15 | array. 16 | */ 17 | var sortedSquares = function (nums) { 18 | if (nums === null || nums.length === 0) { 19 | return nums; 20 | } 21 | let low = 0, 22 | high = nums.length - 1; 23 | let res = []; 24 | while (low <= high) { 25 | if (nums[low] ** 2 > nums[high] ** 2) { 26 | res.push(nums[low] ** 2); 27 | low++; 28 | } else { 29 | res.push(nums[high] ** 2); 30 | high--; 31 | } 32 | } 33 | res.reverse(); 34 | return res; 35 | // T.C: O(N) 36 | // S.C: O(N) 37 | }; 38 | -------------------------------------------------------------------------------- /Topic-wise/Two_Pointers/q_a18.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hbjORbj/interview_prep_javascript/06c8339bc6cac4b87f0da447d08cc4257823cea8/Topic-wise/Two_Pointers/q_a18.js -------------------------------------------------------------------------------- /Topic-wise/Two_Pointers/q_a19.js: -------------------------------------------------------------------------------- 1 | /* 2 | Fruit Into Baskets 3 | 4 | In a row of trees, the i-th tree produces fruit with type tree[i]. 5 | 6 | You start at any tree of your choice, then repeatedly perform the following steps: 7 | 8 | Add one piece of fruit from this tree to your baskets. If you cannot, stop. 9 | Move to the next tree to the right of the current tree. If there is no tree to the right, stop. 10 | Note that you do not have any choice after the initial choice of starting tree: you must perform step 1, then step 2, then back to step 1, then step 2, and so on until you stop. 11 | 12 | You have two baskets, and each basket can carry any quantity of fruit, but you want each basket to only carry one type of fruit each. 13 | 14 | What is the total amount of fruit you can collect with this procedure? 15 | */ 16 | -------------------------------------------------------------------------------- /Topic-wise/Two_Pointers/q_a20.js: -------------------------------------------------------------------------------- 1 | /* 2 | Minimum Number of K Consecutive Bit Flips 3 | 4 | In an array nums containing only 0s and 1s, a k-bit flip consists of choosing a (contiguous) subarray of length k 5 | 6 | and simultaneously changing every 0 in the subarray to 1, and every 1 in the subarray to 0. 7 | 8 | Return the minimum number of k-bit flips required so that there is no 0 in the array. If it is not possible, return -1. 9 | */ 10 | -------------------------------------------------------------------------------- /Topic-wise/Two_Pointers/q_a21.js: -------------------------------------------------------------------------------- 1 | /* 2 | Ways to Split Array Into Three Subarrays 3 | 4 | A split of an integer array is good if: 5 | 6 | The array is split into three non-empty contiguous subarrays - named left, mid, right respectively from left to right. 7 | 8 | The sum of the elements in left is less than or equal to the sum of the elements in mid, 9 | and the sum of the elements in mid is less than or equal to the sum of the elements in right. 10 | 11 | Given nums, an array of non-negative integers, return the number of good ways to split nums. 12 | 13 | As the number may be too large, return it modulo 109 + 7. 14 | */ -------------------------------------------------------------------------------- /Topic-wise/Two_Pointers/q_a23.js: -------------------------------------------------------------------------------- 1 | /* 2 | Count Number of Nice Subarrays 3 | 4 | Given an array of integers nums and an integer k. 5 | 6 | A continuous subarray is called nice if there are k odd numbers on it. 7 | 8 | Return the number of nice sub-arrays. 9 | */ 10 | -------------------------------------------------------------------------------- /Topic-wise/Two_Pointers/q_a24.js: -------------------------------------------------------------------------------- 1 | /* 2 | Subarrays with K Different Integers 3 | 4 | Given an array nums of positive integers, call a (contiguous, not necessarily distinct) subarray of nums good 5 | 6 | if the number of different integers in that subarray is exactly k. 7 | 8 | (For example, [1,2,3,1,2] has 3 different integers: 1, 2, and 3.) 9 | 10 | Return the number of good subarrays of nums. 11 | */ 12 | -------------------------------------------------------------------------------- /Topic-wise/Two_Pointers/q_a25.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hbjORbj/interview_prep_javascript/06c8339bc6cac4b87f0da447d08cc4257823cea8/Topic-wise/Two_Pointers/q_a25.js -------------------------------------------------------------------------------- /Topic-wise/Two_Pointers/q_a26.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hbjORbj/interview_prep_javascript/06c8339bc6cac4b87f0da447d08cc4257823cea8/Topic-wise/Two_Pointers/q_a26.js -------------------------------------------------------------------------------- /Topic-wise/Two_Pointers/q_a27.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hbjORbj/interview_prep_javascript/06c8339bc6cac4b87f0da447d08cc4257823cea8/Topic-wise/Two_Pointers/q_a27.js -------------------------------------------------------------------------------- /Topic-wise/Two_Pointers/q_a28.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hbjORbj/interview_prep_javascript/06c8339bc6cac4b87f0da447d08cc4257823cea8/Topic-wise/Two_Pointers/q_a28.js -------------------------------------------------------------------------------- /Topic-wise/Two_Pointers/q_a29.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hbjORbj/interview_prep_javascript/06c8339bc6cac4b87f0da447d08cc4257823cea8/Topic-wise/Two_Pointers/q_a29.js -------------------------------------------------------------------------------- /Topic-wise/Two_Pointers/q_a30.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hbjORbj/interview_prep_javascript/06c8339bc6cac4b87f0da447d08cc4257823cea8/Topic-wise/Two_Pointers/q_a30.js --------------------------------------------------------------------------------